mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
110
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f64da3ae0 | ||
|
|
1aec8e5394 | ||
|
|
326a4fe3d3 | ||
|
|
f9839ba369 | ||
|
|
e951eb134b | ||
|
|
6cbf007d72 | ||
|
|
07e9bc497d | ||
|
|
e4edb7cbdd | ||
|
|
ca2514c790 | ||
|
|
69c9938aba | ||
|
|
2fd42f2acd | ||
|
|
05630ec9eb | ||
|
|
d64fdb51be | ||
|
|
260d10b729 | ||
|
|
20657df203 | ||
|
|
f08ae1c76b | ||
|
|
4fc133c35e | ||
|
|
de38e60444 | ||
|
|
3c26004e04 | ||
|
|
d1534ebc92 | ||
|
|
20d4c3351e | ||
|
|
8a313b83b8 | ||
|
|
7eea72c415 | ||
|
|
e8ffa6efe3 | ||
|
|
baeecd2ddf | ||
|
|
d352731280 | ||
|
|
a0545286ee | ||
|
|
6f8ed793a7 | ||
|
|
b3c88ce2a6 | ||
|
|
d71c5635e3 | ||
|
|
755761d0de | ||
|
|
550e475962 | ||
|
|
2e6fcceb05 | ||
|
|
abcc816581 | ||
|
|
8353b791fb | ||
|
|
b81227b0ea | ||
|
|
a9fb982ab0 | ||
|
|
a822bfc99b | ||
|
|
1211de5a77 | ||
|
|
ee36692db7 | ||
|
|
ee43522019 | ||
|
|
b4dc30b84a | ||
|
|
73a6cca753 | ||
|
|
705bee7d56 | ||
|
|
5aa9b32283 | ||
|
|
711f378ae8 | ||
|
|
c29d56e2b3 | ||
|
|
d63e85bb18 | ||
|
|
c513649beb | ||
|
|
d2e6fef188 | ||
|
|
2224afd2ea | ||
|
|
3a5558f388 | ||
|
|
173248efbe | ||
|
|
5697a1d36e | ||
|
|
bc62ae206f | ||
|
|
076fba185c | ||
|
|
23cbb108ad | ||
|
|
1a1976d9ad | ||
|
|
dc3fcab7e1 | ||
|
|
ba5816e3ae | ||
|
|
56faaa3a2a | ||
|
|
35084dbce8 | ||
|
|
7e7216979a | ||
|
|
7c0c4cda1f | ||
|
|
642da8fdc1 | ||
|
|
30d2f56997 | ||
|
|
4d1a6e0b21 | ||
|
|
bda38b9f26 | ||
|
|
c004b90c54 | ||
|
|
d44e00f9ad | ||
|
|
dad10d8a5d | ||
|
|
b33821e7eb | ||
|
|
1288a84da2 | ||
|
|
e7b76137d1 | ||
|
|
7bb0ea9472 | ||
|
|
1dab6154c7 | ||
|
|
06a6302732 | ||
|
|
65631450ff | ||
|
|
2d9c6a65bb | ||
|
|
ce83f04d9d | ||
|
|
81f031b30f | ||
|
|
ee3ca2c517 | ||
|
|
50e858dcd5 | ||
|
|
8bbf16ed4f | ||
|
|
324e9810cc | ||
|
|
a8ab201d7d | ||
|
|
733d73ef76 | ||
|
|
5525325160 | ||
|
|
1aade1dcf9 | ||
|
|
787549237f | ||
|
|
088cd05e4f | ||
|
|
dc97095bd6 | ||
|
|
c6d8e5554d | ||
|
|
0900a4a143 | ||
|
|
eeb102e260 | ||
|
|
ea376a66d3 | ||
|
|
88747c8da1 | ||
|
|
8e1eb825df | ||
|
|
4fcf0dde3f | ||
|
|
e4791fc45c | ||
|
|
f55a9fb42b | ||
|
|
8ad06fd78a | ||
|
|
af82963f35 | ||
|
|
321ac597ce | ||
|
|
925a81f4f2 | ||
|
|
df1901ea90 | ||
|
|
569d5fffc4 | ||
|
|
af5a9717d4 | ||
|
|
bf2fffcffa | ||
|
|
55b0087455 |
No files matched your search
@@ -25,4 +25,5 @@ jobs:
|
||||
- run: npm ci
|
||||
- run: node tools/check-i18n.mjs
|
||||
- run: npm run build
|
||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||
- run: cargo test --workspace --locked
|
||||
@@ -69,8 +69,11 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
- 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
|
||||
run: cargo test --workspace -- --test-threads=1
|
||||
run: cargo test --workspace --locked -- --test-threads=1
|
||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||
- name: Build and sign (publish only when requested)
|
||||
id: tauri
|
||||
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
|
||||
@@ -35,6 +35,16 @@ Every published Manager version, including a clearly marked Pre-release, belongs
|
||||
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
|
||||
Promotion updates that entry without duplicating it; Manager and server histories remain separate.
|
||||
|
||||
Translated release notes are a required preparation step before freezing a new Manager source. Follow the
|
||||
runbook's "Mandatory translated release notes during preparation" checklist: translate every new reviewed
|
||||
Manager/server note into Russian, German, French, Spanish and Simplified Chinese in
|
||||
`src/data/latest-note-translations.json`, keyed by exact canonical English text. Preserve existing translations
|
||||
and released fragments. Refresh the bundled server-history snapshot from a pinned canonical commit and record
|
||||
its provenance. Run `node --test tools/release-history.test.mjs`, `node tools/check-i18n.mjs` and `npm run build`;
|
||||
verify each new record, all six viewer languages, English fallback and offline use. Save source/version and checks
|
||||
in the handoff. Translations ship with Manager: a server-only release must record the carrying Manager version or
|
||||
pending translation delivery, without forcing another Manager release or changing already signed installers.
|
||||
|
||||
Before preparing or publishing a Manager/server release, read the maintained
|
||||
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
|
||||
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
|
||||
|
||||
+110
@@ -8,6 +8,116 @@ 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.
|
||||
|
||||
## 0.9.13 — 2026-11-15
|
||||
|
||||
- The custom races client is updated to Custom Races V2.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13)
|
||||
|
||||
## 0.9.12 — 2026-11-14
|
||||
|
||||
- Settings for how much help bots get in dungeons and raids.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12)
|
||||
|
||||
## 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
|
||||
|
||||
- Update and recovery checks use the temporary login port even with a Windows override.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9)
|
||||
|
||||
## 0.9.8 — 2026-11-01
|
||||
|
||||
- Dungeon Clear can be enabled when SQUID bots are active.
|
||||
- Diagnostic exports include launcher stages and lock owner records.
|
||||
- Choose normal logs, errors only or no server logs in maintenance settings.
|
||||
- Update checks temporarily suspend bot population and restore your configuration.
|
||||
- Update validation keeps MySQL running between compatible checks.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8)
|
||||
|
||||
## 0.9.7 — 2026-10-30
|
||||
|
||||
- Show available update notes even when release history is cached.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7)
|
||||
|
||||
## 0.9.5 — 2026-10-30
|
||||
|
||||
- Account creation verifies a lost console reply against the requested login.
|
||||
- Abandoned game relay tunnels close their local connection immediately.
|
||||
- Keep disabled graphics components disabled during client updates.
|
||||
- Force-stop an unresponsive world after a failed normal shutdown.
|
||||
- Crash history includes reports from every world and Windows text files.
|
||||
- Show the online bot count for Playerbots on the overview.
|
||||
- Disable public server browsing in Settings.
|
||||
- Keep deliberate stops and update shutdowns from triggering crash restart.
|
||||
- Server startup waits for a responsive console before reporting success.
|
||||
- Restore the existing Manager window when launching it again.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5)
|
||||
|
||||
## 0.9.4 — 2026-10-29
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- Settings group updates, startup and maintenance with translated release history.
|
||||
- Update and launch without updating share a divided button.
|
||||
- Maximizing the window keeps text and controls at a comfortable size.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4)
|
||||
|
||||
## 0.9.3 — 2026-10-29
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- Slow server startup no longer triggers an early update rollback.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3)
|
||||
|
||||
## 0.9.2 — 2026-10-28
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- New server installation waits for slower database startup.
|
||||
- Find and edit CoA options in the existing server settings.
|
||||
- Simultaneous update checks share results or wait their turn.
|
||||
- Recovery can stop an unfinished world startup after restoring an older launcher.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2)
|
||||
|
||||
## 0.9.1 — 2026-10-28
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- Existing unsupported character records no longer block unrelated server updates.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1)
|
||||
|
||||
## 0.9.0 — 2026-10-28
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- Choose Parallel or Global level scaling in module settings.
|
||||
- Report Content Scaling problems directly to its repository.
|
||||
- Send custom race problem reports directly to their maintainer.
|
||||
- Internet sharing restores the LAN address after server restarts.
|
||||
- Configure custom race availability for new characters.
|
||||
- Public listing offers every realm that starts together, not just the main one.
|
||||
- Public listing is a short list of realms with a window for the details.
|
||||
- Configure profession and defense skill gains in server settings.
|
||||
- Starting a server sets the character classes of the realm chosen on Overview.
|
||||
- Start Wildcard and Warcraft Reborn together with Conquest of Azeroth.
|
||||
- Control portable characters and keep Manager running in the system tray.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0)
|
||||
|
||||
## 0.8.2 — 2026-10-27
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
Generated
+31
-3
@@ -586,7 +586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-core"
|
||||
version = "0.8.2"
|
||||
version = "0.9.14"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -606,6 +606,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"socket2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
@@ -618,6 +619,15 @@ dependencies = [
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "coa-launcher"
|
||||
version = "0.9.14"
|
||||
dependencies = [
|
||||
"coa-core",
|
||||
"serde_json",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "coa-registry-proto"
|
||||
version = "0.1.0"
|
||||
@@ -634,7 +644,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-release"
|
||||
version = "0.8.2"
|
||||
version = "0.9.14"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"coa-core",
|
||||
@@ -643,7 +653,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-server-manager"
|
||||
version = "0.8.2"
|
||||
version = "0.9.14"
|
||||
dependencies = [
|
||||
"coa-control-proto",
|
||||
"coa-core",
|
||||
@@ -655,8 +665,10 @@ dependencies = [
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-process",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4606,6 +4618,22 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "2.13.1"
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
[workspace]
|
||||
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"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.8.2"
|
||||
version = "0.9.14"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
# Per-race availability audit
|
||||
|
||||
Date: 2026-10-27. This is an internal implementation audit, not a supported-feature guide.
|
||||
|
||||
## Frozen sources
|
||||
|
||||
Separate `feat/per-race-toggles` branches and checkouts:
|
||||
|
||||
| Component | Checkout | Fetched base |
|
||||
| --- | --- | --- |
|
||||
| Manager | `C:/games/source/per-race-manager` | `origin/master`, `925a81f` |
|
||||
| Core | `C:/games/source/per-race-core` | `origin/coa-bots`, `1c658cab46d5057a8972cebd84c840aa6fbc4a91` |
|
||||
| CoA Companions | `C:/games/source/per-race-companions` | `origin/master`, `6a289fc2230ce9425924ca86dee02d0bb8d3d344` |
|
||||
| Build | `C:/games/source/per-race-build` | `origin/main`, `89795b6` |
|
||||
|
||||
The build runbook explicitly selects `Corfirean/azerothcore-wotlk-coa:coa-bots`, not its `main`.
|
||||
The old `C:/games/source/server/azerothcore-wotlk-coa` checkout instead tracks jealous-sound upstream
|
||||
and has local modifications. It must not be used as the feature's release base.
|
||||
The primary Manager and Companions checkouts also contain unrelated work and remain untouched.
|
||||
|
||||
SQUID is a separate repository, `Zyth45/mod-playerbots`, not `Corfirean/mod-coa-playerbots`.
|
||||
Existing research checkout: `C:/games/source/squid-playerbots`. Its current local branch is
|
||||
`fix/custom-races-existing-bots`, one commit ahead of `origin/coa`. Build policy selects the highest
|
||||
stable numeric tag, so that local branch must not silently become the shipped dependency.
|
||||
|
||||
## Manager integration points
|
||||
|
||||
- `crates/coa-core/src/custom_races.rs`: package version `1.9.2`, release URLs, MPQ/root/addon lists,
|
||||
hash manifests, client status, install, enable/disable and uninstall.
|
||||
- `PatchTransaction`, `SavedFile`, `recover_patch_transaction`: shared client-relative journal in
|
||||
`.coa-races-transaction/journal.json`, saved files and `committed` marker. Uncommitted changes roll back.
|
||||
Paths use `fsx::safe_join`; file moves handle cross-volume addon locations.
|
||||
- `patch_lock`: exclusive OS file lock on `.coa-races.lock`. The empty file's existence is normal and
|
||||
does not prove another operation is active. Do not delete it as a stale-lock workaround.
|
||||
- Client mutations reject `client::is_running`; reuse this gate and lock for availability changes.
|
||||
- `patch_files`, `matches_patch`, `preserve_original`: ownership and preservation depend on manifests
|
||||
and hashes, not just a filename. Availability overlay ownership needs its own verified record.
|
||||
- `modules/catalog.json`: `custom-races` uses `coa_custom_races.conf` and `CoACustomRaces.Enable`.
|
||||
Companions use `mod_coa_playerbots.conf` / `CoaBots.Enable`; SQUID uses
|
||||
`playerbots.conf` / `AiPlayerbot.Enabled`.
|
||||
- `crates/coa-core/src/modules.rs`: `toggle`, `settings_in`, `save_settings_in` write current module
|
||||
configuration. Bot switches enforce stopped servers and the existing control lock.
|
||||
- `src/screens/ModulesPage.tsx`: Custom Races card, master toggle, install/progress/status UI.
|
||||
- `src/lib/api.ts` and `src-tauri/src/lib.rs`: existing `custom_races_status`,
|
||||
`custom_races_install`, `custom_races_uninstall`, `custom_races_toggle_client` commands.
|
||||
There is no per-race command or verified availability status yet.
|
||||
- `src-tauri/src/lib.rs::play`: local launch reads `realms::state`, calls `client::sync_realm`, then
|
||||
launches. Remote launch has a separate realmlist override path; it cannot infer a remote race policy.
|
||||
- `crates/coa-core/src/realms.rs`: modes CoA, Wildcard and Warcraft Reborn; current configs are captured
|
||||
under `Settings/realm-profiles/<mode>.json`. Use this mechanism rather than a parallel realm store.
|
||||
Existing bot restrictions for non-CoA modes must remain effective.
|
||||
- `crates/coa-core/src/clientdl.rs::apply`: manifest-based client updates, `keep_modified`, staging,
|
||||
preservation of replaced files. No availability-overlay invalidation or rebuild exists today.
|
||||
|
||||
### Confirmed reconciliation risk
|
||||
|
||||
`custom_races.rs::sync_bot_races_config` writes a replacement `AiPlayerbot.ExcludedBotRaces` value:
|
||||
recommended full exclusions or experimental `65,72,77,80,81`. It does not preserve arbitrary user
|
||||
exclusions. `modules.rs` calls it from the master switch and BotsEnable saving; some callers discard
|
||||
errors. Per-race integration cannot rely on this overwrite behavior.
|
||||
|
||||
`playerbots_conf_paths` can also copy a `.dist` file when no active config exists; it is not a purely
|
||||
read-only discovery API. Status inspection should avoid adding more implicit writes.
|
||||
|
||||
## Core gates and bypasses
|
||||
|
||||
- `modules/mod-coa-custom-races/src/mod_coa_custom_races.cpp`: `WorldScript` loads the master switch;
|
||||
`AccountScript::CanAccountCreateCharacter` accepts stock IDs 1–8, 10, 11 or an enabled master switch.
|
||||
No disabled-ID list is implemented. Stock ID 9 is deliberately not included.
|
||||
- `modules/mod-coa-custom-races/conf/coa_custom_races.conf.dist`: Enable and BotsEnable exist;
|
||||
DisabledRaceIds does not.
|
||||
- `src/server/game/Handlers/CharacterHandler.cpp`: normal character creation invokes
|
||||
`sScriptMgr->CanAccountCreateCharacter` inside its finalization callback and rejects with
|
||||
`CHAR_CREATE_DISABLED`. A packet from an unpatched client reaches that gate too.
|
||||
- `src/server/game/Scripting/ScriptDefines/AccountScript.cpp`: hook aggregation must be preserved.
|
||||
- `src/server/game/DataStores/DBCStores.cpp::LoadDBCStores`: chooses `DataDir/dbc_races/<file>` if
|
||||
the master switch is enabled and that file exists, otherwise `DataDir/dbc/<file>`.
|
||||
Per-race creation policy must not remove DBC rows or change login data.
|
||||
- `.agents/docs/systems/ascension-character-creation.md`: native client compatibility depends on
|
||||
`CharBaseInfo.dbc`; race button indices are not RaceIDs. Existing race/class checks must stay intact.
|
||||
|
||||
## Both bot systems
|
||||
|
||||
### CoA Companions
|
||||
|
||||
`module/src/BotSpawnRandom.cpp::GetValidBotRaces` reads the global and bot custom-race switches,
|
||||
`CoaBots.CustomRaces.Enable`, and both AiPlayerbot/CoaBots exclusion lists. It checks DBC presence.
|
||||
Its experimental defaults apply only when the combined exclusion set is empty: adding an owner list
|
||||
to that set would silently remove those defaults. Keep those policies independent.
|
||||
|
||||
`CreateBotClone`, `CreateOneRandomBot`, and leveled spawning clone SQL character data directly;
|
||||
they bypass the account creation hook. Enforce new-character policy at the common clone creation
|
||||
entry as well as random selection. Preserve existing bots and faction selection via
|
||||
`Player::TeamIdForRace`.
|
||||
|
||||
Additional confirmed callers: `module/src/BotBattlegroundFill.cpp::QueueBotForSide` and
|
||||
`module/src/BotLfgFill.cpp` call `CreateOneRandomBot` after trying to reuse an existing bot.
|
||||
The existing-bot reuse path must remain separate from creation restrictions.
|
||||
|
||||
`tools/offline_bot_factory.py` is another direct-SQL creation path. Its main loop chooses a
|
||||
template by class and faction, then copies `template.race` into the new character overrides.
|
||||
It currently does not read the custom-race creation policy. Reject or filter prohibited
|
||||
templates before generating new accounts, GUIDs or SQL; do not rewrite their races.
|
||||
|
||||
### SQUID Playerbots
|
||||
|
||||
`src/PlayerbotAIConfig.cpp` loads `AiPlayerbot.ExcludedBotRaces` and adds
|
||||
`AiPlayerbot.CrashingBotRaces`; it reads BotsEnable. `src/CoaBotRacePolicy.h` implements
|
||||
`IsCoaBotRaceAllowed`. `src/Bot/Factory/RandomPlayerbotFactory.cpp::CreateRandomBot` applies
|
||||
that policy before faction and race/class selection.
|
||||
|
||||
The same predicate also appears in `src/Bot/RandomPlayerbotMgr.cpp` and
|
||||
`src/Bot/PlayerbotMgr.cpp`, including existing-character admission. Do not append owner creation
|
||||
restrictions globally to this shared exclusion vector: that would also affect existing bots.
|
||||
The predicate currently does not itself require `CoACustomRaces.Enable`.
|
||||
`RandomPlayerbotFactory.cpp` calls `Player::Create` directly without the account hook.
|
||||
Use a creation-only check in this factory, leaving existing-character admission unchanged.
|
||||
|
||||
## Portable Characters
|
||||
|
||||
Manager import code is under `crates/coa-core/src/portable/realm/`.
|
||||
`import.rs` validates identity namespaces and race/class start data (`UnknownRaceClass`).
|
||||
Availability policy must not become an import rejection or an identity rewrite. The inspected
|
||||
creation hook is in the normal packet handler, not this importer. In the core,
|
||||
`src/server/coa/CoAPortableImport.cpp` checks `GetPlayerInfo(model.Race, model.Class)` and writes
|
||||
`model.Race` to the imported character and character cache. It does not invoke the account
|
||||
creation hook. Preserve this separation. Live compatibility is still untested.
|
||||
|
||||
## Client experiment, actual observations
|
||||
|
||||
The owner updated `C:/games/Ascension` from 1.9.1 to 1.9.2 during this audit; its manifest now says
|
||||
`# CoA Custom 1.9.2`. A separate physical client copy is being prepared under
|
||||
`C:/games/source/per-race-evidence/client`; game assets are outside Git. The copy completed:
|
||||
25646 files copied, zero failures. The separate server file copy also completed, but has not
|
||||
been configured or started. No database service has been started for this task.
|
||||
|
||||
Read-only MPQ membership probing found ChrRaces in patch-ZZZF, ZZZE, ZZZC, ZZZ, ZZW, ZZV, ZZU,
|
||||
ZZS, T, M and several locale archives. CharacterCreate.lua has multiple owners too.
|
||||
The old `mpqprobe.py` precedence model explicitly admits an inference for Ascension multi-letter
|
||||
archives. Therefore `patch-ZZZF.MPQ` is a candidate source, not runtime-confirmed effective data.
|
||||
`patch-ZZZZ.MPQ` exists already; no overlay filename has been qualified.
|
||||
|
||||
Extracted from `patch-ZZZF.MPQ`:
|
||||
|
||||
- WDBC, 95 records, 69 fields, record size 276, string block 2428, total bytes 28668.
|
||||
- SHA-256 `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
|
||||
- Actual rows: Sethrak 82, Gnoll 83, Saberon 97. Their Flags are 12.
|
||||
- String block starts with `Hu`, not NUL; imposing an initial empty-string invariant incorrectly
|
||||
rejects this real table. String boundaries and referenced offsets still need validation.
|
||||
- Sethrak experiment changes only Flags 12 → 13. All other bytes compare equal.
|
||||
- One generated MPQ was read back through StormLib; its DBC equals the expected patched bytes.
|
||||
- The installed `pympq` Python extension crashed during interpreter finalization. The experimental
|
||||
tool instead uses the installed Unicode StormLib DLL directly. It is not a runtime dependency
|
||||
proposal for Manager or its users.
|
||||
|
||||
`tools/race_availability_poc.py` requires an explicit source archive and creates output only in a new
|
||||
directory. It does not select an archive order, install an overlay or assert in-game success.
|
||||
`tools/test_race_availability_poc.py` uses synthetic bytes only.
|
||||
|
||||
### Background verification after interactive testing was deferred
|
||||
|
||||
The owner requested no screen capture/input and no client/server/MySQL launches while other bot
|
||||
tests run. These restrictions remain active. The owner reported that the copied client launches;
|
||||
this does not confirm creation behavior or effective DBC loading.
|
||||
|
||||
- 17 DBC/fingerprint tests and 8 synthetic MPQ integration tests pass (25 total, none skipped).
|
||||
- Native tests use the explicitly selected existing Unicode StormLib DLL, with no new install.
|
||||
- Output is built and verified in a temporary directory before publishing the offline result folder.
|
||||
Failures leave no published result; this is not the future client transaction implementation.
|
||||
- One and fifty disabled races both produce one MPQ. StormLib adds an internal `(listfile)`;
|
||||
the sole game payload is `DBFilesClient/ChrRaces.dbc`.
|
||||
- Every referenced localized race-name offset is bounds-checked; invalid UTF-8 is rejected.
|
||||
- The experimental fingerprint includes original DBC SHA-256, normalized IDs, algorithm version
|
||||
and explicitly recorded profile. A profile label does not prove client compatibility.
|
||||
- The real three-race offline experiment is in
|
||||
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
|
||||
Source MPQ SHA-256: `40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3`.
|
||||
Generated DBC SHA-256: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
|
||||
|
||||
The first copy launch showed a missing-critical-files message and subsequently crashed on exit.
|
||||
The crash report identifies `AMDXN32.DLL` in the AMD graphics driver at the fault address; this
|
||||
does not establish the root cause. EXE, Extensions, dinput8, d3d9, dxgi, EsteriaAppearance and
|
||||
patch-ZZZF hashes matched the primary client during comparison. The experimental overlay was
|
||||
not installed. No graphics-driver or client-runtime changes were made to work around the crash.
|
||||
|
||||
## Reference implementations and update preservation
|
||||
|
||||
Inspected read-only reference clones:
|
||||
|
||||
- `aspollon/AFK-Realm` at `ea9c5bf691c98cace8cc03c06183c161022946de`.
|
||||
- `aspollon/mod-custom-races` at `5a8f2ff8a0d494ffadf64e677a438aa7f5a6671b`.
|
||||
|
||||
`mod-custom-races/afk-realm.json` declares client patch generation and GlueXML Lua insertion.
|
||||
`client/CustomRaces.lua` extends and lays out buttons, using race names/files and configured IDs.
|
||||
This is a reference, not evidence of compatibility with the current CoA/Esteria UI or a reason
|
||||
to replace CSM's prebuilt-server distribution.
|
||||
|
||||
`crates/coa-core/src/config/merge.rs` performs additive `.dist` merging: missing keys are added,
|
||||
existing user values and unknown keys are retained. A new DisabledRaceIds key should use this
|
||||
path. Existing realm snapshots already capture module `.conf` files. Neither mechanism currently
|
||||
coordinates an availability overlay with client update/repair; that remains implementation work.
|
||||
|
||||
## Open gates
|
||||
|
||||
Update after the owner found the existing Hide Races panel: see
|
||||
[existing-filter research](docs/PER_RACE_EXISTING_FILTER_RESEARCH.md). The inspected Lua already
|
||||
supports personal name/index-based hiding, but it is not a realm-scoped RaceID policy. Nine
|
||||
offline Lua 5.1 probes confirmed key behavior and limitations. Reusing its layout/UI is now a
|
||||
candidate to investigate before choosing a production DBC implementation. This is not evidence
|
||||
that the DBC approach failed, and it does not qualify client support.
|
||||
|
||||
The owner subsequently confirmed the GlueXML probe: restricted races disappeared from selection
|
||||
and were grey, unchecked and disabled in Hide Races. The production client integration should
|
||||
reuse this filter; changing DBC flags is no longer the selected implementation path.
|
||||
|
||||
Server controls, strict catalog-bound configuration, the core creation hook and both bot factory
|
||||
guards are implemented and have passed offline checks and native builds. Existing-bot admission
|
||||
and user/crashing exclusions remain separate from the new creation policy.
|
||||
|
||||
Remaining gates:
|
||||
1. Integrate automatic client reconciliation, ownership and recovery with realm settings.
|
||||
2. Qualify client update/repair and shared-client PLAY behavior.
|
||||
3. Verify live creation rejection/re-enable, existing-character login, imports and both bot systems
|
||||
when the owner's database test environment becomes available.
|
||||
|
||||
Status: **PARTIAL** — server implementation and builds pass; live server acceptance and production
|
||||
client synchronization remain pending. See docs/PER_RACE_TOGGLES_TESTS.md for exact scope.
|
||||
No existing character data, production service, release channel, or primary client archive was changed.
|
||||
+7247
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Choose Parallel or Global level scaling in module settings
|
||||
---
|
||||
Content Scaling progression can now be set to Parallel (Classic over 1 to the level cap, TBC and WotLK over 45 to the cap) or Global (all expansions over 1 to the cap) without editing the config file by hand.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Internet sharing restores the LAN address after server restarts
|
||||
---
|
||||
Friends on the local network receive the server's LAN address and network mask while internet players keep using its public address.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure custom race availability for new characters
|
||||
---
|
||||
Choose individual races in a compact table inside module settings using the installed server catalog. Saving requires a compatible server build and a stopped server. Client synchronization is not yet automatic.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Public listing offers every realm that starts together, not just the main one
|
||||
---
|
||||
With Wildcard or Warcraft Reborn started next to Conquest of Azeroth, Settings now has one listing block per realm, each with its own name, description and access options.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: Public listing is a short list of realms with a window for the details
|
||||
---
|
||||
Settings shows one line per realm with its state, and publishing opens a window. Publish all realms at once. Account creation and portable characters are chosen before publishing; portable characters are on by default.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure profession and defense skill gains in server settings
|
||||
---
|
||||
Advanced rate settings now include prospecting and milling skill gains, plus the points gained from crafting, defense and gathering.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Starting a server sets the character classes of the realm chosen on Overview
|
||||
---
|
||||
A new Conquest of Azeroth server could show two class models, or none, on the character creation screen. The Manager now sets the model of the chosen realm before every start.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Start Wildcard and Warcraft Reborn together with Conquest of Azeroth
|
||||
---
|
||||
Settings now has two options, one for Wildcard and one for Warcraft Reborn. Turn on either one, or both to run all three realms at once, each with its own characters and port.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Find and edit CoA options in the existing server settings
|
||||
---
|
||||
Search includes the separate CoA configuration, including legacy mount flight. Changes go to the correct file; realm profile controls stay managed by the Manager.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Existing unsupported character records no longer block unrelated server updates
|
||||
---
|
||||
Updates compare each affected character with its saved pre-update state. Unchanged older problems are reported as warnings without changing characters. Newly missing race/class data still blocks the update and triggers recovery; schema and identity checks remain enforced.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Recovery can stop an unfinished world startup after restoring an older launcher
|
||||
---
|
||||
If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: New server installation waits for slower database startup
|
||||
---
|
||||
Allow up to five minutes for MySQL to become ready. Failed installations stop their temporary database before cleaning up its files.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Control portable characters and keep Manager running in the system tray
|
||||
---
|
||||
Realm access settings can enable portable characters. Closing the window keeps Manager in the tray, with commands to reopen or exit. Offline realm messages explain why players cannot connect.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: Settings group updates, startup and maintenance with translated release history
|
||||
---
|
||||
Server and Manager keep separate update controls. Read their published changes in one place, including translations of the latest releases in all six interface languages. Saved notes remain available offline. Find public realm controls under Play with friends.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: Update and launch without updating share a divided button
|
||||
---
|
||||
Server and game client actions each use two adjacent segments of equal height. Both actions remain visible and keep their own availability checks.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Simultaneous update checks share results or wait their turn
|
||||
---
|
||||
Repeated checks no longer compete with another foreground or background check in the same Manager window. Maintenance and recovery locks remain enforced.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Maximizing the window keeps text and controls at a comfortable size
|
||||
---
|
||||
The interface no longer enlarges with window width. System display scaling and browser zoom still work, and large action buttons use more compact spacing.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Slow server startup no longer triggers an early update rollback
|
||||
---
|
||||
World startup now allows up to 25 minutes with either bot system and waits for both game and console ports within one deadline. Servers that stop during startup still fail immediately.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Account creation verifies a lost console reply against the requested login
|
||||
---
|
||||
Confirm the requested credentials after a lost reply, block creation during another server action, and explicitly report accounts whose administrator access could not be confirmed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Abandoned game relay tunnels close their local connection immediately
|
||||
---
|
||||
Dropping a tunnel shuts down its shared socket directly instead of relying only on a background message, releasing its local read and write connection.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Keep disabled graphics components disabled during client updates
|
||||
---
|
||||
Client settings can disable DXVK and graphics enhancements. Existing launcher DISABLED files are respected.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Force-stop an unresponsive world after a failed normal shutdown
|
||||
---
|
||||
Confirm the risk of unsaved progress before stopping verified server processes. Shared databases stay running until every owned world has stopped.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Crash history includes reports from every world and Windows text files
|
||||
---
|
||||
Create and verify the crash report folder before native startup, and include reports from simultaneous worlds and files containing Windows ANSI text.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Show the online bot count for Playerbots on the overview
|
||||
---
|
||||
The overview displays bot population for both supported bot systems.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Disable public server browsing in Settings
|
||||
---
|
||||
Turn off public server browsing to block catalog list and detail requests. When browsing is enabled, load the list with Refresh.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Keep deliberate stops and update shutdowns from triggering crash restart
|
||||
---
|
||||
Status checks no longer forget a stop request while the world is still shutting down. Update validation and recovery do not trigger automatic crash restarts.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Show available update notes even when release history is cached
|
||||
---
|
||||
Fetch the release notes for the offered update when they are missing from the cached history, including when an update becomes available while the history is open.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Server startup waits for a responsive console before reporting success
|
||||
---
|
||||
An open port no longer marks a loading world as ready. Account creation checks that the console processes commands before sending a create request.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Restore the existing Manager window when launching it again
|
||||
---
|
||||
Choose whether closing the window exits the Manager or minimizes it to the tray. Tray actions restore the window on the UI thread.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Dungeon Clear can be enabled when SQUID bots are active
|
||||
---
|
||||
Dungeon Clear starts disabled. Switching SQUID bots off also switches Dungeon Clear off; enabling SQUID again leaves Dungeon Clear off until you choose to enable it.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Diagnostic exports include launcher stages and lock owner records
|
||||
---
|
||||
Support packages include recent launcher diagnostics for each realm, with sensitive fields removed. Recorded lock owners help diagnose overlapping startup and shutdown actions.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Choose normal logs, errors only or no server logs in maintenance settings
|
||||
---
|
||||
The logging preset updates both the game world and login server, including their configuration templates. Previous settings are saved in configuration snapshots. Restart the server to apply the change.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Update checks temporarily suspend bot population and restore your configuration
|
||||
---
|
||||
Validation preserves the selected bot system and its population limits. Original configuration files are restored after validation, including recovery from interrupted updates.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Update validation keeps MySQL running between compatible checks
|
||||
---
|
||||
Database checks and the temporary server startup share one MySQL session. The server still stops before files or database snapshots are replaced or restored.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Update and recovery checks use the temporary login port even with a Windows override
|
||||
---
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Settings for how much help bots get in dungeons and raids
|
||||
---
|
||||
Bot damage, healing, damage taken and tank threat can now be tuned under Bots, Combat. Everything defaults to 1 (no change); a switch turns the extra help for four hard bosses on.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: players
|
||||
title: Install community addons from the Manager
|
||||
---
|
||||
The game client card lists SquidBots Lite, DragonUI, IncahootsCoA and CoACombat. Each comes from its author's GitHub at a pinned version, every file is checked before it goes into Interface/AddOns, and the Manager updates or removes only what it installed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: players
|
||||
title: Old item and creature data is cleared before every Play
|
||||
---
|
||||
After a server update the game showed old names and stats from its own cache (Cache/WDB). Play now clears that cache first; it fills again within seconds. A switch next to the client graphics settings turns it off.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: players
|
||||
title: Turning the custom races client patch on or off takes seconds again
|
||||
---
|
||||
V2 has over 7,000 files and switching it could run for many minutes. Now only the files the game itself loads are hidden, and the rest stays in place. A switch that was cut short is undone safely.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: players
|
||||
title: The custom races client is updated to Custom Races V2
|
||||
---
|
||||
The client update installs V2 and starts its own CoACustomRace.exe; Ascension.exe is left as it was. Four archives are the same as in 1.9.2, so a game folder that already had 1.9.2 downloads only the rest.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: The database moves to a free port when Windows reserves or another program takes 3307
|
||||
---
|
||||
Hyper-V, WSL and Docker can reserve a range that includes the database port; the start then waited 30 seconds and failed. The database now picks a free port and records it, and a reserved game port is named as such at once.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Your own MySQL settings survive restarts and updates
|
||||
---
|
||||
Settings, Service has a MySQL settings box. Its options are added to my.ini at every start of the database; before, my.ini was rewritten and hand edits were lost. Port, addresses and data paths stay managed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Disabled custom races stay disabled after a server update that adds races
|
||||
---
|
||||
A race list saved before Custom Races V2 no longer matched V2's race catalog, and the server then ignored it and turned custom races off. Before a start the Manager now keeps the list when every disabled race kept its ID and name.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Rename your realms in the Manager
|
||||
---
|
||||
Settings, Startup has a name for every realm. A running server shows it at once, the game client picks it on the next Play, and it stays after restarts and updates. Before, the launcher wrote the default name back at every start.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: players
|
||||
title: The account for a friend's server is in the login box at every Play
|
||||
---
|
||||
The account the Manager made on a listed server was filled in only when joining. Play now fills it in every time, also after another server's account was used.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Restart the world every day at a chosen time
|
||||
---
|
||||
Settings, Startup, Scheduled restart: at that local time the world restarts with an in-game countdown and comes back by itself; the database keeps running. It works without the Manager open and needs a server with the new launcher.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu
|
||||
---
|
||||
The Custom Races settings now hold Subclasses and Hero Races (subclasses, the Thin Twins, the Two-Headed Ogre, two players per character) and the GM /dev menu, each with its own switch.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Companion bots on Wildcard and Warcraft Reborn
|
||||
---
|
||||
With a server build that supports it, Companions can be switched on for Wildcard and Warcraft Reborn: bots get whole Wildcard archetypes or Reborn abilities by level, and bot creation survives a crash without duplicates.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: The Custom Races card tells which characters stay out while races are off
|
||||
---
|
||||
With custom races off, the card shows how many player characters and bots of custom races cannot enter the world, and offers to delete the companion bots of those races.
|
||||
+216
-1
@@ -123,6 +123,7 @@
|
||||
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
|
||||
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
|
||||
"Corfirean/coa-server-manager:20261022-custom-races-client.md",
|
||||
"Corfirean/coa-server-manager:20261022-scaling-progression-modes.md",
|
||||
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
|
||||
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
|
||||
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
|
||||
@@ -138,7 +139,46 @@
|
||||
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
|
||||
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
|
||||
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
|
||||
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md"
|
||||
"Corfirean/coa-server-manager:20261027-content-scaling-reports.md",
|
||||
"Corfirean/coa-server-manager:20261027-custom-races-reports.md",
|
||||
"Corfirean/coa-server-manager:20261027-internet-lan-address.md",
|
||||
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md",
|
||||
"Corfirean/coa-server-manager:20261027-per-race-server-settings.md",
|
||||
"Corfirean/coa-server-manager:20261027-public-list-shows-every-running-realm.md",
|
||||
"Corfirean/coa-server-manager:20261027-public-listing-window.md",
|
||||
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
|
||||
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
|
||||
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
|
||||
"Corfirean/coa-server-manager:20261028-coa-config-search.md",
|
||||
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
|
||||
"Corfirean/coa-server-manager:20261028-legacy-world-shutdown.md",
|
||||
"Corfirean/coa-server-manager:20261028-mysql-install-startup.md",
|
||||
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md",
|
||||
"Corfirean/coa-server-manager:20261028-settings-release-history.md",
|
||||
"Corfirean/coa-server-manager:20261028-split-update-actions.md",
|
||||
"Corfirean/coa-server-manager:20261028-update-check-queue.md",
|
||||
"Corfirean/coa-server-manager:20261028-window-density.md",
|
||||
"Corfirean/coa-server-manager:20261029-slow-world-startup.md",
|
||||
"Corfirean/coa-server-manager:20261030-account-console-confirmation.md",
|
||||
"Corfirean/coa-server-manager:20261030-close-abandoned-relay-sockets.md",
|
||||
"Corfirean/coa-server-manager:20261030-disabled-client-renderers.md",
|
||||
"Corfirean/coa-server-manager:20261030-force-stop-unresponsive-world.md",
|
||||
"Corfirean/coa-server-manager:20261030-native-crash-reports.md",
|
||||
"Corfirean/coa-server-manager:20261030-playerbots-overview-count.md",
|
||||
"Corfirean/coa-server-manager:20261030-public-server-browsing-control.md",
|
||||
"Corfirean/coa-server-manager:20261030-stop-does-not-trigger-auto-restart.md",
|
||||
"Corfirean/coa-server-manager:20261030-update-history-target-cache.md",
|
||||
"Corfirean/coa-server-manager:20261030-wait-for-world-console-readiness.md",
|
||||
"Corfirean/coa-server-manager:20261030-window-lifecycle.md",
|
||||
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.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-validation-bot-population.md",
|
||||
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
|
||||
"Corfirean/coa-server-manager:20261103-isolated-login-port.md",
|
||||
"Corfirean/coa-server-manager:20261107-bot-strength-scaling-settings.md",
|
||||
"Corfirean/coa-server-manager:20261115-custom-races-v2-client.md"
|
||||
],
|
||||
"releases": [
|
||||
{
|
||||
@@ -721,6 +761,181 @@
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.0",
|
||||
"version": "0.9.0",
|
||||
"date": "2026-10-28",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0",
|
||||
"notes": [
|
||||
"Choose Parallel or Global level scaling in module settings",
|
||||
"Report Content Scaling problems directly to its repository",
|
||||
"Send custom race problem reports directly to their maintainer",
|
||||
"Internet sharing restores the LAN address after server restarts",
|
||||
"Configure custom race availability for new characters",
|
||||
"Public listing offers every realm that starts together, not just the main one",
|
||||
"Public listing is a short list of realms with a window for the details",
|
||||
"Configure profession and defense skill gains in server settings",
|
||||
"Starting a server sets the character classes of the realm chosen on Overview",
|
||||
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth",
|
||||
"Control portable characters and keep Manager running in the system tray"
|
||||
],
|
||||
"commit": "dc97095bd6b36d9b5111f04f0cfd88e1fb2ab1f1",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0",
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.9.1",
|
||||
"tag": "v0.9.1",
|
||||
"date": "2026-10-28",
|
||||
"notes": [
|
||||
"Existing unsupported character records no longer block unrelated server updates"
|
||||
],
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
],
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
|
||||
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.2",
|
||||
"version": "0.9.2",
|
||||
"date": "2026-10-28",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2",
|
||||
"notes": [
|
||||
"New server installation waits for slower database startup",
|
||||
"Find and edit CoA options in the existing server settings",
|
||||
"Simultaneous update checks share results or wait their turn",
|
||||
"Recovery can stop an unfinished world startup after restoring an older launcher"
|
||||
],
|
||||
"commit": "2d9c6a65bbb1e296dc919e4c9e5785ed9d4a070b",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2",
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.3",
|
||||
"version": "0.9.3",
|
||||
"date": "2026-10-29",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3",
|
||||
"notes": [
|
||||
"Slow server startup no longer triggers an early update rollback"
|
||||
],
|
||||
"commit": "e7b76137d1b22a7596c2b1fa05ca9d12403b99d3",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3",
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.4",
|
||||
"version": "0.9.4",
|
||||
"date": "2026-10-29",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4",
|
||||
"notes": [
|
||||
"Settings group updates, startup and maintenance with translated release history",
|
||||
"Update and launch without updating share a divided button",
|
||||
"Maximizing the window keeps text and controls at a comfortable size"
|
||||
],
|
||||
"commit": "c004b90c54fa358b3037c56b093cf019dfcf02b8",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4",
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.5",
|
||||
"version": "0.9.5",
|
||||
"date": "2026-10-30",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5",
|
||||
"notes": [
|
||||
"Account creation verifies a lost console reply against the requested login",
|
||||
"Abandoned game relay tunnels close their local connection immediately",
|
||||
"Keep disabled graphics components disabled during client updates",
|
||||
"Force-stop an unresponsive world after a failed normal shutdown",
|
||||
"Crash history includes reports from every world and Windows text files",
|
||||
"Show the online bot count for Playerbots on the overview",
|
||||
"Disable public server browsing in Settings",
|
||||
"Keep deliberate stops and update shutdowns from triggering crash restart",
|
||||
"Server startup waits for a responsive console before reporting success",
|
||||
"Restore the existing Manager window when launching it again"
|
||||
],
|
||||
"commit": "642da8fdc1a0165aea74fbd1ab1b46933fc7e589",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.7",
|
||||
"version": "0.9.7",
|
||||
"date": "2026-10-30",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7",
|
||||
"notes": [
|
||||
"Show available update notes even when release history is cached"
|
||||
],
|
||||
"commit": "ba5816e3aea471d5b870e5f0db0b03920c071ed3",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.8",
|
||||
"version": "0.9.8",
|
||||
"date": "2026-11-01",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8",
|
||||
"notes": [
|
||||
"Dungeon Clear can be enabled when SQUID bots are active",
|
||||
"Diagnostic exports include launcher stages and lock owner records",
|
||||
"Choose normal logs, errors only or no server logs in maintenance settings",
|
||||
"Update checks temporarily suspend bot population and restore your configuration",
|
||||
"Update validation keeps MySQL running between compatible checks"
|
||||
],
|
||||
"commit": "076fba185c4d96d74f7258d6ca0cae6a4ae4a613",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.9",
|
||||
"version": "0.9.9",
|
||||
"date": "2026-11-04",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9",
|
||||
"notes": [
|
||||
"Update and recovery checks use the temporary login port even with a Windows override"
|
||||
],
|
||||
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
|
||||
"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"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.12",
|
||||
"version": "0.9.12",
|
||||
"date": "2026-11-14",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12",
|
||||
"notes": [
|
||||
"Settings for how much help bots get in dungeons and raids"
|
||||
],
|
||||
"commit": "d71c5635e3262a775b400a1c90ac81d7bddcbeaf",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.13",
|
||||
"version": "0.9.13",
|
||||
"date": "2026-11-15",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13",
|
||||
"notes": [
|
||||
"The custom races client is updated to Custom Races V2"
|
||||
],
|
||||
"commit": "d3527312803fb5a3e1cd48e01496645a8bbc9dcf",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
socket2 = "0.6"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
@@ -37,7 +38,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
|
||||
[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]
|
||||
testkit = []
|
||||
@@ -0,0 +1,154 @@
|
||||
use coa_core::{
|
||||
db::{Account, Db},
|
||||
driver::{self, Verb},
|
||||
ra::Ra,
|
||||
Result,
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture"));
|
||||
assert!(root
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("coa-update-recovery-fixture-"));
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let result = std::panic::catch_unwind(|| -> Result<()> {
|
||||
let started = driver::run(&root, Verb::StartAll)?;
|
||||
assert!(started.ok, "{}", started.output);
|
||||
assert!(root.join("Core/Crashes").is_dir());
|
||||
let db = Db::from_repack(&root, Account::Admin)?;
|
||||
println!("Account acceptance: server started, connecting to RA");
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
println!("Account acceptance: RA authenticated");
|
||||
let name = "STABILITYACCT2";
|
||||
assert_eq!(
|
||||
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
|
||||
.trim(),
|
||||
"0"
|
||||
);
|
||||
println!("Account acceptance: sending create command");
|
||||
coa_core::accounts::create(&root, name, "PrivateTest773", true)?;
|
||||
println!("Account acceptance: created");
|
||||
assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2' AND LENGTH(salt)=32 AND LENGTH(verifier)=32;")?.trim(), "1");
|
||||
assert!(ra
|
||||
.create_account(name, "PrivateTest773")
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("already taken"));
|
||||
ra.set_account_password(name, "PrivateTest774")?;
|
||||
ra.set_account_access(name, 3)?;
|
||||
assert_eq!(db.query("SELECT gmlevel FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='STABILITYACCT2');")?.trim(), "3");
|
||||
ra.delete_account(name)?;
|
||||
assert_eq!(
|
||||
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
|
||||
.trim(),
|
||||
"0"
|
||||
);
|
||||
lost_reply(&root, &db)?;
|
||||
println!("PASS: native RA account create, SRP salt/verifier, duplicate refusal, password change, administrator access and deletion");
|
||||
Ok(())
|
||||
});
|
||||
let stopped = driver::run(&root, Verb::StopAll)?;
|
||||
assert!(stopped.ok, "{}", stopped.output);
|
||||
result.map_err(|_| {
|
||||
coa_core::Error::Invalid("Native account acceptance failed; fixture stopped".into())
|
||||
})?
|
||||
}
|
||||
|
||||
fn lost_reply(root: &std::path::Path, db: &Db) -> Result<()> {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
let path = root.join("Settings/repack.json");
|
||||
let original = std::fs::read(&path)?;
|
||||
struct Restore(std::path::PathBuf, Vec<u8>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
std::fs::write(&self.0, &self.1).expect("restore disposable fixture settings");
|
||||
}
|
||||
}
|
||||
let restore = Restore(path.clone(), original.clone());
|
||||
let actual = coa_core::layout::read_ports(root).ra;
|
||||
for (name, forward, ready) in [
|
||||
("STABLOSTREPLY", true, true),
|
||||
("STABNOTCREATED", false, true),
|
||||
("STABNOTREADY", false, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
db.query(&format!(
|
||||
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
|
||||
))?
|
||||
.trim(),
|
||||
"0"
|
||||
);
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0))?;
|
||||
let mut config: serde_json::Value = serde_json::from_slice(&original)?;
|
||||
config["raPort"] = listener.local_addr()?.port().into();
|
||||
coa_core::fsx::atomic_write_json(&path, &config)?;
|
||||
let proxy = std::thread::spawn(move || {
|
||||
fn until(s: &mut TcpStream, marker: &[u8]) -> Vec<u8> {
|
||||
s.set_read_timeout(Some(std::time::Duration::from_secs(30)))
|
||||
.unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let mut byte = [0];
|
||||
while !bytes.ends_with(marker) {
|
||||
s.read_exact(&mut byte).unwrap();
|
||||
bytes.push(byte[0]);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
let (mut client, _) = listener.accept().unwrap();
|
||||
let mut server = TcpStream::connect(("127.0.0.1", actual)).unwrap();
|
||||
for marker in [b"Username: ".as_slice(), b"Password: ".as_slice()] {
|
||||
client.write_all(&until(&mut server, marker)).unwrap();
|
||||
server.write_all(&until(&mut client, b"\r\n")).unwrap();
|
||||
}
|
||||
client.write_all(&until(&mut server, b"AC>")).unwrap();
|
||||
let readiness = until(&mut client, b"\r\n");
|
||||
assert_eq!(readiness, b"server info\r\n");
|
||||
if !ready {
|
||||
return;
|
||||
}
|
||||
server.write_all(&readiness).unwrap();
|
||||
client.write_all(&until(&mut server, b"AC>")).unwrap();
|
||||
let command = until(&mut client, b"\r\n");
|
||||
if forward {
|
||||
server.write_all(&command).unwrap();
|
||||
let _ = until(&mut server, b"AC>");
|
||||
}
|
||||
});
|
||||
let outcome = coa_core::accounts::create(root, name, "PrivateTest773", false);
|
||||
proxy.join().unwrap();
|
||||
std::fs::write(&path, &original)?;
|
||||
if forward {
|
||||
outcome?;
|
||||
assert_eq!(
|
||||
db.query(&format!(
|
||||
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
|
||||
))?
|
||||
.trim(),
|
||||
"1"
|
||||
);
|
||||
assert!(coa_core::accounts::create(root, name, "DifferentPass77", false).is_err());
|
||||
Ra::connect(root)?.delete_account(name)?;
|
||||
} else {
|
||||
assert!(outcome.is_err());
|
||||
if !ready {
|
||||
assert!(outcome
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("No create command was sent"));
|
||||
}
|
||||
assert_eq!(
|
||||
db.query(&format!(
|
||||
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
|
||||
))?
|
||||
.trim(),
|
||||
"0"
|
||||
);
|
||||
}
|
||||
}
|
||||
drop(restore);
|
||||
println!("PASS: a lost native console reply is reconciled by exact SRP credentials; a command that was never executed is rejected");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use coa_core::{crashes, Result};
|
||||
fn main()->Result<()> {
|
||||
let root=std::path::PathBuf::from(std::env::args().nth(1).expect("marked native fixture"));
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let reports=crashes::list(&root,30)?;
|
||||
let matching:Vec<_>=reports.iter().filter(|r|r.full_log.contains("AllowableRaces")).collect();
|
||||
assert!(!matching.is_empty());
|
||||
assert!(matching.iter().all(|r|r.exception_code.as_deref()==Some("C0000420")));
|
||||
println!("PASS: Manager discovered {} actual worldserver SQL assertion reports from Core/Crashes, including Windows ANSI text",matching.len());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use coa_core::{
|
||||
db::{Account, Db},
|
||||
driver::{self, Verb},
|
||||
ra::Ra,
|
||||
Result,
|
||||
};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(
|
||||
std::env::args()
|
||||
.nth(1)
|
||||
.expect("disposable recovery fixture"),
|
||||
);
|
||||
assert!(root
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("coa-update-recovery-fixture-"));
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let result = std::panic::catch_unwind(|| -> Result<()> {
|
||||
let start = driver::run(&root, Verb::StartAll)?;
|
||||
assert!(start.ok, "{}", start.output);
|
||||
let db = Db::from_repack(&root, Account::Admin)?;
|
||||
coa_core::companions::ensure_templates(&db)?;
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
let before = coa_core::population::query(&root)?;
|
||||
assert_eq!(before.bots_online, 0);
|
||||
let rejected = db.query("SELECT name, at_login FROM acore_characters.characters WHERE guid=3030 AND account IN (SELECT id FROM acore_auth.account WHERE username LIKE 'COABOTHOST%');")?;
|
||||
assert!(rejected.contains("Christian Shadowheart"));
|
||||
assert_eq!(rejected.split_whitespace().last(), Some("1"));
|
||||
println!("Repair reply: {}", ra.run("botcmd spawnbot 3030")?);
|
||||
let repair_deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let row = db.query(
|
||||
"SELECT name, at_login, online FROM acore_characters.characters WHERE guid=3030;",
|
||||
)?;
|
||||
if row.trim().ends_with("0\t1") {
|
||||
assert!(!row.contains("Christian Shadowheart"));
|
||||
println!("PASS: the exact previously rejected companion was renamed by server validation and logged in");
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < repair_deadline,
|
||||
"previously rejected companion logged in"
|
||||
);
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
let _ = ra.despawn_all()?;
|
||||
let clear_deadline = Instant::now() + Duration::from_secs(30);
|
||||
while coa_core::population::query(&root)?.bots_online > 0 {
|
||||
assert!(Instant::now() < clear_deadline);
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
println!("Spawn reply: {}", ra.spawn_bots(21)?);
|
||||
let deadline = Instant::now() + Duration::from_secs(180);
|
||||
loop {
|
||||
let pop = coa_core::population::query(&root)?;
|
||||
if pop.bots_online >= 21 {
|
||||
println!(
|
||||
"PASS: {} companions logged in; real players={}",
|
||||
pop.bots_online, pop.players_online
|
||||
);
|
||||
break;
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
return Err(coa_core::Error::Invalid(format!(
|
||||
"Only {} of 21 companion logins completed",
|
||||
pop.bots_online
|
||||
)));
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
let _ = ra.cancel_spawning()?;
|
||||
let _ = ra.despawn_all()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while coa_core::population::query(&root)?.bots_online > 0 {
|
||||
assert!(Instant::now() < deadline, "companions despawned");
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
println!("PASS: companion despawn completed");
|
||||
Ok(())
|
||||
});
|
||||
let stopped = driver::run(&root, Verb::StopAll)?;
|
||||
assert!(stopped.ok, "{}", stopped.output);
|
||||
result.map_err(|_| {
|
||||
coa_core::Error::Invalid("Companion native acceptance panicked; fixture stopped".into())
|
||||
})?
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use coa_core::{crashes, Result};
|
||||
fn main() -> Result<()> {
|
||||
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("native crash evidence"));
|
||||
assert!(root.join(".crash-report-evidence").is_file());
|
||||
let reports = crashes::list(&root, 10)?;
|
||||
assert_eq!(reports.len(), 1);
|
||||
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
|
||||
assert_eq!(reports[0].category, "access_violation");
|
||||
assert!(!reports[0].full_log.is_empty());
|
||||
println!("PASS: Manager crash history discovers and classifies the actual native handler report from Core/Crashes");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use coa_core::{driver, fsx, process, Result};
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::{
|
||||
path::Path,
|
||||
process::{Child, Command, Stdio},
|
||||
};
|
||||
|
||||
struct OwnedChild(Child);
|
||||
impl Drop for OwnedChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
fn copy_tree(source: &Path, target: &Path) -> Result<()> {
|
||||
std::fs::create_dir_all(target)?;
|
||||
for entry in std::fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
let destination = target.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &destination)?;
|
||||
} else {
|
||||
std::fs::copy(entry.path(), destination)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn spawn(path: &Path) -> OwnedChild {
|
||||
let mut cmd = Command::new(path);
|
||||
cmd.args(["-t", "127.0.0.1"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
OwnedChild(cmd.spawn().unwrap())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
assert!(cfg!(windows));
|
||||
let source = std::path::PathBuf::from(
|
||||
std::env::args()
|
||||
.nth(1)
|
||||
.expect("marked disposable runtime source"),
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(source.join(".release-schema-fixture"))?,
|
||||
b"disposable release-schema fixture"
|
||||
);
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = temp.path();
|
||||
copy_tree(&source.join("Runtime"), &root.join("Runtime"))?;
|
||||
std::fs::create_dir_all(root.join("Core"))?;
|
||||
std::fs::create_dir_all(root.join("Scripts"))?;
|
||||
let system =
|
||||
std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/ping.exe");
|
||||
std::fs::copy(&system, root.join("Core/worldserver.exe"))?;
|
||||
std::fs::copy(&system, root.join("foreign.exe"))?;
|
||||
let mut ports = Vec::new();
|
||||
let mut listeners = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
ports.push(listener.local_addr()?.port());
|
||||
listeners.push(listener);
|
||||
}
|
||||
let config = serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3],"raUsername":"fixture","raPassword":"fixture"});
|
||||
fsx::atomic_write_json(&root.join("Settings/repack.json"), &config)?;
|
||||
drop(listeners);
|
||||
let mut launcher = std::fs::read_to_string(source.join("Scripts/manage.py"))?;
|
||||
launcher.push_str("\nfrom contextlib import nullcontext\ndef control_lock(): return nullcontext()\ndef stop_all(config):\n assert not process('world'), 'world must stop before database'\n (ROOT/'database-stage').write_text('safe')\n");
|
||||
fsx::atomic_write(&root.join("Scripts/manage.py"), launcher.as_bytes())?;
|
||||
let mut foreign = spawn(&root.join("foreign.exe"));
|
||||
let foreign_identity = process::identity(foreign.0.id()).unwrap();
|
||||
fsx::atomic_write_json(&root.join(".state/world.json"), &foreign_identity)?;
|
||||
let rejected = driver::force_stop(root)?;
|
||||
assert!(!rejected.ok, "a foreign world record must be rejected");
|
||||
assert!(!root.join("database-stage").exists());
|
||||
assert!(foreign.0.try_wait()?.is_none());
|
||||
let mut owned = spawn(&root.join("Core/worldserver.exe"));
|
||||
let stopped = driver::force_stop(root)?;
|
||||
assert!(stopped.ok, "{}", stopped.output);
|
||||
assert!(owned.0.try_wait()?.is_some());
|
||||
assert!(
|
||||
foreign.0.try_wait()?.is_none(),
|
||||
"foreign process was untouched"
|
||||
);
|
||||
assert_eq!(std::fs::read(root.join("database-stage"))?, b"safe");
|
||||
println!("PASS: native Windows forced-stop rejects foreign records, recovers the exact owned world identity, stops it before the database stage, and leaves the foreign process alive");
|
||||
Ok(())
|
||||
}
|
||||
@@ -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,199 @@
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use coa_core::{
|
||||
backup,
|
||||
db::Db,
|
||||
driver::{self, Verb},
|
||||
fsx,
|
||||
manifest::{Kind, Migration},
|
||||
package::{self, BuildOptions},
|
||||
pkgsource::Source,
|
||||
registry::MetaDir,
|
||||
update::{self, RepackEnv},
|
||||
Result,
|
||||
};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(
|
||||
std::env::args()
|
||||
.nth(1)
|
||||
.expect("qualified disposable fixture"),
|
||||
);
|
||||
let sql = std::fs::read(std::env::args().nth(2).expect("corrective SQL"))?;
|
||||
assert_eq!(
|
||||
root.file_name().unwrap(),
|
||||
"coa-schema-fixture-stability-upgrade-76-85-20261030"
|
||||
);
|
||||
assert!(root.join(".release-schema-fixture").is_file());
|
||||
assert!(!root.join("legacy-start-data-e2e-started").exists());
|
||||
fsx::atomic_write(
|
||||
&root.join("legacy-start-data-e2e-started"),
|
||||
b"disposable regression test",
|
||||
)?;
|
||||
let result = std::panic::catch_unwind(|| -> Result<()> {
|
||||
let meta = coa_core::registry::metadata_dir_for(&root)?;
|
||||
let mut identities = String::new();
|
||||
let mut custom = String::new();
|
||||
backup::with_database(&root, |db| {
|
||||
assert_eq!(
|
||||
db.query(
|
||||
"SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45);"
|
||||
)?
|
||||
.trim(),
|
||||
"0"
|
||||
);
|
||||
let base: u32 = db
|
||||
.query("SELECT MAX(guid)+100 FROM acore_characters.characters;")?
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap();
|
||||
clone_character(db, base, 33, 12, "Thinprobe")?;
|
||||
clone_character(db, base + 1, 45, 30, "Leperprobe")?;
|
||||
identities = db.query(&format!(
|
||||
"SELECT * FROM acore_characters.characters WHERE guid IN ({base},{});",
|
||||
base + 1
|
||||
))?;
|
||||
let missing = coa_core::character_start_check::missing(db)?;
|
||||
assert!(missing
|
||||
.iter()
|
||||
.any(|c| c.guid == base && c.race == 33 && c.class == 12));
|
||||
assert!(missing
|
||||
.iter()
|
||||
.any(|c| c.guid == base + 1 && c.race == 45 && c.class == 30));
|
||||
db.query("INSERT INTO acore_world.playercreateinfo SELECT 33,class,map,zone,position_x+0.125,position_y,position_z,orientation FROM acore_world.playercreateinfo WHERE race=1 AND class=32;")?;
|
||||
custom =
|
||||
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?;
|
||||
fsx::atomic_write(
|
||||
&root.join("legacy-probe-guids.json"),
|
||||
serde_json::to_string(&[base, base + 1])?.as_bytes(),
|
||||
)?;
|
||||
println!("PASS: reproduced missing starting data for existing race 33/class 12 and race 45/class 30 characters");
|
||||
Ok(())
|
||||
})?;
|
||||
let source = root.join("legacy-start-data-source");
|
||||
let pkg = root.join("legacy-start-data-package");
|
||||
fsx::atomic_write(
|
||||
&source.join("Core/legacy-start-data-proof.txt"),
|
||||
b"corrective migration acceptance",
|
||||
)?;
|
||||
fsx::atomic_write(
|
||||
&source.join("_migrations/world/stabilization_legacy_starts.sql"),
|
||||
&sql,
|
||||
)?;
|
||||
let manifest = package::build(
|
||||
&source,
|
||||
&pkg,
|
||||
&BuildOptions {
|
||||
kind: Kind::Update,
|
||||
version: "2.0.0".into(),
|
||||
core_commit: None,
|
||||
bots_commit: None,
|
||||
built_at: "private regression acceptance".into(),
|
||||
part_size: 1 << 20,
|
||||
migrations: vec![Migration {
|
||||
id: "stabilization_legacy_starts".into(),
|
||||
db: "world".into(),
|
||||
sha256: fsx::sha256_bytes(&sql),
|
||||
compatible_sha256: vec![],
|
||||
destructive: false,
|
||||
}],
|
||||
},
|
||||
&|_| {},
|
||||
)?;
|
||||
let key = SigningKey::generate(&mut rand_core::OsRng);
|
||||
fsx::atomic_write(
|
||||
&pkg.join("manifest.json.sig"),
|
||||
STANDARD
|
||||
.encode(
|
||||
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
|
||||
.to_bytes(),
|
||||
)
|
||||
.as_bytes(),
|
||||
)?;
|
||||
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
|
||||
let env = RepackEnv {
|
||||
root: &root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
let out = update::apply(
|
||||
&update::Params {
|
||||
root: &root,
|
||||
meta_dir: &meta,
|
||||
source: Source::Dir(pkg),
|
||||
trusted_key: &trusted,
|
||||
cancel: Default::default(),
|
||||
resolutions: BTreeMap::new(),
|
||||
env: &env,
|
||||
fail_after_ops: None,
|
||||
},
|
||||
&|step, pct| println!("{pct}% {step}"),
|
||||
)?;
|
||||
assert_eq!(out.txn.state, update::State::Committed);
|
||||
assert_eq!(
|
||||
MetaDir::open(&meta)?.1.core.version.as_deref(),
|
||||
Some("2.0.0")
|
||||
);
|
||||
backup::with_database(&root, |db| {
|
||||
let guids: Vec<u32> =
|
||||
serde_json::from_slice(&std::fs::read(root.join("legacy-probe-guids.json"))?)?;
|
||||
assert_eq!(
|
||||
db.query(&format!(
|
||||
"SELECT * FROM acore_characters.characters WHERE guid IN ({},{});",
|
||||
guids[0], guids[1]
|
||||
))?,
|
||||
identities
|
||||
);
|
||||
assert!(coa_core::character_start_check::missing(db)?
|
||||
.iter()
|
||||
.all(|c| !guids.contains(&c.guid)));
|
||||
assert_eq!(
|
||||
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
|
||||
custom
|
||||
);
|
||||
assert!(coa_core::migrations::status(db, &manifest.migrations)?
|
||||
.iter()
|
||||
.all(|m| m.status == coa_core::migrations::Status::Applied));
|
||||
let before = counts(db)?;
|
||||
db.query(&format!(
|
||||
"USE acore_world; {}",
|
||||
String::from_utf8_lossy(&sql)
|
||||
))?;
|
||||
assert_eq!(counts(db)?, before);
|
||||
assert_eq!(
|
||||
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
|
||||
custom
|
||||
);
|
||||
println!("PASS: signed Manager update restored legacy starts, preserved complete character rows and custom starts, and remained idempotent on a second SQL execution");
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
});
|
||||
let stopped = driver::run(&root, Verb::StopAll)?;
|
||||
assert!(stopped.ok, "{}", stopped.output);
|
||||
result.map_err(|_| {
|
||||
coa_core::Error::Invalid("Legacy start regression failed; fixture stopped".into())
|
||||
})?
|
||||
}
|
||||
fn counts(db: &Db) -> Result<String> {
|
||||
db.query("SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_item WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_action WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.player_race_stats WHERE Race IN (33,45); SELECT COUNT(*) FROM acore_world.ascension_custom_class_race WHERE race IN (33,45);")
|
||||
}
|
||||
fn clone_character(db: &Db, guid: u32, race: u32, class: u32, name: &str) -> Result<()> {
|
||||
let columns = db.query("SHOW COLUMNS FROM acore_characters.characters;")?;
|
||||
let names: Vec<_> = columns
|
||||
.lines()
|
||||
.map(|l| l.split('\t').next().unwrap())
|
||||
.collect();
|
||||
let values: Vec<String> = names
|
||||
.iter()
|
||||
.map(|c| match *c {
|
||||
"guid" => guid.to_string(),
|
||||
"name" => format!("'{name}'"),
|
||||
"race" => race.to_string(),
|
||||
"class" => class.to_string(),
|
||||
"online" | "at_login" => "0".into(),
|
||||
_ => format!("`{c}`"),
|
||||
})
|
||||
.collect();
|
||||
db.query(&format!("INSERT INTO acore_characters.characters ({}) SELECT {} FROM acore_characters.characters WHERE class={class} LIMIT 1;",names.iter().map(|c|format!("`{c}`")).collect::<Vec<_>>().join(","),values.join(",")))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -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,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");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use coa_core::{backup, schema_check, Result};
|
||||
fn main()->Result<()> {
|
||||
let root=std::path::PathBuf::from(std::env::args().nth(1).unwrap());
|
||||
let contract=std::path::PathBuf::from(std::env::args().nth(2).unwrap());
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
assert!(contract.join(".release-schema-fixture").is_file());
|
||||
backup::with_database(&root,|db| {for p in schema_check::check(db,&contract)? {println!("{}.{}.{}: {}",p.database,p.table,p.column,p.detail);} Ok(())})
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use coa_core::{
|
||||
backup,
|
||||
driver::{self, Verb},
|
||||
fsx,
|
||||
manifest::{Kind, Migration},
|
||||
package::{self, BuildOptions},
|
||||
pkgsource::Source,
|
||||
update::{self, RepackEnv},
|
||||
Result,
|
||||
};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(std::env::args().nth(1).unwrap());
|
||||
let core = PathBuf::from(std::env::args().nth(2).unwrap());
|
||||
let release = PathBuf::from(std::env::args().nth(3).unwrap());
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let result = std::panic::catch_unwind(|| -> Result<()> {
|
||||
let meta = coa_core::registry::metadata_dir_for(&root)?;
|
||||
let source = root.join("schema-sync-source-v2");
|
||||
let pkg = root.join("schema-sync-package-v2");
|
||||
assert!(!pkg.exists());
|
||||
fsx::atomic_write(
|
||||
&source.join("Core/schema-sync-proof.txt"),
|
||||
b"official schema migration acceptance",
|
||||
)?;
|
||||
let published =
|
||||
coa_core::manifest::Manifest::parse(&std::fs::read(release.join("manifest.json"))?)?;
|
||||
let contract_path = PathBuf::from("C:/games/source/coa-schema-fixture-stability-upgrade-76-85-20261030/Scripts/database-schema.json");
|
||||
let contract = std::fs::read(contract_path)?;
|
||||
let expected = published
|
||||
.files
|
||||
.iter()
|
||||
.find(|f| f.path == "Scripts/database-schema.json")
|
||||
.unwrap();
|
||||
assert_eq!(fsx::sha256_bytes(&contract), expected.sha256);
|
||||
fsx::atomic_write(&source.join("Scripts/database-schema.json"), &contract)?;
|
||||
let mut migrations: Vec<Migration> = Vec::new();
|
||||
for id in [
|
||||
"rev_1793212891571528600",
|
||||
"rev_20261027_18_coa_strange_piece_of_scrap_faction_diamond",
|
||||
] {
|
||||
let m = published
|
||||
.migrations
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.unwrap()
|
||||
.clone();
|
||||
let sql = std::fs::read(
|
||||
core.join(format!("data/sql/updates/pending_db_{}/{}.sql", m.db, m.id)),
|
||||
)?;
|
||||
assert_eq!(fsx::sha256_bytes(&sql), m.sha256);
|
||||
fsx::atomic_write(
|
||||
&source.join(format!("_migrations/{}/{}.sql", m.db, m.id)),
|
||||
&sql,
|
||||
)?;
|
||||
migrations.push(m);
|
||||
}
|
||||
package::build(
|
||||
&source,
|
||||
&pkg,
|
||||
&BuildOptions {
|
||||
kind: Kind::Update,
|
||||
version: "3.0.0".into(),
|
||||
core_commit: None,
|
||||
bots_commit: None,
|
||||
built_at: "private native fixture schema sync".into(),
|
||||
part_size: 1 << 20,
|
||||
migrations,
|
||||
},
|
||||
&|_| {},
|
||||
)?;
|
||||
let key = SigningKey::generate(&mut rand_core::OsRng);
|
||||
fsx::atomic_write(
|
||||
&pkg.join("manifest.json.sig"),
|
||||
STANDARD
|
||||
.encode(
|
||||
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
|
||||
.to_bytes(),
|
||||
)
|
||||
.as_bytes(),
|
||||
)?;
|
||||
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
|
||||
let env = RepackEnv {
|
||||
root: &root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
let out = update::apply(
|
||||
&update::Params {
|
||||
root: &root,
|
||||
meta_dir: &meta,
|
||||
source: Source::Dir(pkg),
|
||||
trusted_key: &trusted,
|
||||
cancel: Default::default(),
|
||||
resolutions: BTreeMap::from([(
|
||||
"Scripts/database-schema.json".into(),
|
||||
update::Resolution::Replace,
|
||||
)]),
|
||||
env: &env,
|
||||
fail_after_ops: None,
|
||||
},
|
||||
&|step, pct| println!("{pct}% {step}"),
|
||||
)?;
|
||||
assert_eq!(out.txn.state, update::State::Committed);
|
||||
backup::with_database(&root, |db| {
|
||||
assert_eq!(
|
||||
db.query("SELECT name,at_login FROM acore_characters.characters WHERE guid=3030;")?
|
||||
.trim(),
|
||||
"Christian Shadowheart\t1"
|
||||
);
|
||||
assert_eq!(
|
||||
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?
|
||||
.trim(),
|
||||
"42"
|
||||
);
|
||||
assert_eq!(
|
||||
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?
|
||||
.trim(),
|
||||
"44"
|
||||
);
|
||||
Ok(())
|
||||
})?;
|
||||
println!("PASS: the exact two published migrations brought the old fixture schema forward through the Manager updater while preserving the rejected companion and recovery probes");
|
||||
Ok(())
|
||||
});
|
||||
let stop = driver::run(&root, Verb::StopAll)?;
|
||||
assert!(stop.ok, "{}", stop.output);
|
||||
result.map_err(|_| {
|
||||
coa_core::Error::Invalid("Schema sync acceptance failed; fixture stopped".into())
|
||||
})?
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use coa_core::{
|
||||
backup, driver, fsx,
|
||||
manifest::{Kind, Migration},
|
||||
package::{self, BuildOptions},
|
||||
pkgsource::Source,
|
||||
registry::MetaDir,
|
||||
update::{self, RepackEnv},
|
||||
Result,
|
||||
};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(
|
||||
std::env::args()
|
||||
.nth(1)
|
||||
.expect("disposable recovery fixture"),
|
||||
);
|
||||
assert!(root
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("coa-update-recovery-fixture-"));
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let cycles_only = std::env::args().nth(2).as_deref() == Some("--cycles-only");
|
||||
if !cycles_only {
|
||||
assert!(!root.join("success-e2e-started").exists());
|
||||
fsx::atomic_write(
|
||||
&root.join("success-e2e-started"),
|
||||
b"disposable success acceptance",
|
||||
)?;
|
||||
}
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
if cycles_only {
|
||||
restart_cycles(&root)
|
||||
} else {
|
||||
exercise(&root)
|
||||
}
|
||||
}));
|
||||
assert!(
|
||||
driver::run(&root, driver::Verb::StopAll)?.ok,
|
||||
"fixture shutdown"
|
||||
);
|
||||
result.map_err(|_| {
|
||||
coa_core::Error::Invalid(
|
||||
"Success acceptance assertion failed; fixture services stopped".into(),
|
||||
)
|
||||
})?
|
||||
}
|
||||
|
||||
fn exercise(root: &std::path::Path) -> Result<()> {
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
assert!(update::unfinished(&meta).is_none());
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
let source = root.join("success-source");
|
||||
let pkg = root.join("success-package");
|
||||
fsx::atomic_write(
|
||||
&source.join("Core/stabilization-success.txt"),
|
||||
b"verified update",
|
||||
)?;
|
||||
let sql = b"UPDATE manager_recovery_probe SET id=44 WHERE id=43;";
|
||||
fsx::atomic_write(
|
||||
&source.join("_migrations/world/stabilization_success.sql"),
|
||||
sql,
|
||||
)?;
|
||||
let manifest = package::build(
|
||||
&source,
|
||||
&pkg,
|
||||
&BuildOptions {
|
||||
kind: Kind::Update,
|
||||
version: "2.0.0".into(),
|
||||
core_commit: None,
|
||||
bots_commit: None,
|
||||
built_at: "disposable acceptance".into(),
|
||||
part_size: 1 << 20,
|
||||
migrations: vec![Migration {
|
||||
id: "stabilization_success".into(),
|
||||
db: "world".into(),
|
||||
sha256: fsx::sha256_bytes(sql),
|
||||
compatible_sha256: vec![],
|
||||
destructive: false,
|
||||
}],
|
||||
},
|
||||
&|_| {},
|
||||
)?;
|
||||
let key = SigningKey::generate(&mut rand_core::OsRng);
|
||||
fsx::atomic_write(
|
||||
&pkg.join("manifest.json.sig"),
|
||||
STANDARD
|
||||
.encode(
|
||||
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
|
||||
.to_bytes(),
|
||||
)
|
||||
.as_bytes(),
|
||||
)?;
|
||||
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
|
||||
let env = RepackEnv {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
let outcome = update::apply(
|
||||
&update::Params {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
source: Source::Dir(pkg),
|
||||
trusted_key: &trusted,
|
||||
cancel: Default::default(),
|
||||
resolutions: BTreeMap::new(),
|
||||
env: &env,
|
||||
fail_after_ops: None,
|
||||
},
|
||||
&|step, pct| println!("{pct}% {step}"),
|
||||
)?;
|
||||
assert_eq!(outcome.txn.state, update::State::Committed);
|
||||
assert_eq!(
|
||||
MetaDir::open(&meta)?.1.core.version.as_deref(),
|
||||
Some("2.0.0")
|
||||
);
|
||||
assert!(update::unfinished(&meta).is_none());
|
||||
assert_eq!(
|
||||
std::fs::read(root.join("Core/stabilization-success.txt"))?,
|
||||
b"verified update"
|
||||
);
|
||||
backup::with_database(root, |db| {
|
||||
assert_eq!(
|
||||
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?,
|
||||
"42"
|
||||
);
|
||||
assert_eq!(
|
||||
db.query("SELECT id FROM acore_characters.manager_recovery_view;")?,
|
||||
"42"
|
||||
);
|
||||
assert_eq!(
|
||||
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?,
|
||||
"44"
|
||||
);
|
||||
assert!(coa_core::migrations::status(db, &manifest.migrations)?
|
||||
.iter()
|
||||
.all(|m| m.status == coa_core::migrations::Status::Applied));
|
||||
Ok(())
|
||||
})?;
|
||||
restart_cycles(root)?;
|
||||
println!("PASS: signed update committed after failed rehearsal and recovery; SQL, files, metadata and player data verified; two native restart cycles passed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restart_cycles(root: &std::path::Path) -> Result<()> {
|
||||
for cycle in 0..2 {
|
||||
let stopped = driver::run(root, driver::Verb::StopAll)?;
|
||||
assert!(
|
||||
stopped.ok,
|
||||
"Stop cycle {cycle}: {}",
|
||||
coa_core::diag::redact(&stopped.output)
|
||||
);
|
||||
let started = driver::run(root, driver::Verb::StartAll)?;
|
||||
assert!(started.ok, "{}", started.output);
|
||||
let pop = coa_core::population::query(root)?;
|
||||
println!(
|
||||
"Restart cycle {cycle}: world ready, players={}, bots={}",
|
||||
pop.players_online, pop.bots_online
|
||||
);
|
||||
}
|
||||
println!("PASS: two native restart cycles finished");
|
||||
Ok(())
|
||||
}
|
||||
@@ -30,15 +30,27 @@ fn main() -> Result<()> {
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("coa-update-recovery-fixture-"));
|
||||
assert!(
|
||||
!root.join("recovery-e2e-started").exists(),
|
||||
"Use a new fixture; never reuse an owned server"
|
||||
);
|
||||
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
|
||||
let result = exercise(&root);
|
||||
let stopped = driver::run(&root, Verb::StopAll)?;
|
||||
assert!(stopped.ok);
|
||||
result
|
||||
let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered");
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
if resume {
|
||||
assert!(root.join("recovery-e2e-started").is_file());
|
||||
let manifest = coa_core::manifest::Manifest::parse(&std::fs::read(
|
||||
root.join("fixture-package/manifest.json"),
|
||||
)?)?;
|
||||
verify_recovered(&root, &manifest)
|
||||
} else {
|
||||
assert!(
|
||||
!root.join("recovery-e2e-started").exists(),
|
||||
"Use a new fixture"
|
||||
);
|
||||
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
|
||||
exercise(&root)
|
||||
}
|
||||
}));
|
||||
assert!(driver::run(&root, Verb::StopAll)?.ok);
|
||||
result.map_err(|_| {
|
||||
Error::Invalid("Recovery acceptance assertion failed; owned services were stopped".into())
|
||||
})?
|
||||
}
|
||||
|
||||
fn exercise(root: &Path) -> Result<()> {
|
||||
@@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> {
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("private update rehearsal failed"),
|
||||
.contains("files and databases were restored to the recovery point"),
|
||||
"{error}"
|
||||
);
|
||||
verify_recovered(root, &manifest)
|
||||
}
|
||||
|
||||
fn verify_recovered(root: &Path, manifest: &coa_core::manifest::Manifest) -> Result<()> {
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
let env = RepackEnv {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
assert!(!root.join("Core/recovery-probe.txt").exists());
|
||||
assert!(update::unfinished(&meta).is_none());
|
||||
assert_eq!(
|
||||
@@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> {
|
||||
Db::from_repack(root, Account::Admin)?.realm(),
|
||||
coa_core::realms::Mode::Coa
|
||||
);
|
||||
println!("PASS: private rehearsal caught failed SQL before changing the installed world, characters, ledger, objects, files or version; complete recovery succeeded");
|
||||
println!("PASS: failed SQL was rolled back; characters, world, ledger, views, triggers, routines, files and version were verified; the saved recovery point was restored again");
|
||||
Ok(())
|
||||
}
|
||||
@@ -80,6 +80,60 @@ fn upper(name: &str) -> Result<String> {
|
||||
Ok(name.to_ascii_uppercase())
|
||||
}
|
||||
|
||||
pub fn create(root: &Path, name: &str, password: &str, administrator: bool) -> Result<()> {
|
||||
validate_account(name, password)?;
|
||||
let name = name.to_ascii_uppercase();
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
if db
|
||||
.query(&format!(
|
||||
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
|
||||
))?
|
||||
.trim()
|
||||
!= "0"
|
||||
{
|
||||
return Err(Error::Invalid("That account name is already taken.".into()));
|
||||
}
|
||||
let mut ra = Ra::connect(root)?;
|
||||
ra.performance().map_err(|error| Error::Invalid(format!("The server console is not ready for account creation. No create command was sent. {error}")))?;
|
||||
let confirmed = ra.create_account(&name, password);
|
||||
if let Err(error) = confirmed {
|
||||
let stored = db.query(&format!(
|
||||
"SELECT HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username='{name}';"
|
||||
))?;
|
||||
if !matches_credentials(&stored, &name, password) {
|
||||
return Err(Error::Invalid(format!("Account creation was not confirmed. Refresh the account list before retrying. {error}")));
|
||||
}
|
||||
if administrator {
|
||||
ra = Ra::connect(root).map_err(|error| Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")))?;
|
||||
}
|
||||
}
|
||||
if administrator {
|
||||
if let Err(error) = ra.make_administrator(&name) {
|
||||
let access = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='{name}') AND gmlevel=3 AND RealmID=-1;"))?;
|
||||
if access.trim() != "1" {
|
||||
return Err(Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn matches_credentials(stored: &str, name: &str, password: &str) -> bool {
|
||||
let Some((salt, verifier)) = stored.trim().split_once('\t') else {
|
||||
return false;
|
||||
};
|
||||
let Ok(salt) = hex::decode(salt) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else {
|
||||
return false;
|
||||
};
|
||||
let Ok(verifier) = hex::decode(verifier) else {
|
||||
return false;
|
||||
};
|
||||
verifier.as_slice() == crate::srp6::verifier(name, password, &salt)
|
||||
}
|
||||
|
||||
/// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an
|
||||
/// account that is not logged in. The old name is put back if anything goes wrong.
|
||||
pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> {
|
||||
@@ -165,6 +219,19 @@ pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lost_reply_requires_the_exact_requested_credentials() {
|
||||
let salt = [42; 32];
|
||||
let verifier = crate::srp6::verifier("NewPlayer", "Password77", &salt);
|
||||
let stored = format!("{}\t{}\n", hex::encode(salt), hex::encode(verifier));
|
||||
assert!(matches_credentials(&stored, "NEWPLAYER", "password77"));
|
||||
assert!(!matches_credentials(&stored, "NEWPLAYER", "wrongpass"));
|
||||
assert!(!matches_credentials(&stored, "OTHERPLAYER", "Password77"));
|
||||
for value in ["", "NULL\tNULL", "00\t00", "malformed"] {
|
||||
assert!(!matches_credentials(value, "NewPlayer", "Password77"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_from_the_client_become_accounts() {
|
||||
let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n";
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! A catalog of game addons the Manager can install into a client's `Interface/AddOns`.
|
||||
//!
|
||||
//! Every addon is pinned to a commit of its GitHub repository; the catalog lists each file it installs with its
|
||||
//! git blob SHA-1 and size, which are checked after download (GitHub's archives are not byte-stable, their
|
||||
//! contents are). The Manager records what it installed in `Interface/AddOns/.coa-addons.json` and only ever
|
||||
//! removes or replaces those folders; a folder of the same name that someone else put there is moved to
|
||||
//! `Interface/AddOns/.coa-addons-backup` first.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use crate::download::{Cancel, Transport};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
static CATALOG: &str = include_str!("../../../addons/catalog.json");
|
||||
const STATE: &str = ".coa-addons.json";
|
||||
const BACKUP: &str = ".coa-addons-backup";
|
||||
/// No addon archive is anywhere near this; a larger answer is not what the catalog describes.
|
||||
const MAX_ARCHIVE: u64 = 1 << 30;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct AddonFile {
|
||||
path: String,
|
||||
from: String,
|
||||
sha1: String,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct Entry {
|
||||
id: String,
|
||||
name: String,
|
||||
description: BTreeMap<String, String>,
|
||||
author: String,
|
||||
license: String,
|
||||
#[serde(default)]
|
||||
needs: Option<String>,
|
||||
repo: String,
|
||||
commit: String,
|
||||
archive: String,
|
||||
folders: Vec<String>,
|
||||
files: Vec<AddonFile>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog {
|
||||
addons: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||
struct Installed {
|
||||
commit: String,
|
||||
folders: Vec<String>,
|
||||
}
|
||||
|
||||
/// One addon of the catalog as the Manager shows it for a client.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AddonView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: BTreeMap<String, String>,
|
||||
pub author: String,
|
||||
pub license: String,
|
||||
/// A server module the addon is made for (`playerbots`), shown as a hint.
|
||||
pub needs: Option<String>,
|
||||
pub repo: String,
|
||||
pub size: u64,
|
||||
pub installed: bool,
|
||||
pub update_available: bool,
|
||||
/// Folders of this addon that are in the client but were not installed by the Manager.
|
||||
pub foreign_folders: Vec<String>,
|
||||
/// Installed by something else, shown so nobody looks for it twice: `custom-races` (the client patch).
|
||||
pub bundled: Option<String>,
|
||||
}
|
||||
|
||||
fn catalog() -> Result<Vec<Entry>> {
|
||||
let catalog: Catalog = serde_json::from_str(CATALOG)?;
|
||||
for entry in &catalog.addons {
|
||||
for folder in &entry.folders {
|
||||
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
|
||||
return Err(Error::Invalid(format!("Invalid addon folder in the catalog: {folder}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(catalog.addons)
|
||||
}
|
||||
|
||||
fn addons_dir(client: &Path) -> PathBuf {
|
||||
client.join("Interface").join("AddOns")
|
||||
}
|
||||
|
||||
fn read_state(client: &Path) -> BTreeMap<String, Installed> {
|
||||
fsx::read_json(&addons_dir(client).join(STATE)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_state(client: &Path, state: &BTreeMap<String, Installed>) -> Result<()> {
|
||||
fsx::atomic_write_json(&addons_dir(client).join(STATE), state)
|
||||
}
|
||||
|
||||
/// The catalog with what is installed in `client`.
|
||||
pub fn list(client: &Path) -> Result<Vec<AddonView>> {
|
||||
let state = read_state(client);
|
||||
let dir = addons_dir(client);
|
||||
let owned: Vec<&String> = state.values().flat_map(|i| i.folders.iter()).collect();
|
||||
Ok(catalog()?
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let installed = state.get(&entry.id);
|
||||
AddonView {
|
||||
foreign_folders: entry
|
||||
.folders
|
||||
.iter()
|
||||
.filter(|f| dir.join(f).exists() && !owned.contains(f))
|
||||
.cloned()
|
||||
.collect(),
|
||||
size: entry.files.iter().map(|f| f.size).sum(),
|
||||
installed: installed.is_some(),
|
||||
update_available: installed.is_some_and(|i| i.commit != entry.commit),
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
description: entry.description,
|
||||
author: entry.author,
|
||||
license: entry.license,
|
||||
needs: entry.needs,
|
||||
repo: entry.repo,
|
||||
bundled: None,
|
||||
}
|
||||
})
|
||||
.chain(std::iter::once(dev_menu(&dir)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The /dev menu addon of Custom Races V2: the client patch installs it and switches it with the patch.
|
||||
fn dev_menu(dir: &Path) -> AddonView {
|
||||
let mut description = BTreeMap::new();
|
||||
for (lang, text) in [
|
||||
("en", "The in-game /dev editor for game masters. It comes with the Custom Races V2 client patch and is switched with it."),
|
||||
("ru", "Внутриигровой редактор /dev для гейм-мастеров. Ставится вместе с клиентским патчем Custom Races V2 и включается вместе с ним."),
|
||||
("de", "Der /dev-Editor im Spiel für Spielleiter. Er kommt mit dem Client-Patch Custom Races V2 und wird mit ihm geschaltet."),
|
||||
("fr", "L'éditeur /dev en jeu pour les maîtres du jeu. Il vient avec le patch client Custom Races V2 et s'active avec lui."),
|
||||
("es", "El editor /dev del juego para los máster. Viene con el parche de cliente Custom Races V2 y se activa con él."),
|
||||
("zh", "供游戏管理员使用的游戏内 /dev 编辑器。随 Custom Races V2 客户端补丁安装,并随补丁一起开关。"),
|
||||
] {
|
||||
description.insert(lang.to_string(), text.to_string());
|
||||
}
|
||||
AddonView {
|
||||
id: "coa-dev-menu".into(),
|
||||
name: "CoA Dev Menu".into(),
|
||||
description,
|
||||
author: "ilusixn".into(),
|
||||
license: "see repository".into(),
|
||||
needs: None,
|
||||
repo: "https://github.com/ilusixn/ilusixn-dev-menu".into(),
|
||||
size: 0,
|
||||
installed: dir.join("CoA_DevMenu/CoA_DevMenu.toc").is_file(),
|
||||
update_available: false,
|
||||
foreign_folders: Vec::new(),
|
||||
bundled: Some("custom-races".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The git blob id of `bytes` (what the catalog records for each file).
|
||||
fn git_blob_sha1(bytes: &[u8]) -> String {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
|
||||
hasher.update(bytes);
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
fn download(transport: &dyn Transport, url: &str, dest: &Path, cancel: &Cancel) -> Result<()> {
|
||||
crate::download::check_url(url)?;
|
||||
let reply = transport.get(url, 0).map_err(Error::Invalid)?;
|
||||
if reply.status != 200 {
|
||||
return Err(Error::Invalid(format!("The addon download answered HTTP {}.", reply.status)));
|
||||
}
|
||||
let mut body = reply.body.take(MAX_ARCHIVE + 1);
|
||||
let mut file = fs::File::create(dest)?;
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
let mut total = 0u64;
|
||||
loop {
|
||||
if cancel.is_set() {
|
||||
return Err(Error::Invalid("Operation cancelled.".into()));
|
||||
}
|
||||
let n = body.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > MAX_ARCHIVE {
|
||||
return Err(Error::Invalid("The addon download is larger than any catalog addon.".into()));
|
||||
}
|
||||
file.write_all(&buf[..n])?;
|
||||
}
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Unpack the catalog's files of `entry` from `archive` into `staging`, checking every one.
|
||||
fn unpack(entry: &Entry, archive: &Path, staging: &Path) -> Result<()> {
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(archive)?)
|
||||
.map_err(|e| Error::Invalid(format!("The addon download is not a zip archive: {e}")))?;
|
||||
// GitHub archives hold everything under one top folder (`<repo>-<commit>/`).
|
||||
let mut by_path = BTreeMap::new();
|
||||
for index in 0..zip.len() {
|
||||
let name = zip
|
||||
.by_index(index)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?
|
||||
.name()
|
||||
.replace('\\', "/");
|
||||
if let Some((_, inner)) = name.split_once('/') {
|
||||
by_path.insert(inner.to_string(), index);
|
||||
}
|
||||
}
|
||||
for file in &entry.files {
|
||||
let index = *by_path
|
||||
.get(&file.from)
|
||||
.ok_or_else(|| Error::Invalid(format!("The addon download lacks {}.", file.from)))?;
|
||||
let mut zipped = zip.by_index(index).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut bytes = Vec::with_capacity(file.size as usize);
|
||||
zipped.by_ref().take(file.size + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 != file.size || git_blob_sha1(&bytes) != file.sha1 {
|
||||
return Err(Error::Invalid(format!("{} failed verification.", file.from)));
|
||||
}
|
||||
let target = fsx::safe_join(staging, &file.path)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(target, bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stamp() -> String {
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S").to_string()
|
||||
}
|
||||
|
||||
/// Install or update `id` in `client` from `transport`.
|
||||
pub fn install_with(transport: &dyn Transport, client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
|
||||
if crate::client::is_running(client) {
|
||||
return Err(Error::Invalid("Close the game before installing addons.".into()));
|
||||
}
|
||||
let entry = catalog()?
|
||||
.into_iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| Error::Invalid(format!("Unknown addon {id}.")))?;
|
||||
install_entry(transport, client, &entry, cancel)?;
|
||||
list(client)
|
||||
}
|
||||
|
||||
fn install_entry(transport: &dyn Transport, client: &Path, entry: &Entry, cancel: &Cancel) -> Result<()> {
|
||||
let dir = addons_dir(client);
|
||||
fs::create_dir_all(&dir)?;
|
||||
// Staged next to AddOns' own folders, so the final moves stay on one volume even for a linked AddOns.
|
||||
let staging = tempfile::Builder::new().prefix(".coa-addon-").tempdir_in(&dir)?;
|
||||
let archive = staging.path().join("archive.zip");
|
||||
download(transport, &entry.archive, &archive, cancel)?;
|
||||
let unpacked = staging.path().join("files");
|
||||
unpack(entry, &archive, &unpacked)?;
|
||||
if cancel.is_set() {
|
||||
return Err(Error::Invalid("Operation cancelled.".into()));
|
||||
}
|
||||
let mut state = read_state(client);
|
||||
let ours: Vec<String> = state.values().flat_map(|i| i.folders.clone()).collect();
|
||||
// Move what is in the way out first, so a failed move leaves the client as it was.
|
||||
let mut moved: Vec<(PathBuf, PathBuf)> = Vec::new();
|
||||
let undo = |moved: &[(PathBuf, PathBuf)]| {
|
||||
for (from, to) in moved.iter().rev() {
|
||||
let _ = fs::rename(to, from);
|
||||
}
|
||||
};
|
||||
for folder in &entry.folders {
|
||||
let target = dir.join(folder);
|
||||
if !target.exists() {
|
||||
continue;
|
||||
}
|
||||
let aside = if ours.contains(folder) {
|
||||
staging.path().join("old").join(folder)
|
||||
} else {
|
||||
dir.join(BACKUP).join(format!("{folder}-{}", stamp()))
|
||||
};
|
||||
if let Some(parent) = aside.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if let Err(e) = fs::rename(&target, &aside) {
|
||||
undo(&moved);
|
||||
return Err(Error::Invalid(format!("{folder} is in use and could not be replaced: {e}")));
|
||||
}
|
||||
moved.push((target, aside));
|
||||
}
|
||||
let mut placed: Vec<PathBuf> = Vec::new();
|
||||
for folder in &entry.folders {
|
||||
let target = dir.join(folder);
|
||||
if let Err(e) = fs::rename(unpacked.join(folder), &target) {
|
||||
for p in &placed {
|
||||
let _ = fs::remove_dir_all(p);
|
||||
}
|
||||
undo(&moved);
|
||||
return Err(Error::Invalid(format!("{folder} could not be installed: {e}")));
|
||||
}
|
||||
placed.push(target);
|
||||
}
|
||||
state.insert(
|
||||
entry.id.clone(),
|
||||
Installed {
|
||||
commit: entry.commit.clone(),
|
||||
folders: entry.folders.clone(),
|
||||
},
|
||||
);
|
||||
write_state(client, &state)?;
|
||||
tracing::info!(addon = %entry.id, commit = %entry.commit, "addon installed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
|
||||
install_with(&crate::download::HttpTransport::with_total_timeout(1800)?, client, id, cancel)
|
||||
}
|
||||
|
||||
/// Remove an addon the Manager installed (only its recorded folders).
|
||||
pub fn remove(client: &Path, id: &str) -> Result<Vec<AddonView>> {
|
||||
if crate::client::is_running(client) {
|
||||
return Err(Error::Invalid("Close the game before removing addons.".into()));
|
||||
}
|
||||
let mut state = read_state(client);
|
||||
let Some(installed) = state.remove(id) else {
|
||||
return list(client);
|
||||
};
|
||||
let dir = addons_dir(client);
|
||||
for folder in &installed.folders {
|
||||
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let target = dir.join(folder);
|
||||
if target.exists() {
|
||||
fs::remove_dir_all(&target)?;
|
||||
}
|
||||
}
|
||||
write_state(client, &state)?;
|
||||
list(client)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::download::Reply;
|
||||
|
||||
struct Serve(Vec<u8>);
|
||||
impl Transport for Serve {
|
||||
fn get(&self, _: &str, _: u64) -> std::result::Result<Reply, String> {
|
||||
Ok(Reply { status: 200, content_range: None, body: Box::new(std::io::Cursor::new(self.0.clone())) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A GitHub-like archive of the catalog entry `id` with the given file bodies (path in repo -> bytes).
|
||||
fn archive(entry: &Entry, body: &dyn Fn(&AddonFile) -> Vec<u8>) -> Vec<u8> {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
let mut zip = zip::ZipWriter::new(&mut out);
|
||||
for file in &entry.files {
|
||||
zip.start_file(format!("repo-{}/{}", entry.commit, file.from), zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(&body(file)).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
/// A small catalog entry whose files hash to what the archive will hold.
|
||||
fn small_entry() -> Entry {
|
||||
let bytes = b"## Interface: 30300\n".to_vec();
|
||||
Entry {
|
||||
id: "t".into(),
|
||||
name: "T".into(),
|
||||
description: BTreeMap::new(),
|
||||
author: "a".into(),
|
||||
license: "x".into(),
|
||||
needs: None,
|
||||
repo: "r".into(),
|
||||
commit: "c1".into(),
|
||||
archive: "https://example.invalid/a.zip".into(),
|
||||
folders: vec!["TestAddon".into()],
|
||||
files: vec![AddonFile {
|
||||
path: "TestAddon/TestAddon.toc".into(),
|
||||
from: "TestAddon/TestAddon.toc".into(),
|
||||
sha1: git_blob_sha1(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_catalog_is_valid_and_pins_every_addon() {
|
||||
let entries = catalog().unwrap();
|
||||
assert!(entries.len() >= 4);
|
||||
let views = list(Path::new("C:/no-such-client")).unwrap();
|
||||
assert_eq!(views.iter().filter(|v| v.bundled.is_some()).count(), 1, "the dev menu is shown, not installable");
|
||||
for e in &entries {
|
||||
assert_eq!(e.commit.len(), 40, "{}", e.id);
|
||||
assert!(e.archive.starts_with("https://codeload.github.com/") && e.archive.ends_with(&e.commit));
|
||||
assert!(e.description.contains_key("en") && e.description.contains_key("ru"));
|
||||
for folder in &e.folders {
|
||||
assert!(e.files.iter().any(|f| f.path.eq_ignore_ascii_case(&format!("{folder}/{folder}.toc"))
|
||||
|| f.path.starts_with(&format!("{folder}/")) && f.path.ends_with(".toc")), "{folder} has no toc");
|
||||
}
|
||||
for f in &e.files {
|
||||
fsx::safe_join(Path::new("C:/x"), &f.path).unwrap();
|
||||
assert!(e.folders.iter().any(|folder| f.path.starts_with(&format!("{folder}/"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Downloads the catalog's small addons from GitHub"]
|
||||
fn the_real_catalog_installs_from_github() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
for id in ["incahoots", "coacombat", "squidbots-lite"] {
|
||||
let views = install(client.path(), id, &Cancel::default()).unwrap();
|
||||
let view = views.iter().find(|v| v.id == id).unwrap();
|
||||
assert!(view.installed && !view.update_available, "{id}");
|
||||
}
|
||||
assert!(addons_dir(client.path()).join("IncahootsCoA/IncahootsCoA.toc").is_file());
|
||||
assert!(addons_dir(client.path()).join("SquidBotsLite/SquidBotsLite.toc").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_blob_ids_match_git() {
|
||||
// `printf 'hello\n' | git hash-object --stdin`
|
||||
assert_eq!(git_blob_sha1(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
|
||||
}
|
||||
|
||||
fn unpack_and_place(entry: &Entry, client: &Path, bytes: Vec<u8>) -> Result<()> {
|
||||
let dir = addons_dir(client);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let staging = tempfile::tempdir_in(&dir)?;
|
||||
let archive = staging.path().join("a.zip");
|
||||
download(&Serve(bytes), &entry.archive, &archive, &Cancel::default())?;
|
||||
unpack(entry, &archive, &staging.path().join("files"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tampered_or_incomplete_download_is_refused() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let entry = small_entry();
|
||||
let good = archive(&entry, &|_| b"## Interface: 30300\n".to_vec());
|
||||
unpack_and_place(&entry, client.path(), good).unwrap();
|
||||
let bad = archive(&entry, &|_| b"## Interface: 30300 evil\n".to_vec());
|
||||
assert!(unpack_and_place(&entry, client.path(), bad).unwrap_err().to_string().contains("verification"));
|
||||
let empty = {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
zip::ZipWriter::new(&mut out).finish().unwrap();
|
||||
out.into_inner()
|
||||
};
|
||||
assert!(unpack_and_place(&entry, client.path(), empty).unwrap_err().to_string().contains("lacks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_update_and_remove_keep_other_folders() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let mut entry = small_entry();
|
||||
let dir = addons_dir(client.path());
|
||||
fs::create_dir_all(dir.join("TestAddon")).unwrap();
|
||||
fs::write(dir.join("TestAddon/mine.lua"), b"player's own").unwrap();
|
||||
fs::create_dir_all(dir.join("Other")).unwrap();
|
||||
let serve = Serve(archive(&entry, &|_| b"## Interface: 30300
|
||||
".to_vec()));
|
||||
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
|
||||
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
|
||||
assert!(!dir.join("TestAddon/mine.lua").exists(), "the player's folder was set aside");
|
||||
let backups: Vec<_> = fs::read_dir(dir.join(BACKUP)).unwrap().flatten().collect();
|
||||
assert_eq!(backups.len(), 1);
|
||||
assert!(backups[0].path().join("mine.lua").is_file());
|
||||
assert_eq!(read_state(client.path())["t"].commit, "c1");
|
||||
// An update replaces the Manager's own folder without another backup.
|
||||
entry.commit = "c2".into();
|
||||
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
|
||||
assert_eq!(read_state(client.path())["t"].commit, "c2");
|
||||
assert_eq!(fs::read_dir(dir.join(BACKUP)).unwrap().count(), 1);
|
||||
// A failed download changes nothing.
|
||||
let broken = Serve(archive(&entry, &|_| b"tampered".to_vec()));
|
||||
assert!(install_entry(&broken, client.path(), &entry, &Cancel::default()).is_err());
|
||||
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
|
||||
remove(client.path(), "t").unwrap();
|
||||
assert!(!dir.join("TestAddon").exists());
|
||||
assert!(dir.join("Other").is_dir());
|
||||
assert!(!read_state(client.path()).contains_key("t"));
|
||||
// No leftover staging folders.
|
||||
assert!(fs::read_dir(&dir).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with(".coa-addon-")));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented
|
||||
//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current
|
||||
//! settings come from `worldserver.conf.dist` and `modules/coa.conf.dist`, the current
|
||||
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
|
||||
//! the database connection is left out; the Manager owns those.
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::path::Path;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::config::parser::ConfFile;
|
||||
use crate::config::{take_snapshot, targets, Scope};
|
||||
use crate::config::{take_snapshot, targets, Scope, Targets};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
@@ -39,6 +39,14 @@ fn hidden(key: &str) -> bool {
|
||||
|| k.starts_with("logindatabase.")
|
||||
|| k.starts_with("worlddatabase.")
|
||||
|| k.starts_with("characterdatabase.")
|
||||
|| [
|
||||
"coa.classmodel",
|
||||
"coa.realmtype",
|
||||
"coa.gamemodemask",
|
||||
"coa.mapclass10towarrior",
|
||||
"coa.clientbooleanconfigs",
|
||||
]
|
||||
.contains(&k.as_str())
|
||||
|| [
|
||||
"bindip",
|
||||
"realmid",
|
||||
@@ -121,52 +129,85 @@ fn dist_path(root: &Path) -> std::path::PathBuf {
|
||||
root.join("Core/configs/worldserver.conf.dist")
|
||||
}
|
||||
|
||||
fn sources(root: &Path) -> Result<Vec<(std::path::PathBuf, Targets)>> {
|
||||
let mut result = vec![(dist_path(root), targets(root, Scope::Server)?)];
|
||||
let dist = root.join("Core/configs/modules/coa.conf.dist");
|
||||
if dist.is_file() {
|
||||
let active = root.join("Core/configs/modules/coa.conf");
|
||||
result.push((
|
||||
dist,
|
||||
Targets {
|
||||
read: active.clone(),
|
||||
writes: vec![active],
|
||||
generated: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn list(root: &Path) -> Result<Vec<Item>> {
|
||||
let dist = fs::read_to_string(dist_path(root)).map_err(|_| {
|
||||
Error::Invalid(
|
||||
"The documented settings file (worldserver.conf.dist) was not found on this server."
|
||||
.into(),
|
||||
)
|
||||
})?;
|
||||
let t = targets(root, Scope::Server)?;
|
||||
let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?;
|
||||
Ok(parse_dist(&dist)
|
||||
.into_iter()
|
||||
.filter(|(k, _, _)| !hidden(k))
|
||||
.map(|(key, default, doc)| {
|
||||
let value = active
|
||||
.get(&key)
|
||||
.map(|v| v.trim().to_string())
|
||||
.unwrap_or_else(|| default.clone());
|
||||
let changed = value != default;
|
||||
Item {
|
||||
key,
|
||||
value,
|
||||
default,
|
||||
doc,
|
||||
changed,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
let mut items = Vec::new();
|
||||
for (dist_path, t) in sources(root)? {
|
||||
let dist = fs::read_to_string(&dist_path)?;
|
||||
let active = ConfFile::parse_bytes(&if t.read.exists() {
|
||||
fs::read(&t.read)?
|
||||
} else {
|
||||
dist.as_bytes().to_vec()
|
||||
})?;
|
||||
items.extend(
|
||||
parse_dist(&dist)
|
||||
.into_iter()
|
||||
.filter(|(k, _, _)| !hidden(k))
|
||||
.map(|(key, default, doc)| {
|
||||
let value = active
|
||||
.get(&key)
|
||||
.map(|v| v.trim().to_string())
|
||||
.unwrap_or_else(|| default.clone());
|
||||
let changed = value != default;
|
||||
Item {
|
||||
key,
|
||||
value,
|
||||
default,
|
||||
doc,
|
||||
changed,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
|
||||
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
|
||||
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
|
||||
let known: BTreeMap<String, String> =
|
||||
parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| {
|
||||
Error::Invalid("worldserver.conf.dist was not found on this server.".into())
|
||||
})?)
|
||||
.into_iter()
|
||||
.map(|(k, d, _)| (k, d))
|
||||
.collect();
|
||||
let t = targets(root, Scope::Server)?;
|
||||
let _lock = crate::update::operation_lock(meta)?;
|
||||
crate::update::ensure_recovered(meta)?;
|
||||
let sources = sources(root)?;
|
||||
let mut known = BTreeMap::new();
|
||||
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
|
||||
let mut confs: Vec<ConfFile> = Vec::new();
|
||||
for p in &t.writes {
|
||||
let bytes = fs::read(p)?;
|
||||
confs.push(ConfFile::parse_bytes(&bytes)?);
|
||||
originals.push((p.clone(), bytes));
|
||||
let mut owners = Vec::new();
|
||||
for (index, (dist, t)) in sources.iter().enumerate() {
|
||||
let defaults = fs::read(dist)?;
|
||||
for (key, default, _) in parse_dist(&String::from_utf8_lossy(&defaults)) {
|
||||
if known.insert(key.clone(), (default, index)).is_some() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"{key} is documented in more than one configuration file."
|
||||
)));
|
||||
}
|
||||
}
|
||||
for p in &t.writes {
|
||||
let bytes = if p.exists() {
|
||||
fs::read(p)?
|
||||
} else {
|
||||
defaults.clone()
|
||||
};
|
||||
confs.push(ConfFile::parse_bytes(&bytes)?);
|
||||
originals.push((p.clone(), bytes));
|
||||
owners.push(index);
|
||||
}
|
||||
}
|
||||
let mut changed = Vec::new();
|
||||
for (key, value) in changes {
|
||||
@@ -181,10 +222,22 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
||||
"The value of {key} must be one line of text."
|
||||
)));
|
||||
}
|
||||
let same = confs.iter().all(|c| match c.get(key) {
|
||||
Some(v) => v.trim() == value,
|
||||
None => known[key] == value,
|
||||
});
|
||||
let (default, owner) = &known[key];
|
||||
if default.parse::<f64>().is_ok() && !value.parse::<f64>().is_ok_and(f64::is_finite)
|
||||
|| key == "CoA.LegacyMountFlight" && !matches!(value, "0" | "1")
|
||||
{
|
||||
return Err(Error::Invalid(format!(
|
||||
"The value of {key} must be a number matching its documented default."
|
||||
)));
|
||||
}
|
||||
let same = confs
|
||||
.iter()
|
||||
.zip(&owners)
|
||||
.filter(|(_, index)| *index == owner)
|
||||
.all(|(c, _)| match c.get(key) {
|
||||
Some(v) => v.trim() == value,
|
||||
None => default == value,
|
||||
});
|
||||
if !same {
|
||||
changed.push((key.clone(), value.to_string()));
|
||||
}
|
||||
@@ -192,20 +245,31 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
||||
if changed.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
for c in &mut confs {
|
||||
for (c, owner) in confs.iter_mut().zip(&owners) {
|
||||
for (k, v) in &changed {
|
||||
c.set(k, v, &["Added by CoA Server Manager"]);
|
||||
if known[k].1 == *owner {
|
||||
c.set(k, v, &["Added by CoA Server Manager"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
|
||||
for text in &texts {
|
||||
for (text, owner) in texts.iter().zip(&owners) {
|
||||
let reread = ConfFile::parse(text);
|
||||
for (k, v) in &changed {
|
||||
if reread.get(k).map(str::trim) != Some(v.as_str()) {
|
||||
if known[k].1 == *owner && reread.get(k).map(str::trim) != Some(v.as_str()) {
|
||||
return Err(Error::Invalid(format!("internal check failed for {k}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
let affected: std::collections::BTreeSet<_> =
|
||||
changed.iter().map(|(key, _)| known[key].1).collect();
|
||||
let (originals, texts): (Vec<_>, Vec<_>) = originals
|
||||
.into_iter()
|
||||
.zip(texts)
|
||||
.zip(owners)
|
||||
.filter(|(_, owner)| affected.contains(owner))
|
||||
.map(|(pair, _)| pair)
|
||||
.unzip();
|
||||
take_snapshot(
|
||||
meta,
|
||||
Scope::Server,
|
||||
@@ -232,6 +296,114 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unrelated_saves_do_not_create_coa_files_and_existing_realm_values_are_preserved() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, meta) = server(d.path());
|
||||
let module = root.join("Core/configs/modules");
|
||||
fs::create_dir_all(&module).unwrap();
|
||||
fs::write(
|
||||
module.join("coa.conf.dist"),
|
||||
"CoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
save(
|
||||
&root,
|
||||
&meta,
|
||||
&BTreeMap::from([("Rate.Drop.Item.Rare".into(), "1.5".into())]),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!module.join("coa.conf").exists());
|
||||
fs::write(
|
||||
module.join("coa.conf"),
|
||||
"# Reborn realm\nCoA.ClassModel = \"wcr\"\nCustom.Preserved = 42\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(save(
|
||||
&root,
|
||||
&meta,
|
||||
&BTreeMap::from([("CoA.ClassModel".into(), "\"coa\"".into())])
|
||||
)
|
||||
.is_err());
|
||||
save(
|
||||
&root,
|
||||
&meta,
|
||||
&BTreeMap::from([("CoA.LegacyMountFlight".into(), "1".into())]),
|
||||
)
|
||||
.unwrap();
|
||||
let actual = fs::read_to_string(module.join("coa.conf")).unwrap();
|
||||
assert!(
|
||||
actual.contains("CoA.ClassModel = \"wcr\"") && actual.contains("Custom.Preserved = 42")
|
||||
);
|
||||
assert!(actual.contains("# Reborn realm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coa_settings_are_found_saved_to_the_module_and_snapshotted_without_profile_overrides() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, meta) = server(d.path());
|
||||
let module = root.join("Core/configs/modules");
|
||||
fs::create_dir_all(&module).unwrap();
|
||||
let defaults = "[worldserver]\n# Mount flight rules\nCoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\nCoA.RealmType = \"live\"\n";
|
||||
fs::write(module.join("coa.conf.dist"), defaults).unwrap();
|
||||
let original_world = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||
let items = list(&root).unwrap();
|
||||
assert!(items
|
||||
.iter()
|
||||
.any(|i| i.key == "CoA.LegacyMountFlight" && i.value == "0"));
|
||||
assert!(!items
|
||||
.iter()
|
||||
.any(|i| i.key == "CoA.ClassModel" || i.key == "CoA.RealmType"));
|
||||
for value in ["2", "invalid", "1\nInjected = 1"] {
|
||||
assert!(save(
|
||||
&root,
|
||||
&meta,
|
||||
&BTreeMap::from([("CoA.LegacyMountFlight".into(), value.into())])
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
assert!(!module.join("coa.conf").exists());
|
||||
save(
|
||||
&root,
|
||||
&meta,
|
||||
&BTreeMap::from([
|
||||
("CoA.LegacyMountFlight".into(), "1".into()),
|
||||
("Rate.Drop.Item.Rare".into(), "1.5".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(fs::read_to_string(module.join("coa.conf"))
|
||||
.unwrap()
|
||||
.contains("CoA.LegacyMountFlight = 1"));
|
||||
let world = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||
assert!(!world.contains("CoA.LegacyMountFlight"));
|
||||
assert!(world.contains("Rate.Drop.Item.Rare = 1.5"));
|
||||
assert!(!String::from_utf8(original_world)
|
||||
.unwrap()
|
||||
.contains("CoA.LegacyMountFlight"));
|
||||
assert_eq!(
|
||||
list(&root)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i.key == "CoA.LegacyMountFlight")
|
||||
.unwrap()
|
||||
.value,
|
||||
"1"
|
||||
);
|
||||
assert!(!crate::config::list_snapshots(&meta).is_empty());
|
||||
let saved = crate::config::list_snapshots(&meta).remove(0);
|
||||
crate::config::restore_snapshot(&meta, &saved.id).unwrap();
|
||||
assert_eq!(
|
||||
list(&root)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i.key == "CoA.LegacyMountFlight")
|
||||
.unwrap()
|
||||
.value,
|
||||
"0"
|
||||
);
|
||||
}
|
||||
|
||||
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
|
||||
|
||||
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
||||
|
||||
@@ -308,7 +308,9 @@ pub fn with_database<T>(root: &Path, f: impl FnOnce(&Db) -> Result<T>) -> Result
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let observed = process::observe(root, &read_ports(root));
|
||||
let mysql_was_up = observed.mysql.state == ServiceState::Running && db.ping();
|
||||
if !mysql_was_up {
|
||||
let db = if mysql_was_up {
|
||||
db
|
||||
} else {
|
||||
let out = driver::run(root, Verb::StartMysql)?;
|
||||
if !out.ok {
|
||||
// Keep the launcher's own last lines: the title alone ("Something went wrong") hides the cause.
|
||||
@@ -317,7 +319,9 @@ pub fn with_database<T>(root: &Path, f: impl FnOnce(&Db) -> Result<T>) -> Result
|
||||
driver::startup_failure(root, &out)
|
||||
)));
|
||||
}
|
||||
}
|
||||
// The start may have moved the database to another port (a reserved or taken one).
|
||||
Db::from_repack(root, Account::Admin)?
|
||||
};
|
||||
let result = f(&db);
|
||||
if !mysql_was_up {
|
||||
let now = process::observe(root, &read_ports(root));
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Update-only comparison of existing unsupported character starts. Never repairs or deletes rows.
|
||||
use crate::{db::Db, Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct MissingStart {
|
||||
pub guid: u32,
|
||||
pub race: u32,
|
||||
pub class: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Baseline {
|
||||
pub schema: u32,
|
||||
pub realms: BTreeMap<String, BTreeSet<MissingStart>>,
|
||||
}
|
||||
|
||||
pub fn parse_missing(text: &str) -> Result<BTreeSet<MissingStart>> {
|
||||
text.lines()
|
||||
.map(|line| {
|
||||
let values = line
|
||||
.split('\t')
|
||||
.map(str::parse::<u32>)
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(|_| {
|
||||
Error::Invalid("Cannot read existing character start identities.".into())
|
||||
})?;
|
||||
if values.len() != 3 {
|
||||
return Err(Error::Invalid(
|
||||
"Incomplete character start identity.".into(),
|
||||
));
|
||||
}
|
||||
Ok(MissingStart {
|
||||
guid: values[0],
|
||||
race: values[1],
|
||||
class: values[2],
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn missing(db: &Db) -> Result<BTreeSet<MissingStart>> {
|
||||
parse_missing(&db.query("SELECT c.guid,c.race,c.class FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL;")?)
|
||||
}
|
||||
|
||||
pub fn capture(db: &Db, root: &Path) -> Result<Baseline> {
|
||||
let mut realms = BTreeMap::new();
|
||||
for mode in crate::realms::state(root)?.modes() {
|
||||
realms.insert(
|
||||
mode.name().to_owned(),
|
||||
missing(&db.clone().for_realm(mode))?,
|
||||
);
|
||||
}
|
||||
Ok(Baseline { schema: 1, realms })
|
||||
}
|
||||
|
||||
/// Match identity and race/class, never just totals: one new failure cannot replace an old one.
|
||||
pub fn introduced(
|
||||
current: &BTreeSet<MissingStart>,
|
||||
before: &BTreeSet<MissingStart>,
|
||||
) -> BTreeSet<MissingStart> {
|
||||
current.difference(before).copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn old_gaps_are_not_new_character_loss() {
|
||||
let before = parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14").unwrap();
|
||||
assert!(introduced(&before, &before).is_empty());
|
||||
assert!(introduced(&BTreeSet::new(), &before).is_empty());
|
||||
let replaced = parse_missing("1\t44\t14\n2\t44\t14\n4\t44\t14").unwrap();
|
||||
assert_eq!(
|
||||
introduced(&replaced, &before),
|
||||
parse_missing("4\t44\t14").unwrap()
|
||||
);
|
||||
let changed = parse_missing("1\t44\t15").unwrap();
|
||||
assert_eq!(introduced(&changed, &before), changed);
|
||||
assert_eq!(introduced(&before, &BTreeSet::new()), before);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_identity_is_not_silently_ignored() {
|
||||
for text in ["1\t44", "bad\t44\t14", "1\t44\t14\t0", "1\t44\t-1"] {
|
||||
assert!(parse_missing(text).is_err());
|
||||
}
|
||||
assert!(parse_missing("").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_174_old_records_cannot_mask_one_newly_hidden_character() {
|
||||
// Reproduce the report's scale without shipping another person's diagnostics or identities.
|
||||
let before: BTreeSet<_> = (1..=174)
|
||||
.map(|guid| MissingStart {
|
||||
guid,
|
||||
race: 44,
|
||||
class: 14,
|
||||
})
|
||||
.collect();
|
||||
assert!(introduced(&before, &before).is_empty());
|
||||
let mut after = before.clone();
|
||||
after.remove(&MissingStart {
|
||||
guid: 1,
|
||||
race: 44,
|
||||
class: 14,
|
||||
});
|
||||
after.insert(MissingStart {
|
||||
guid: 175,
|
||||
race: 44,
|
||||
class: 14,
|
||||
});
|
||||
assert_eq!(after.len(), before.len());
|
||||
assert_eq!(
|
||||
introduced(&after, &before),
|
||||
BTreeSet::from([MissingStart {
|
||||
guid: 175,
|
||||
race: 44,
|
||||
class: 14
|
||||
}])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,8 @@ use crate::fsx;
|
||||
pub use crate::glue_config;
|
||||
|
||||
pub const ADDON_NAME: &str = "CoABotUI";
|
||||
const EXECUTABLES: [&str; 3] = ["Ascension.exe", "Wow.exe", "WoW.exe"];
|
||||
// CoA Custom Races V2 ships its own client (CoACustomRace.exe) next to Ascension.exe and must be started instead.
|
||||
const EXECUTABLES: [&str; 4] = ["CoACustomRace.exe", "Ascension.exe", "Wow.exe", "WoW.exe"];
|
||||
|
||||
pub fn is_running(client: &Path) -> bool {
|
||||
if crate::platform::flavor() == crate::platform::Flavor::Docker {
|
||||
@@ -71,13 +72,23 @@ fn realm_config(old: &[u8], realm: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
pub fn sync_realm(client: &Path, meta: &Path, mode: crate::realms::Mode) -> Result<bool> {
|
||||
sync_realm_when_closed(client, meta, mode, is_running(client))
|
||||
let realm = match mode {
|
||||
crate::realms::Mode::Coa => "Conquest of Azeroth",
|
||||
crate::realms::Mode::Wildcard => "Wildcard",
|
||||
crate::realms::Mode::Reborn => "Warcraft Reborn",
|
||||
};
|
||||
sync_realm_when_closed(client, meta, realm, is_running(client))
|
||||
}
|
||||
|
||||
/// [`sync_realm`] with the realm's name as the server shows it (the owner may have renamed it).
|
||||
pub fn sync_realm_named(client: &Path, meta: &Path, realm: &str) -> Result<bool> {
|
||||
sync_realm_when_closed(client, meta, realm, is_running(client))
|
||||
}
|
||||
|
||||
fn sync_realm_when_closed(
|
||||
client: &Path,
|
||||
meta: &Path,
|
||||
mode: crate::realms::Mode,
|
||||
realm: &str,
|
||||
running: bool,
|
||||
) -> Result<bool> {
|
||||
if running {
|
||||
@@ -89,11 +100,6 @@ fn sync_realm_when_closed(
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let realm = match mode {
|
||||
crate::realms::Mode::Coa => "Conquest of Azeroth",
|
||||
crate::realms::Mode::Wildcard => "Wildcard",
|
||||
crate::realms::Mode::Reborn => "Warcraft Reborn",
|
||||
};
|
||||
let new = realm_config(&old, realm);
|
||||
if new == old {
|
||||
return Ok(true);
|
||||
@@ -409,6 +415,38 @@ pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the game's cache of server data (`Cache/WDB/<locale>/*.wdb`: creatures, items, quests, pages). The client
|
||||
/// keeps answers it got from a server; after the server's data changes they show old names and stats until the
|
||||
/// cache is gone. Only `.wdb` files under `Cache/WDB` are removed. Returns how many.
|
||||
pub fn clear_game_cache(client: &Path) -> Result<usize> {
|
||||
if is_running(client) {
|
||||
return Ok(0);
|
||||
}
|
||||
let root = client.join("Cache").join("WDB");
|
||||
let mut removed = 0;
|
||||
let Ok(locales) = fs::read_dir(&root) else {
|
||||
return Ok(0);
|
||||
};
|
||||
for locale in locales.flatten() {
|
||||
if !locale.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(files) = fs::read_dir(locale.path()) else {
|
||||
continue;
|
||||
};
|
||||
for file in files.flatten() {
|
||||
let path = file.path();
|
||||
let is_wdb = path
|
||||
.extension()
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case("wdb"));
|
||||
if is_wdb && file.file_type().is_ok_and(|t| t.is_file()) && fs::remove_file(&path).is_ok() {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Start the game client. The caller is responsible for making sure the server is ready first.
|
||||
pub fn launch(client: &Path) -> Result<u32> {
|
||||
let exe =
|
||||
@@ -607,6 +645,23 @@ pub fn recover_all_realmlist_overrides(meta_roots: &[PathBuf]) -> usize {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_the_server_data_cache_is_cleared() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let wdb = d.path().join("Cache/WDB/enUS");
|
||||
fs::create_dir_all(&wdb).unwrap();
|
||||
fs::write(wdb.join("creaturecache.wdb"), b"x").unwrap();
|
||||
fs::write(wdb.join("itemcache.WDB"), b"x").unwrap();
|
||||
fs::write(wdb.join("notes.txt"), b"keep").unwrap();
|
||||
fs::create_dir_all(d.path().join("Data/Retail/Cache")).unwrap();
|
||||
fs::write(d.path().join("Data/Retail/Cache/id-1.bin"), b"keep").unwrap();
|
||||
assert_eq!(clear_game_cache(d.path()).unwrap(), 2);
|
||||
assert!(wdb.join("notes.txt").is_file());
|
||||
assert!(d.path().join("Data/Retail/Cache/id-1.bin").is_file());
|
||||
assert_eq!(clear_game_cache(d.path()).unwrap(), 0);
|
||||
assert_eq!(clear_game_cache(&d.path().join("missing")).unwrap(), 0);
|
||||
}
|
||||
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
@@ -677,10 +732,10 @@ mod tests {
|
||||
let meta = d.path().join("meta");
|
||||
let original = b"SET realmName \"Wildcard\"\n";
|
||||
fs::write(c.join("WTF/Config.wtf"), original).unwrap();
|
||||
assert!(!sync_realm_when_closed(&c, &meta, crate::realms::Mode::Coa, true).unwrap());
|
||||
assert!(!sync_realm_when_closed(&c, &meta, "Conquest of Azeroth", true).unwrap());
|
||||
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
|
||||
assert!(!backup_dir(&meta).exists());
|
||||
assert!(sync_realm_when_closed(&c, &meta, crate::realms::Mode::Coa, false).unwrap());
|
||||
assert!(sync_realm_when_closed(&c, &meta, "Conquest of Azeroth", false).unwrap());
|
||||
assert_eq!(
|
||||
fs::read(c.join("WTF/Config.wtf")).unwrap(),
|
||||
b"SET realmName \"Conquest of Azeroth\"\n"
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
use crate::{fsx, Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fs, path::Path};
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct Graphics {
|
||||
pub dxvk_disabled: bool,
|
||||
pub enhancements_disabled: bool,
|
||||
}
|
||||
|
||||
fn preferences(client: &Path) -> Result<Option<Graphics>> {
|
||||
match fs::read(client.join(".coa-manager/graphics.json")) {
|
||||
Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(client: &Path) -> Result<Graphics> {
|
||||
let saved = preferences(client)?.unwrap_or_default();
|
||||
let actual = |name: &str, remembered: bool| -> Result<bool> {
|
||||
let active = client.join(name).is_file();
|
||||
let inactive = client.join(format!("{name}.DISABLED")).is_file();
|
||||
if active && inactive {
|
||||
return Err(Error::Invalid(
|
||||
"Both enabled and disabled renderer files exist.".into(),
|
||||
));
|
||||
}
|
||||
Ok(inactive || (!active && remembered))
|
||||
};
|
||||
Ok(Graphics {
|
||||
dxvk_disabled: actual("d3d9.dll", saved.dxvk_disabled)?,
|
||||
enhancements_disabled: actual("dxgi.dll", saved.enhancements_disabled)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn disabled(client: &Path, path: &str) -> Result<bool> {
|
||||
let name = path.to_ascii_lowercase();
|
||||
if !matches!(name.as_str(), "d3d9.dll" | "dxgi.dll") {
|
||||
return Ok(false);
|
||||
}
|
||||
let state = status(client)?;
|
||||
Ok(if name == "d3d9.dll" {
|
||||
state.dxvk_disabled
|
||||
} else {
|
||||
state.enhancements_disabled
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set(client: &Path, name: &str, disabled: bool) -> Result<Graphics> {
|
||||
if !matches!(name, "d3d9.dll" | "dxgi.dll") {
|
||||
return Err(Error::Invalid("Unknown graphics setting.".into()));
|
||||
}
|
||||
if crate::client::is_running(client) {
|
||||
return Err(Error::Invalid(
|
||||
"Close the game before changing graphics settings.".into(),
|
||||
));
|
||||
}
|
||||
let active = fsx::safe_join(client, name)?;
|
||||
let inactive = fsx::safe_join(client, &format!("{name}.DISABLED"))?;
|
||||
if active.exists() && inactive.exists() {
|
||||
return Err(Error::Invalid("Both enabled and disabled renderer files exist. Resolve the conflict before changing graphics settings.".into()));
|
||||
}
|
||||
let mut state = status(client)?;
|
||||
if name == "d3d9.dll" {
|
||||
state.dxvk_disabled = disabled;
|
||||
} else {
|
||||
state.enhancements_disabled = disabled;
|
||||
}
|
||||
let (source, target) = if disabled {
|
||||
(&active, &inactive)
|
||||
} else {
|
||||
(&inactive, &active)
|
||||
};
|
||||
// The no-clobber link also preserves an existing destination if another app changes the setting.
|
||||
if source.is_file() {
|
||||
if let Err(error) = fs::hard_link(source, target) {
|
||||
if error.kind() == std::io::ErrorKind::AlreadyExists {
|
||||
return Err(error.into());
|
||||
}
|
||||
let mut output = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(target)?;
|
||||
let copied = std::fs::File::open(source)
|
||||
.and_then(|mut input| std::io::copy(&mut input, &mut output))
|
||||
.and_then(|_| output.sync_all());
|
||||
drop(output);
|
||||
if let Err(error) = copied {
|
||||
let _ = fs::remove_file(target);
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
if let Err(error) = fs::remove_file(source) {
|
||||
let _ = fs::remove_file(target);
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
fsx::atomic_write_json(&client.join(".coa-manager/graphics.json"), &state)?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn toggles_preserve_bytes_and_refuse_conflicts() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
fs::write(root.join("d3d9.dll"), b"custom renderer").unwrap();
|
||||
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
|
||||
assert!(!root.join("d3d9.dll").exists());
|
||||
assert_eq!(
|
||||
fs::read(root.join("d3d9.dll.DISABLED")).unwrap(),
|
||||
b"custom renderer"
|
||||
);
|
||||
assert!(!set(root, "d3d9.dll", false).unwrap().dxvk_disabled);
|
||||
fs::write(root.join("d3d9.dll.DISABLED"), b"other").unwrap();
|
||||
assert!(set(root, "d3d9.dll", false).is_err());
|
||||
assert_eq!(fs::read(root.join("d3d9.dll")).unwrap(), b"custom renderer");
|
||||
assert_eq!(fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), b"other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remembers_missing_wrapper_and_imports_launcher_marker() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
|
||||
assert!(disabled(root, "d3d9.dll").unwrap());
|
||||
fs::write(root.join("dxgi.dll.DISABLED"), b"launcher disabled").unwrap();
|
||||
assert!(disabled(root, "dxgi.dll").unwrap());
|
||||
assert!(!disabled(root, "Data/d3d9.dll").unwrap());
|
||||
}
|
||||
}
|
||||
@@ -299,6 +299,11 @@ pub fn plan(
|
||||
bytes_per_sec: 0,
|
||||
file: Some(f.path.clone()),
|
||||
});
|
||||
if crate::client_graphics::disabled(client, &f.path)? {
|
||||
kept += 1;
|
||||
done += f.size;
|
||||
continue;
|
||||
}
|
||||
let path = fsx::safe_join(client, &f.path)?;
|
||||
let meta = match fs::metadata(&path) {
|
||||
Ok(meta) if meta.is_file() => meta,
|
||||
@@ -440,6 +445,9 @@ pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
|
||||
|
||||
let mut todo = Vec::new();
|
||||
for item in &a.plan.items {
|
||||
if crate::client_graphics::disabled(a.client, &item.path)? {
|
||||
continue;
|
||||
}
|
||||
if item.kind == Kind::Modified && a.keep_modified {
|
||||
let path = fsx::safe_join(a.client, &item.path)?;
|
||||
let meta = fs::metadata(&path)?;
|
||||
@@ -777,6 +785,52 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")];
|
||||
let manifest = manifest("v1", &files);
|
||||
let cancel = Cancel::default();
|
||||
let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap();
|
||||
fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap();
|
||||
crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap();
|
||||
let server = Server::new(&files);
|
||||
apply(
|
||||
&Apply {
|
||||
client: dir.path(),
|
||||
manifest: &manifest,
|
||||
plan: &old_plan,
|
||||
keep_modified: false,
|
||||
transport: &server,
|
||||
objects_url: "https://x.invalid/objects",
|
||||
cancel: &cancel,
|
||||
},
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(server.requested.lock().unwrap().is_empty());
|
||||
assert!(!dir.path().join("d3d9.dll").exists());
|
||||
assert!(!dir.path().join("dxgi.dll").exists());
|
||||
assert_eq!(
|
||||
fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(),
|
||||
b"custom disabled"
|
||||
);
|
||||
let after = plan(
|
||||
dir.path(),
|
||||
&manifest,
|
||||
&load_state(dir.path()).unwrap(),
|
||||
&cancel,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(after.items.is_empty());
|
||||
crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap();
|
||||
assert_eq!(
|
||||
fs::read(dir.path().join("d3d9.dll")).unwrap(),
|
||||
b"custom disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1034,6 +1034,31 @@ Spellbook.New = 5
|
||||
assert!(v.drift_keys.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_controls_persist_and_reject_invalid_gains() {
|
||||
let (_d, root, meta) = fixture();
|
||||
let changes = BTreeMap::from([
|
||||
("SkillChance.Prospecting".into(), json!(true)),
|
||||
("SkillChance.Milling".into(), json!(true)),
|
||||
("SkillGain.Crafting".into(), json!(3)),
|
||||
("SkillGain.Defense".into(), json!(4)),
|
||||
("SkillGain.Gathering".into(), json!(5)),
|
||||
]);
|
||||
let report = save(&root, &meta, Scope::Server, &changes).unwrap();
|
||||
assert_eq!(report.changed.len(), 5);
|
||||
assert_eq!(report.restart, Some(Restart::World));
|
||||
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
|
||||
let conf = load_conf(&root.join(path)).unwrap();
|
||||
for (key, expected) in [("SkillChance.Prospecting", "1"), ("SkillChance.Milling", "1"), ("SkillGain.Crafting", "3"), ("SkillGain.Defense", "4"), ("SkillGain.Gathering", "5")] {
|
||||
assert_eq!(conf.get(key), Some(expected));
|
||||
}
|
||||
assert_eq!(conf.get("Unknown.Custom"), Some("\"keep me\""));
|
||||
}
|
||||
for value in [json!(-1), json!(1.5), json!(451)] {
|
||||
assert!(save(&root, &meta, Scope::Server, &BTreeMap::from([("SkillGain.Crafting".into(), value)])).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creature_rates_save_independently_in_template_and_active_config() {
|
||||
let (_d, root, meta) = fixture();
|
||||
|
||||
@@ -214,11 +214,13 @@ fn run(
|
||||
struct StreamWorker {
|
||||
tx: Sender<TunnelMsg>,
|
||||
reset_on_drop: bool,
|
||||
shutdown: Arc<TcpStream>,
|
||||
}
|
||||
|
||||
impl Drop for StreamWorker {
|
||||
fn drop(&mut self) {
|
||||
if self.reset_on_drop {
|
||||
let _ = self.shutdown.shutdown(std::net::Shutdown::Both);
|
||||
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
|
||||
}
|
||||
}
|
||||
@@ -388,6 +390,8 @@ fn session(
|
||||
};
|
||||
match TcpStream::connect(("127.0.0.1", local_port)) {
|
||||
Ok(tcp) => {
|
||||
let tcp = Arc::new(tcp);
|
||||
let shutdown = tcp.clone();
|
||||
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
|
||||
let ws_tx = ws_out_tx.clone();
|
||||
|
||||
@@ -398,6 +402,7 @@ fn session(
|
||||
StreamWorker {
|
||||
tx: stream_tx,
|
||||
reset_on_drop: true,
|
||||
shutdown,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -456,19 +461,20 @@ fn session(
|
||||
|
||||
fn spawn_local_tcp_bridge(
|
||||
stream_id: u32,
|
||||
mut tcp: TcpStream,
|
||||
tcp: Arc<TcpStream>,
|
||||
from_tunnel: Receiver<TunnelMsg>,
|
||||
to_tunnel: Sender<TunnelMsg>,
|
||||
) {
|
||||
let _ = tcp.set_nonblocking(false);
|
||||
let _ = tcp.set_nodelay(true);
|
||||
let mut tcp_read = tcp.try_clone().expect("tcp clone");
|
||||
let tcp_read = tcp.clone();
|
||||
let to_tunnel_read = to_tunnel.clone();
|
||||
|
||||
// Local TCP read -> to tunnel
|
||||
std::thread::Builder::new()
|
||||
.name(format!("relay-stream-{stream_id}-read"))
|
||||
.spawn(move || {
|
||||
let mut tcp_read = tcp_read.as_ref();
|
||||
let mut buf = [0u8; 16384];
|
||||
loop {
|
||||
match tcp_read.read(&mut buf) {
|
||||
@@ -498,11 +504,12 @@ fn spawn_local_tcp_bridge(
|
||||
std::thread::Builder::new()
|
||||
.name(format!("relay-stream-{stream_id}-write"))
|
||||
.spawn(move || {
|
||||
let mut tcp_write = tcp.as_ref();
|
||||
while let Ok(msg) = from_tunnel.recv() {
|
||||
match msg {
|
||||
TunnelMsg::Data { chunk, .. } => {
|
||||
if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) {
|
||||
if tcp.write_all(&data).is_err() {
|
||||
if tcp_write.write_all(&data).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -608,22 +615,71 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
|
||||
fn local_tunnel_exchanges_data_in_both_directions_before_reset() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let tcp = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
|
||||
let shutdown = tcp.clone();
|
||||
let (mut peer, _) = listener.accept().unwrap();
|
||||
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let (tx, rx) = channel();
|
||||
let (out, _) = channel();
|
||||
spawn_local_tcp_bridge(7, tcp, rx, out);
|
||||
drop(StreamWorker {
|
||||
let (out, replies) = channel();
|
||||
spawn_local_tcp_bridge(8, tcp, rx, out);
|
||||
let worker = StreamWorker {
|
||||
tx,
|
||||
reset_on_drop: true,
|
||||
});
|
||||
match peer.read(&mut [0u8; 1]) {
|
||||
Ok(0) => {},
|
||||
Err(error) if matches!(error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => {},
|
||||
other => panic!("The abandoned relay stream must close, got {other:?}"),
|
||||
shutdown,
|
||||
};
|
||||
worker
|
||||
.tx
|
||||
.send(TunnelMsg::Data {
|
||||
stream_id: 8,
|
||||
chunk: base64::engine::general_purpose::STANDARD.encode(b"request"),
|
||||
})
|
||||
.unwrap();
|
||||
let mut request = [0; 7];
|
||||
peer.read_exact(&mut request).unwrap();
|
||||
assert_eq!(&request, b"request");
|
||||
peer.write_all(b"response").unwrap();
|
||||
let mut response = Vec::new();
|
||||
while response.len() < 8 {
|
||||
match replies.recv_timeout(Duration::from_secs(3)).unwrap() {
|
||||
TunnelMsg::Data { chunk, .. } => response.extend(
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(chunk)
|
||||
.unwrap(),
|
||||
),
|
||||
other => panic!("Expected the local reply, got {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(response, b"response");
|
||||
drop(worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
|
||||
for _ in 0..32 {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
|
||||
let shutdown = tcp.clone();
|
||||
let (mut peer, _) = listener.accept().unwrap();
|
||||
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let (tx, rx) = channel();
|
||||
let (out, _) = channel();
|
||||
spawn_local_tcp_bridge(7, tcp, rx, out);
|
||||
drop(StreamWorker {
|
||||
tx,
|
||||
reset_on_drop: true,
|
||||
shutdown,
|
||||
});
|
||||
match peer.read(&mut [0u8; 1]) {
|
||||
Ok(0) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
|
||||
) => {}
|
||||
other => panic!("The abandoned relay stream must close, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,17 +24,25 @@ pub struct CrashItem {
|
||||
|
||||
/// Lists recent crash reports from `Core/Crashes`, sorted newest first.
|
||||
pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
|
||||
let dir = root.join("Core/Crashes");
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(crate::multiworld::Tree::ALL.map(|tree| crate::multiworld::tree_root(root, tree)));
|
||||
let mut files: Vec<(PathBuf, SystemTime)> = Vec::new();
|
||||
if let Ok(entries) = fs::read_dir(&dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
|
||||
let mtime = entry
|
||||
.metadata()
|
||||
.and_then(|m| m.modified())
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
files.push((path, mtime));
|
||||
for world_root in roots {
|
||||
let entries = match fs::read_dir(world_root.join("Core/Crashes")) {
|
||||
Ok(entries) => Some(entries),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if let Some(entries) = entries {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
|
||||
let mtime = entry
|
||||
.metadata()
|
||||
.and_then(|m| m.modified())
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
files.push((path, mtime));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,8 +51,12 @@ pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
|
||||
|
||||
let mut items = Vec::new();
|
||||
for (path, mtime) in files {
|
||||
if let Ok(content) = fs::read_to_string(&path) {
|
||||
let item = parse_crash_content(&path, mtime, &content);
|
||||
if let Ok(bytes) = fs::read(&path) {
|
||||
let content = String::from_utf8_lossy(&bytes);
|
||||
let mut item = parse_crash_content(&path, mtime, &content);
|
||||
if let Ok(relative) = path.strip_prefix(root) {
|
||||
item.id = relative.to_string_lossy().replace('\\', "/");
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
}
|
||||
@@ -237,6 +249,49 @@ fn explain(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovers_native_ansi_reports_and_ignores_dump_files() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
assert!(list(root.path(), 10).unwrap().is_empty());
|
||||
fs::create_dir_all(root.path().join("Core/Crashes")).unwrap();
|
||||
fs::write(
|
||||
root.path().join("Core/Crashes/report.txt"),
|
||||
b"Exception code: C0000005 \xff\r\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.path().join("Core/Crashes/report.dmp"), b"binary").unwrap();
|
||||
let reports = list(root.path(), 10).unwrap();
|
||||
assert_eq!(reports.len(), 1);
|
||||
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_reports_from_all_worlds_without_filename_collisions() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
for relative in [
|
||||
"Core/Crashes",
|
||||
".realms/secondary/Core/Crashes",
|
||||
".realms/reborn/Core/Crashes",
|
||||
] {
|
||||
fs::create_dir_all(root.path().join(relative)).unwrap();
|
||||
fs::write(
|
||||
root.path().join(relative).join("same.txt"),
|
||||
b"Exception code: C0000005",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let reports = list(root.path(), 10).unwrap();
|
||||
assert_eq!(reports.len(), 3);
|
||||
assert_eq!(
|
||||
reports
|
||||
.iter()
|
||||
.map(|r| &r.id)
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_assertion_report() {
|
||||
let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static)
|
||||
|
||||
+1034
-167
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,116 @@
|
||||
{
|
||||
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
|
||||
"Data/Retail/Assets/EquipmentFitting/1068-1.bin": "332d2c38b037a118f262bbb3096a01ebfb33c5347e96bbfb64157437b300281b",
|
||||
"Data/Retail/Assets/EquipmentFitting/60-0.bin": "ffbf6efc9ea09b0c442f048c5bc7b4c5975258045cfddedd9a77a93363312b5e",
|
||||
"Data/Retail/Assets/EquipmentFitting/60-1.bin": "36ceed2a55756f3322e018938809acea5124351161405058ef27d100173778da",
|
||||
"Data/Retail/Assets/EquipmentFitting/61-0.bin": "3b302a4055d1e795c451b02e38dfe8007527ee1bc5f926ebcd6ef17f433cd232",
|
||||
"Data/Retail/Assets/EquipmentFitting/61-1.bin": "c42df399ed99be3c7ce1b5fdb95a873711011713a4cd867bc226a14b1ce0e8ca",
|
||||
"Data/Retail/Assets/EquipmentFitting/65-0.bin": "8ce3f884ae197d14dff0f955c2cf05abb716742c8aff79f7af1cec5cf7225f04",
|
||||
"Data/Retail/Assets/EquipmentFitting/68-0.bin": "f1d878f0f943cbdb8025af8daac4a38c1d1e159bd961d9d76f225931c11648ac",
|
||||
"Data/Retail/Assets/EquipmentFitting/68-1.bin": "2ccbae634384200340c0cc3dca36a7a014a8ddad110598e4470ff1b266576465",
|
||||
"Data/Retail/Assets/EquipmentFitting/73-0.bin": "5530882678f677ad47987ce906e851338a35f7d9737e3f9d829938027b8af67f",
|
||||
"Data/Retail/Assets/EquipmentFitting/74-0.bin": "53a7be86b3bfdd6995406c706df3ca091484206d8141cebb39113c714500384a",
|
||||
"Data/Retail/Assets/EquipmentFitting/74-1.bin": "e688c55a355231978d42480a003c26d379460f5931c2469c119ecb073ea153e1",
|
||||
"Data/Retail/Assets/EquipmentFitting/75-0.bin": "289abc71c6df0e031a64d62a40e658eaefd37e45373a062ca52f08fbe803500c",
|
||||
"Data/Retail/Assets/EquipmentFitting/76-0.bin": "63a493e70b91f59ff49f1942d959df986062bd267fe2ba589f344963df771021",
|
||||
"Data/Retail/Assets/EquipmentFitting/77-0.bin": "b1366ce0dc4f31cb8c8c9705be2da565df4b905224af04b6b88f8c8e9c87e3c9",
|
||||
"Data/Retail/Assets/EquipmentFitting/78-0.bin": "7b0031fb12ab19020005bdccacca2dd3991349c36949a58b035992585b4134db",
|
||||
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
|
||||
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
|
||||
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
|
||||
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
|
||||
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
|
||||
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
|
||||
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
|
||||
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
|
||||
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
|
||||
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
|
||||
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
|
||||
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
|
||||
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
|
||||
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
|
||||
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
|
||||
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
|
||||
"Data/patch-ZK.MPQ": "444d0ecb72c1e990509d53e3cfa5b7634c816733533e8a97e5d7f5653ee32cce",
|
||||
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
|
||||
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
|
||||
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
|
||||
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
|
||||
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
|
||||
"Data/patch-ZZT.MPQ": "e60dab63fe5650fdf5f0846ea6d4136219293bcfdad46d9b796697faeff9ab4c",
|
||||
"Data/patch-ZZU.MPQ": "0311de8f034eae7dec1bd2c92b1fe6c741cbaf53da62c7609cd12b6c37908e47",
|
||||
"Data/patch-ZZV.MPQ": "3b04008905e7185d165827d68f7ca228dda8272816364f7d71874ecc83b64f0e",
|
||||
"Data/patch-ZZW.MPQ": "3bbbc72901fd2d662113036485c380701e693f5a39ba9479af306bf2fa2030bd",
|
||||
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
|
||||
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
|
||||
"Data/patch-ZZZA.MPQ": "57ccbdc0a66000767554ffd194088df6d602ddd8341a141bca8201e7d5435889",
|
||||
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
|
||||
"Data/patch-ZZZD.MPQ": "ca893cf8129f6fd442a63f0697a8ddea88546e3ce71bde713be2cc832b892bc9",
|
||||
"Data/patch-ZZZE.MPQ": "2e245ee0fe3b913087eed399062fda5843d98b04afac38024f7c64ac3bf43e18",
|
||||
"Data/patch-ZZZF.MPQ": "40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3",
|
||||
"Data/patch-ZZZZ.MPQ": "860c990db3b4185fdc36e1a001d3ca3507a68253a4506793a115f86eb0892a15",
|
||||
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
|
||||
"EsteriaAppearance.dll": "88e268d3be9eca3b0644f543d823f4bdcc04a9700a6e8ed73fd2a1260ad191af",
|
||||
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
|
||||
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
|
||||
"EsteriaBanshee.bin": "d3fe66caa6a0ecba96bddb07ac1cbdb915694e87fc1608da0fdabecdf9ffea4d",
|
||||
"EsteriaBansheeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaCentaur.bin": "d63f0b7d21cee67d234d134e832fe6d55c398f2b63f9f6c191dcfa9671637185",
|
||||
"EsteriaCentaurTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
|
||||
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
|
||||
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
|
||||
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
|
||||
"EsteriaEthereal.bin": "ada3b7588511a847dd5154d91e3041e9f7f193998b06bfede5e0afc32570b48c",
|
||||
"EsteriaEtherealTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaFaceless.bin": "1c5a1d7a6b1db6984a8e41bc4804e9f7c50d65dcdbb8c0a9d1a9e8af8c91bd8f",
|
||||
"EsteriaFacelessTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
|
||||
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
|
||||
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
|
||||
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
|
||||
"EsteriaHozen.bin": "739bc3775388976f5c09bcbf3a98b62d804dff78d545e25a41d07dd99b5fddc5",
|
||||
"EsteriaHozenTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaKvItems.bin": "fc5f9d86114234b38dbb0e14a6a5ec16249eaa92a73411a7fc371a950549dcce",
|
||||
"EsteriaKvSkins.bin": "60b2b899f5f83137368514928f92f3b04c0fae058f534c487ddbe913ee4bec18",
|
||||
"EsteriaKyrian.bin": "9329147f08805ff4003f9e062fea7c6ea8fdd8c4d6a40de63a6d228ebe1b7c9a",
|
||||
"EsteriaKyrianTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaMantid.bin": "71536dee6c2abd0b0e13f33bc73cad7e6fb1b0fc1f6912a95c55d57bc7ee1787",
|
||||
"EsteriaMantidTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
|
||||
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
|
||||
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
|
||||
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
|
||||
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
|
||||
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
|
||||
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
|
||||
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
|
||||
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaThinHuman.bin": "bc12e5ca2c087ca0a8642ff6cd8e78fe2e1f85928518b12c19b4245a8320585d",
|
||||
"EsteriaThinHumanTextures.bin": "27488a7494fa9733b53118d1d0f4acef50a9e19004f81f9c8a614b10f4c3fd5e",
|
||||
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
|
||||
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
|
||||
"EsteriaVenthyr.bin": "5bcf7804363e59b3c922830d06de17bbd348b9967307f39b7d72bc09f58814eb",
|
||||
"EsteriaVenthyrTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaVorkai.bin": "d6d2088c7e867b5db437e9afc2d323c22d830c6f84a3598415eedcaa27e2461f",
|
||||
"EsteriaVorkaiTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
|
||||
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
|
||||
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
|
||||
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
|
||||
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
|
||||
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
|
||||
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.lua": "062de55c91228971553f482fd2c8753f4752993b4e8e49d4ded04fa18b98bde7",
|
||||
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.toc": "890bb9d1087e236f4823603f5df3ab0e316dbb65c28feebbda08fb0ab53a408f",
|
||||
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
|
||||
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
|
||||
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
|
||||
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.toc": "16298c04af68e68d6445e7a11f42aee525dd4145f85d2771ff434fb7c6e95a85",
|
||||
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
|
||||
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
|
||||
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
|
||||
}
|
||||
@@ -96,6 +96,9 @@ pub fn run(root: &Path, meta: &InstallMeta) -> Report {
|
||||
if let Some(second) = &o.secondary_world {
|
||||
services.push(("Second world", second));
|
||||
}
|
||||
if let Some(reborn) = &o.reborn_world {
|
||||
services.push(("Warcraft Reborn world", reborn));
|
||||
}
|
||||
for (title, s) in services {
|
||||
let (lvl, text) = match (s.state, &s.conflict) {
|
||||
(ServiceState::Running, _) => (Level::Ok, "Running".to_string()),
|
||||
@@ -639,6 +642,7 @@ fn processes_report(root: &Path, ports: &layout::Ports) -> String {
|
||||
Some(&o.auth),
|
||||
Some(&o.world),
|
||||
o.secondary_world.as_ref(),
|
||||
o.reborn_world.as_ref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -714,6 +718,24 @@ pub fn export_package(
|
||||
"maintenance.json",
|
||||
serde_json::to_string_pretty(&maintenance)?.as_bytes(),
|
||||
)?;
|
||||
for (realm, prefix) in [("primary", ""), ("secondary", ".realms/secondary/"), ("reborn", ".realms/reborn/")] {
|
||||
let state = root.join(format!("{prefix}.state"));
|
||||
if let Ok(owner) = fs::read_to_string(state.join("control-owner.json")) {
|
||||
add(&format!("launcher/{realm}/control-owner.json"), redact_json(&owner).as_bytes())?;
|
||||
}
|
||||
for (path, _, _) in newest_files(&state.join("diagnostics"), "jsonl", 20)
|
||||
.into_iter()
|
||||
.filter(|(path, _, _)| path.file_name().is_some_and(|name| name.to_string_lossy().starts_with("manage-")))
|
||||
.take(5)
|
||||
{
|
||||
let bytes = tail(&path, 512 * 1024);
|
||||
let entries: Vec<serde_json::Value> = String::from_utf8_lossy(&bytes).lines().map(|line| {
|
||||
serde_json::from_str(&redact_json(line)).unwrap_or_else(|_| serde_json::Value::String(redact(line)))
|
||||
}).collect();
|
||||
add(&format!("launcher/{realm}/{}.json", path.file_stem().unwrap_or_default().to_string_lossy()),
|
||||
serde_json::to_string_pretty(&entries)?.as_bytes())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Logs. The newest update logs of the repack's own updater are added under their own names.
|
||||
let mut logs: Vec<(String, PathBuf)> = vec![
|
||||
@@ -1253,6 +1275,12 @@ real error
|
||||
fs::create_dir_all(meta_dir.join("diagnostics")).unwrap();
|
||||
fs::write(meta_dir.join("diagnostics/schema-validation-CoA-test.json"), r#"{"problems":[{"table":"creature_display_preset","column":"display_id","detail":"default mismatch"}],"password":"schema-secret"}"#).unwrap();
|
||||
fs::write(meta_dir.join("diagnostics/database-recovery-test.json"), r#"{"objects":[{"database":"acore_characters","kind":"TRIGGER","name":"user_character_trigger"}],"password":"recovery-secret"}"#).unwrap();
|
||||
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
|
||||
let state = root.join(format!("{prefix}.state"));
|
||||
fs::create_dir_all(state.join("diagnostics")).unwrap();
|
||||
fs::write(state.join("control-owner.json"), r#"{"pid":42,"action":"start-all","password":"launcher-owner-secret"}"#).unwrap();
|
||||
fs::write(state.join("diagnostics/manage-test.jsonl"), "{\"event\":\"launcher-stage-test\",\"password\":\"launcher-stage-secret\"}\n{\"event\":\"wait_ready.error\",\"port\":3307}\n").unwrap();
|
||||
}
|
||||
let meta = InstallMeta::new(InstallKind::Imported, &root);
|
||||
let report = run(&root, &meta);
|
||||
let zip_path = d.path().join("diag.zip");
|
||||
@@ -1285,6 +1313,9 @@ real error
|
||||
assert!(all.contains("checking updates") && all.contains("1234"));
|
||||
assert!(all.contains("lockFilePresent") && all.contains("does not establish"));
|
||||
assert!(!all.contains("owner-secret"));
|
||||
assert!(all.contains("launcher-stage-test"));
|
||||
assert!(all.contains("wait_ready.error"));
|
||||
assert!(!all.contains("launcher-stage-secret"));
|
||||
assert_eq!(fs::read(meta_dir.join("update.lock")).unwrap(), b"");
|
||||
assert!(
|
||||
!all.contains("hunter2")
|
||||
|
||||
@@ -758,6 +758,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
auth: unknown("auth", ports.auth),
|
||||
world: unknown("world", ports.world),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
};
|
||||
};
|
||||
let n = cfg.names();
|
||||
@@ -767,6 +768,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
auth: unknown("auth", ports.auth),
|
||||
world: unknown("world", ports.world),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
};
|
||||
};
|
||||
let ip = connect_ip(&cfg);
|
||||
@@ -795,6 +797,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
listening(state.get(&n.world), ports.world),
|
||||
),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+128
-313
@@ -1,11 +1,10 @@
|
||||
//! Start/stop of a repack-shaped installation by delegating to the repack's own supervisor
|
||||
//! (`Runtime\python\python.exe Scripts\manage.py <verb>`), which already implements config rendering, the
|
||||
//! bug-report relay, RA graceful shutdown and readiness. Observation stays native (see `process`).
|
||||
//! Start/stop of a repack-shaped installation through the repack launcher in this crate
|
||||
//! ([`crate::launcher`]): config rendering, the services, the world supervisor, graceful shutdown and readiness.
|
||||
//! 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, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -22,43 +21,15 @@ pub enum Verb {
|
||||
}
|
||||
|
||||
impl Verb {
|
||||
fn arg(self) -> &'static str {
|
||||
fn action(self) -> crate::launcher::ops::Action {
|
||||
use crate::launcher::ops::Action;
|
||||
match self {
|
||||
Verb::StartAll => "start-all",
|
||||
Verb::StartMysql => "start-mysql",
|
||||
Verb::StartWorld => "start-world",
|
||||
Verb::StopAll => "stop-all",
|
||||
Verb::StartAll => Action::StartAll,
|
||||
Verb::StartMysql => Action::StartMysql,
|
||||
Verb::StartWorld => Action::StartWorld,
|
||||
Verb::StopAll => Action::StopAll,
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout(self, root: &Path) -> Duration {
|
||||
match self {
|
||||
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
|
||||
Verb::StartAll | Verb::StartWorld => Duration::from_secs(420),
|
||||
Verb::StartMysql => Duration::from_secs(120),
|
||||
Verb::StopAll => Duration::from_secs(240),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn squid_enabled(root: &Path) -> bool {
|
||||
let active = root.join("Core/configs/modules/playerbots.conf");
|
||||
let path = if active.exists() {
|
||||
active
|
||||
} else {
|
||||
root.join("Core/configs/modules/playerbots.conf.dist")
|
||||
};
|
||||
std::fs::read(path)
|
||||
.ok()
|
||||
.and_then(|bytes| crate::config::parser::ConfFile::parse_bytes(&bytes).ok())
|
||||
.is_some_and(|config| {
|
||||
config.get("AiPlayerbot.Enabled").is_none_or(|value| {
|
||||
!matches!(
|
||||
value.trim().trim_matches('"').to_ascii_lowercase().as_str(),
|
||||
"0" | "false" | "no" | "off"
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -71,41 +42,14 @@ pub struct DriverOutcome {
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// Map the launcher's own messages onto stable error codes. Unknown text stays `Unknown` (details remain visible).
|
||||
pub fn translate(output: &str) -> ErrorCode {
|
||||
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() {
|
||||
fn has_launcher_settings(root: &Path) -> Result<()> {
|
||||
if !root.join("Settings/repack.json").is_file() {
|
||||
return Err(Error::Invalid(
|
||||
"This server has no CoA Repack launcher; start/stop is not available for it yet."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok((python, script))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
||||
@@ -122,7 +66,69 @@ pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartAll, true)
|
||||
}
|
||||
|
||||
pub fn force_stop(root: &Path) -> Result<DriverOutcome> {
|
||||
if crate::docker::is_docker(root) {
|
||||
return Err(Error::Invalid(
|
||||
"Forced shutdown is only available for Windows repacks.".into(),
|
||||
));
|
||||
}
|
||||
for tree in crate::multiworld::Tree::ALL {
|
||||
let path = crate::multiworld::tree_root(root, tree);
|
||||
if crate::multiworld::tree_running(root, tree)
|
||||
|| !crate::process::find_by_exe(&path.join("Core/worldserver.exe")).is_empty()
|
||||
{
|
||||
let child = fsx::ensure_within(root, &path)?;
|
||||
let out = run_inner_mode(&child, Verb::StopAll, false, true)?;
|
||||
if !out.ok || crate::multiworld::tree_running(root, tree) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"An extra world could not stop; the shared database was left running. {}",
|
||||
out.output
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
run_inner_mode(root, Verb::StopAll, false, true)
|
||||
}
|
||||
|
||||
fn recover_world_for_forced_stop(root: &Path) -> Result<()> {
|
||||
let worlds = crate::process::find_by_exe(&root.join("Core/worldserver.exe"));
|
||||
if worlds.len() > 1 {
|
||||
return Err(Error::Invalid(
|
||||
"More than one world process belongs to this folder; its database was left running."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if let Some(world) = worlds.first() {
|
||||
if !crate::process::is_alive(world) {
|
||||
return Err(Error::Invalid(
|
||||
"The world process identity changed; retry the stop.".into(),
|
||||
));
|
||||
}
|
||||
if crate::process::read_state_record(root, "world")
|
||||
.is_none_or(|saved| !saved.same_as(world))
|
||||
{
|
||||
let record = root.join(".state/world.json");
|
||||
let previous = root.join(".state/world-before-forced-stop-recovery.json");
|
||||
if record.is_file() && !previous.exists() {
|
||||
fsx::atomic_write(&previous, &std::fs::read(&record)?)?;
|
||||
}
|
||||
fsx::atomic_write_json(&record, world)?;
|
||||
tracing::warn!(pid = world.pid, root = %root.display(), "Recovered owned world identity before an explicitly requested forced stop");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
|
||||
run_inner_mode(root, verb, validating_update, false)
|
||||
}
|
||||
|
||||
fn run_inner_mode(
|
||||
root: &Path,
|
||||
verb: Verb,
|
||||
validating_update: bool,
|
||||
force: bool,
|
||||
) -> Result<DriverOutcome> {
|
||||
let root = fsx::canonicalize_lenient(root)?;
|
||||
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
Some(crate::update::operation_lock_for(
|
||||
@@ -138,12 +144,16 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
}
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::modules::ensure_bot_exclusivity(&root)?;
|
||||
// A server update that only added races keeps the owner's race restriction (and custom races on).
|
||||
if let Err(error) = crate::race_availability::rebind_unchanged(&root) {
|
||||
tracing::warn!(%error, "the race restriction could not be checked against the race catalog");
|
||||
}
|
||||
}
|
||||
if crate::docker::is_docker(&root) {
|
||||
prepare_headless_world(&root, verb)?;
|
||||
return crate::docker::run(&root, verb);
|
||||
}
|
||||
if verb == Verb::StopAll {
|
||||
if verb == Verb::StopAll && !force {
|
||||
crate::multiworld::stop(&root)?;
|
||||
}
|
||||
if verb == Verb::StartAll {
|
||||
@@ -162,99 +172,56 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::modules::ensure_bot_exclusivity(&root)?;
|
||||
}
|
||||
let (python, script) = launcher(&root)?;
|
||||
has_launcher_settings(&root)?;
|
||||
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) {
|
||||
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
|
||||
}
|
||||
let mut cmd = Command::new(&python);
|
||||
cmd.arg("-B")
|
||||
.arg("-c")
|
||||
.arg(LAUNCH_SCRIPT)
|
||||
.arg(&script)
|
||||
.arg(verb.arg())
|
||||
.current_dir(&root)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
if force {
|
||||
recover_world_for_forced_stop(&root)?;
|
||||
}
|
||||
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();
|
||||
let (ok, exit_code) = match status {
|
||||
Some(st) => (st.success(), st.code()),
|
||||
None => (false, None),
|
||||
};
|
||||
let code = if ok {
|
||||
None
|
||||
let action = if force {
|
||||
crate::launcher::ops::Action::ForceStopAll
|
||||
} else {
|
||||
// Log evidence beats the launcher's generic "stopped during startup" message.
|
||||
let base = if status.is_none() {
|
||||
ErrorCode::StartupFailed
|
||||
} else {
|
||||
translate(&output)
|
||||
};
|
||||
match base {
|
||||
ErrorCode::StartupFailed | ErrorCode::Unknown => {
|
||||
Some(crate::health::diagnose_installation(&root).unwrap_or(base))
|
||||
verb.action()
|
||||
};
|
||||
tracing::info!(?verb, root = %root.display(), "driver: starting launcher action");
|
||||
let lines = Mutex::new(Vec::<String>::new());
|
||||
let progress = |line: &str| {
|
||||
tracing::info!(?verb, "launcher: {line}");
|
||||
lines.lock().unwrap_or_else(|e| e.into_inner()).push(line.to_string());
|
||||
};
|
||||
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) {
|
||||
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
|
||||
for service in [&observed.mysql, &observed.auth, &observed.world]
|
||||
.into_iter()
|
||||
.chain(observed.secondary_world.iter())
|
||||
.chain(observed.extra_worlds())
|
||||
{
|
||||
if let Some(conflict) = &service.conflict {
|
||||
output.push_str(&format!(
|
||||
@@ -290,6 +257,9 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
|
||||
if !matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(root.join("Core/Crashes"))?;
|
||||
let probe = tempfile::NamedTempFile::new_in(root.join("Core/Crashes"))?;
|
||||
probe.close()?;
|
||||
for relative in [
|
||||
"Settings/worldserver.conf.template",
|
||||
"Core/configs/worldserver.conf",
|
||||
@@ -314,35 +284,6 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
|
||||
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
|
||||
/// graceful shutdown. Adopt only the exact executable owning its configured port.
|
||||
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
|
||||
@@ -393,60 +334,6 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const LAUNCH_SCRIPT: &str = "import runpy,sys\nfrom pathlib import Path\nscript=sys.argv[1]\nsys.path.insert(0,str(Path(script).resolve().parent))\nsys.argv=sys.argv[1:]\nif sys.argv[1]=='stop-all':\n launcher=runpy.run_path(script,run_name='coa_manager_shutdown')\n config=launcher['settings']()\n with launcher['control_lock']():\n launcher['stop_all'](config)\nelse:\n runpy.run_path(script,run_name='__main__')";
|
||||
|
||||
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 {
|
||||
let code = started
|
||||
.code
|
||||
@@ -548,7 +435,7 @@ mod tests {
|
||||
text.contains("launcher request failed before completion")
|
||||
&& text.contains("in progress")
|
||||
);
|
||||
assert!(!text.contains("starting launcher verb"));
|
||||
assert!(!text.contains("starting launcher action"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -587,6 +474,7 @@ mod tests {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let root = folder.path();
|
||||
prepare_headless_world(root, Verb::StartAll).unwrap();
|
||||
assert!(root.join("Core/Crashes").is_dir());
|
||||
std::fs::create_dir_all(root.join("Core/configs")).unwrap();
|
||||
let path = root.join("Core/configs/worldserver.conf");
|
||||
for original in [
|
||||
@@ -604,74 +492,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_squid_provisioning_has_time_to_finish_without_extending_shutdown() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let modules = folder.path().join("Core/configs/modules");
|
||||
std::fs::create_dir_all(&modules).unwrap();
|
||||
std::fs::write(
|
||||
modules.join("playerbots.conf.dist"),
|
||||
"AiPlayerbot.Enabled = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
Verb::StartAll.timeout(folder.path()),
|
||||
Duration::from_secs(2700)
|
||||
);
|
||||
assert_eq!(
|
||||
Verb::StopAll.timeout(folder.path()),
|
||||
Duration::from_secs(240)
|
||||
);
|
||||
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
||||
assert_eq!(
|
||||
Verb::StartWorld.timeout(folder.path()),
|
||||
Duration::from_secs(420)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn 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);
|
||||
fn launcher_failures_carry_their_error_code() {
|
||||
let e = Error::Service(ErrorCode::PortInUse, "Port 8085 is already used (PID 4).".into());
|
||||
assert_eq!(e.code(), ErrorCode::PortInUse);
|
||||
assert_eq!(e.to_string(), "Port 8085 is already used (PID 4).");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -714,13 +538,4 @@ mod tests {
|
||||
assert!(!reason.contains("private"));
|
||||
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),
|
||||
#[error("{0}")]
|
||||
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}")]
|
||||
PackageNotPublished(String),
|
||||
#[error("download server unreachable: {0}")]
|
||||
@@ -199,6 +202,7 @@ impl Error {
|
||||
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
||||
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
||||
Error::BotModulesConflict => ErrorCode::BotModulesConflict,
|
||||
Error::Service(code, _) => *code,
|
||||
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
||||
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
|
||||
_ => ErrorCode::Unknown,
|
||||
|
||||
@@ -88,23 +88,27 @@ fn run_elevated(commands: &[String]) -> Result<()> {
|
||||
|
||||
/// Make sure both rules exist (adds only the missing ones) and confirm afterwards.
|
||||
pub fn ensure_rules(ports: &Ports) -> Result<Status> {
|
||||
ensure_rules_with_secondary(ports, None)
|
||||
ensure_rules_with_extra(ports, &[])
|
||||
}
|
||||
|
||||
pub fn ensure_rules_with_secondary(ports: &Ports, secondary: Option<u16>) -> Result<Status> {
|
||||
/// As `ensure_rules`, plus one rule for the world port of each extra realm that runs next to the main one.
|
||||
pub fn ensure_rules_with_extra(ports: &Ports, extra: &[u16]) -> Result<Status> {
|
||||
let have = status();
|
||||
let mut cmds = plan(ports, &have);
|
||||
let second_name = secondary.map(|port| format!("CoA Server Manager - Second World {port}"));
|
||||
if let (Some(port), Some(name)) = (secondary, &second_name) {
|
||||
let extra_names: Vec<String> = extra
|
||||
.iter()
|
||||
.map(|port| format!("CoA Server Manager - Second World {port}"))
|
||||
.collect();
|
||||
for (port, name) in extra.iter().zip(&extra_names) {
|
||||
if !rule_exists(name) {
|
||||
cmds.push(add_cmd(name, port));
|
||||
cmds.push(add_cmd(name, *port));
|
||||
}
|
||||
}
|
||||
if !cmds.is_empty() {
|
||||
run_elevated(&cmds)?;
|
||||
}
|
||||
let now = status();
|
||||
if now.auth && now.world && second_name.as_ref().is_none_or(|name| rule_exists(name)) {
|
||||
if now.auth && now.world && extra_names.iter().all(|name| rule_exists(name)) {
|
||||
Ok(now)
|
||||
} else {
|
||||
Err(Error::Invalid(
|
||||
|
||||
@@ -163,20 +163,64 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
|
||||
|
||||
/// Make the realm list advertise `host` to remote clients (the launcher resets it to 127.0.0.1 at every start, so this
|
||||
/// runs after each start).
|
||||
pub fn apply_realm_address(root: &Path, host: &str) -> Result<()> {
|
||||
fn realm_address_sql(
|
||||
host: &str,
|
||||
local: Option<(std::net::Ipv4Addr, std::net::Ipv4Addr)>,
|
||||
where_realms: &str,
|
||||
) -> Result<String> {
|
||||
if !host_ok(host) {
|
||||
return Err(Error::Invalid("That address is not valid.".into()));
|
||||
}
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let realm = crate::realms::state(root)?.active.realm_id();
|
||||
let where_realms = if crate::realms::state(root)?.simultaneous {
|
||||
"id IN (1,2)".into()
|
||||
} else {
|
||||
format!("id={realm}")
|
||||
let local = local
|
||||
.map(|(address, mask)| format!(",localAddress='{address}',localSubnetMask='{mask}'"))
|
||||
.unwrap_or_default();
|
||||
Ok(format!(
|
||||
"UPDATE acore_auth.realmlist SET address='{host}'{local} WHERE {where_realms};"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn apply_realm_address(root: &Path, settings: &Settings) -> Result<()> {
|
||||
let host = settings.host.as_deref().unwrap_or("127.0.0.1");
|
||||
let local = match settings.mode {
|
||||
Mode::Direct | Mode::Lan => {
|
||||
let address = if settings.mode == Mode::Lan {
|
||||
host.to_owned()
|
||||
} else {
|
||||
crate::net::resolve_lan_host(
|
||||
settings.lan_address_override.as_deref(),
|
||||
crate::net::lan_ip(),
|
||||
)?
|
||||
};
|
||||
let address = crate::net::validate_lan_address(&address)?;
|
||||
let mask = if_addrs::get_if_addrs()?
|
||||
.into_iter()
|
||||
.find_map(|interface| match interface.addr {
|
||||
if_addrs::IfAddr::V4(v4) if v4.ip == address => Some(v4.netmask),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::Invalid("The selected local network address is not connected.".into())
|
||||
})?;
|
||||
Some((address, mask))
|
||||
}
|
||||
Mode::Local => Some((
|
||||
std::net::Ipv4Addr::LOCALHOST,
|
||||
std::net::Ipv4Addr::new(255, 0, 0, 0),
|
||||
)),
|
||||
Mode::Private => None,
|
||||
};
|
||||
db.query(&format!(
|
||||
"UPDATE acore_auth.realmlist SET address='{host}' WHERE {where_realms};"
|
||||
))?;
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let state = crate::realms::state(root)?;
|
||||
let mut ids = vec![state.active];
|
||||
ids.extend(state.extra_modes());
|
||||
let where_realms = format!(
|
||||
"id IN ({})",
|
||||
ids.iter()
|
||||
.map(|m| m.realm_id().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
);
|
||||
db.query(&realm_address_sql(host, local, &where_realms)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -194,9 +238,9 @@ pub fn ensure_bind(root: &Path, meta: &Path) -> Result<bool> {
|
||||
/// After every server start: put the chosen address back into the realm list (the launcher resets it to 127.0.0.1).
|
||||
pub fn reapply(root: &Path, meta: &Path) -> Result<()> {
|
||||
let s = load(meta);
|
||||
match (s.mode, s.host) {
|
||||
match (s.mode, &s.host) {
|
||||
(Mode::Local, _) | (_, None) => Ok(()),
|
||||
(_, Some(host)) => apply_realm_address(root, &host),
|
||||
(_, Some(_)) => apply_realm_address(root, &s),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +434,25 @@ CoA.AllowRemoteClients = 0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn realm_addresses_restore_lan_without_replacing_public_host() {
|
||||
let sql = realm_address_sql(
|
||||
"203.0.113.9",
|
||||
Some((
|
||||
"192.168.50.7".parse().unwrap(),
|
||||
"255.255.254.0".parse().unwrap(),
|
||||
)),
|
||||
"id IN (1,2)",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(sql, "UPDATE acore_auth.realmlist SET address='203.0.113.9',localAddress='192.168.50.7',localSubnetMask='255.255.254.0' WHERE id IN (1,2);");
|
||||
assert_eq!(
|
||||
realm_address_sql("100.64.1.2", None, "id=1").unwrap(),
|
||||
"UPDATE acore_auth.realmlist SET address='100.64.1.2' WHERE id=1;"
|
||||
);
|
||||
assert!(realm_address_sql("bad'host", None, "id=1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_settings_load_without_migrating_effective_host_to_override() {
|
||||
let s: Settings = serde_json::from_str(r#"{"mode":"lan","host":"192.168.1.50"}"#).unwrap();
|
||||
|
||||
@@ -239,14 +239,14 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> {
|
||||
}
|
||||
fs::copy(&boot, &target)?; // launcher needs database.json to render its files at first start
|
||||
|
||||
let started = driver::run(root, Verb::StartMysql)?;
|
||||
if !started.ok {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The database could not be started. {}",
|
||||
driver::startup_failure(root, &started)
|
||||
)));
|
||||
}
|
||||
let result = (|| -> Result<()> {
|
||||
let started = driver::run(root, Verb::StartMysql)?;
|
||||
if !started.ok {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The database could not be started. {}",
|
||||
driver::startup_failure(root, &started)
|
||||
)));
|
||||
}
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let (root_pw, app_pw) = (random_hex(48), random_hex(48));
|
||||
let accounts = db.query(
|
||||
@@ -362,6 +362,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
||||
// 3. Extract into our own staging folder.
|
||||
if staging_root.exists() {
|
||||
if staging_root.join(MARKER).is_file() {
|
||||
stop_installation(&staging_root)?;
|
||||
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
|
||||
} else {
|
||||
return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display())));
|
||||
@@ -426,24 +427,60 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
||||
})();
|
||||
|
||||
if result.is_err() {
|
||||
if staging_root.join(MARKER).exists() {
|
||||
// Unfinished work of ours; the destination was never touched.
|
||||
let _ = driver::run(&staging_root, Verb::StopAll);
|
||||
let _ = fs::remove_dir_all(&staging_root);
|
||||
let unfinished = if staging_root.join(MARKER).is_file() {
|
||||
Some(&staging_root)
|
||||
} else if dest.join(MARKER).is_file() {
|
||||
// Failed after the folder was moved into place. The destination was empty or absent before (preflight),
|
||||
// so what carries our marker is only our unfinished install.
|
||||
let _ = driver::run(&dest, Verb::StopAll);
|
||||
let _ = fs::remove_dir_all(&dest);
|
||||
Some(&dest)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(unfinished) = unfinished {
|
||||
if let Err(cleanup) = stop_installation(unfinished) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"{} {cleanup}",
|
||||
result.as_ref().unwrap_err()
|
||||
)));
|
||||
}
|
||||
let _ = fs::remove_dir_all(unfinished);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn stop_installation(root: &Path) -> Result<()> {
|
||||
if !root.join("Scripts/manage.py").is_file() {
|
||||
return Ok(());
|
||||
}
|
||||
let stopped = driver::run(root, Verb::StopAll)?;
|
||||
if !stopped.ok {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The unfinished installation could not be stopped; its files were kept. {}",
|
||||
driver::startup_failure(root, &stopped)
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unstoppable_partial_installation_keeps_its_files_for_recovery() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let root = folder.path();
|
||||
fs::create_dir_all(root.join("Scripts")).unwrap();
|
||||
fs::write(root.join("Scripts/manage.py"), "# incomplete launcher").unwrap();
|
||||
fs::write(root.join(MARKER), "").unwrap();
|
||||
fs::write(root.join("database-preserved"), "unchanged").unwrap();
|
||||
assert!(stop_installation(root).is_err());
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("database-preserved")).unwrap(),
|
||||
"unchanged"
|
||||
);
|
||||
assert!(root.join(MARKER).is_file());
|
||||
}
|
||||
|
||||
fn reg(d: &Path) -> Registry {
|
||||
Registry::at(d.join("reg/installs.json"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
//! 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 schedule;
|
||||
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,103 @@
|
||||
//! 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)?;
|
||||
}
|
||||
let relocated;
|
||||
let cfg = match action {
|
||||
Action::StartAll | Action::StartMysql | Action::StartAuth | Action::StartWorld => {
|
||||
match services::relocate_database_port(root, cfg, offset, progress)? {
|
||||
Some(_) => {
|
||||
let mut moved = Settings::load(root, offset)?;
|
||||
moved.env_remove = cfg.env_remove.clone();
|
||||
relocated = moved;
|
||||
&relocated
|
||||
}
|
||||
None => cfg,
|
||||
}
|
||||
}
|
||||
_ => cfg,
|
||||
};
|
||||
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());
|
||||
}
|
||||
}
|
||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user