mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 19:25:56 +00:00
Compare commits
160
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59132216f7 | ||
|
|
f9839ba369 | ||
|
|
06b606c100 | ||
|
|
2fd42f2acd | ||
|
|
34f6fa1cd1 | ||
|
|
fc8b18ef97 | ||
|
|
05630ec9eb | ||
|
|
d64fdb51be | ||
|
|
260d10b729 | ||
|
|
20657df203 | ||
|
|
f08ae1c76b | ||
|
|
4fc133c35e | ||
|
|
de38e60444 | ||
|
|
3c26004e04 | ||
|
|
d1534ebc92 | ||
|
|
20d4c3351e | ||
|
|
8a313b83b8 | ||
|
|
7eea72c415 | ||
|
|
e8ffa6efe3 | ||
|
|
baeecd2ddf | ||
|
|
d352731280 | ||
|
|
a0545286ee | ||
|
|
6f8ed793a7 | ||
|
|
b3c88ce2a6 | ||
|
|
d71c5635e3 | ||
|
|
755761d0de | ||
|
|
550e475962 | ||
|
|
f126cb4ed0 | ||
|
|
fdbf38ee4e | ||
|
|
6091e545f8 | ||
|
|
2e6fcceb05 | ||
|
|
5ccd8871d1 | ||
|
|
abcc816581 | ||
|
|
1ee17f8415 | ||
|
|
71ffd568bb | ||
|
|
8353b791fb | ||
|
|
b81227b0ea | ||
|
|
a9fb982ab0 | ||
|
|
a822bfc99b | ||
|
|
1211de5a77 | ||
|
|
ee36692db7 | ||
|
|
ee43522019 | ||
|
|
a0d3cc08ce | ||
|
|
89e2abb642 | ||
|
|
b4dc30b84a | ||
|
|
73a6cca753 | ||
|
|
705bee7d56 | ||
|
|
5aa9b32283 | ||
|
|
711f378ae8 | ||
|
|
c29d56e2b3 | ||
|
|
d63e85bb18 | ||
|
|
c513649beb | ||
|
|
d2e6fef188 | ||
|
|
db23c9b098 | ||
|
|
f62729d281 | ||
|
|
e7744dfc7c | ||
|
|
899b7c6617 | ||
|
|
3987f1b2ff | ||
|
|
b647e62ca6 | ||
|
|
d990efcfad | ||
|
|
9f48cfc8d5 | ||
|
|
3866e219ce | ||
|
|
2224afd2ea | ||
|
|
6723a7eda1 | ||
|
|
b65b632c63 | ||
|
|
56aa1834db | ||
|
|
53c5e79d92 | ||
|
|
f97408e8aa | ||
|
|
f81313be5e | ||
|
|
048d746d29 | ||
|
|
4facefc5dc | ||
|
|
229ffe1257 | ||
|
|
1ca4e12870 | ||
|
|
2bec907fa7 | ||
|
|
53789b9bdd | ||
|
|
df4a97bff2 | ||
|
|
9153e3ece5 | ||
|
|
3be5fe9609 | ||
|
|
da94fb49a4 | ||
|
|
76be1d3238 | ||
|
|
46fcc780bd | ||
|
|
c29945095b | ||
|
|
e8ac3151a3 | ||
|
|
3a5558f388 | ||
|
|
0a56bc7cf2 | ||
|
|
c0260247ba | ||
|
|
3597b196e3 | ||
|
|
173248efbe | ||
|
|
5697a1d36e | ||
|
|
03722a1d9d | ||
|
|
fb55eb97a9 | ||
|
|
4ebf86d222 | ||
|
|
c2bf8ecbb6 | ||
|
|
221f4a93d3 | ||
|
|
be644f8c54 | ||
|
|
6334402542 | ||
|
|
508ebb6ad1 | ||
|
|
4b16157d10 | ||
|
|
86482fe278 | ||
|
|
7d062faa1a | ||
|
|
223dc56c7d | ||
|
|
d736bc0c47 | ||
|
|
e5386d6133 | ||
|
|
cba8ea3a87 | ||
|
|
d9f9d0f0c2 | ||
|
|
d0c57f9b75 | ||
|
|
c53fc64d8b | ||
|
|
6bbdef1989 | ||
|
|
4e661e6986 | ||
|
|
3dbfffba76 | ||
|
|
c3664b881d | ||
|
|
3b06b75a66 | ||
|
|
4fbcc4d29b | ||
|
|
3e44ca7455 | ||
|
|
2c37c4e29a | ||
|
|
f8312976a7 | ||
|
|
d5ae38440d | ||
|
|
3367be2e99 | ||
|
|
bd98d3eb73 | ||
|
|
bc62ae206f | ||
|
|
0f0f9e6fe2 | ||
|
|
076fba185c | ||
|
|
23cbb108ad | ||
|
|
e97fe52ab3 | ||
|
|
4e73c28f7b | ||
|
|
28af9e2907 | ||
|
|
68e9d7d0cf | ||
|
|
873db420c0 | ||
|
|
b2572d4f7c | ||
|
|
aff7659625 | ||
|
|
49d1ae75ab | ||
|
|
cf94868fd9 | ||
|
|
90f93074c2 | ||
|
|
1a1976d9ad | ||
|
|
dc3fcab7e1 | ||
|
|
ba5816e3ae | ||
|
|
56faaa3a2a | ||
|
|
35084dbce8 | ||
|
|
7e7216979a | ||
|
|
7c0c4cda1f | ||
|
|
642da8fdc1 | ||
|
|
30d2f56997 | ||
|
|
4d1a6e0b21 | ||
|
|
bda38b9f26 | ||
|
|
c004b90c54 | ||
|
|
d44e00f9ad | ||
|
|
dad10d8a5d | ||
|
|
b33821e7eb | ||
|
|
1288a84da2 | ||
|
|
e7b76137d1 | ||
|
|
7bb0ea9472 | ||
|
|
1dab6154c7 | ||
|
|
06a6302732 | ||
|
|
65631450ff | ||
|
|
a8ab201d7d | ||
|
|
733d73ef76 | ||
|
|
5525325160 | ||
|
|
c5eac64477 | ||
|
|
039c40da06 | ||
|
|
b3bb0fdc19 |
No files matched your search
@@ -26,5 +26,4 @@ jobs:
|
|||||||
- run: node tools/check-i18n.mjs
|
- run: node tools/check-i18n.mjs
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
|
||||||
- run: cargo test --workspace --locked
|
- run: cargo test --workspace --locked
|
||||||
@@ -69,10 +69,11 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
# tauri::generate_context! needs ../dist; without a warm target cache the tests do not compile without it.
|
||||||
|
- run: npm run build
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --workspace --locked -- --test-threads=1
|
run: cargo test --workspace --locked -- --test-threads=1
|
||||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
|
||||||
- name: Build and sign (publish only when requested)
|
- name: Build and sign (publish only when requested)
|
||||||
id: tauri
|
id: tauri
|
||||||
uses: tauri-apps/tauri-action@v0
|
uses: tauri-apps/tauri-action@v0
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
name: sign-local-installer
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [release/20261108-manager]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
build_run_id:
|
||||||
|
description: Successful manager-local run in coa-server-build
|
||||||
|
required: true
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
actions: read
|
||||||
|
jobs:
|
||||||
|
sign:
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
- name: Verify local build provenance
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
BUILD_RUN: ${{ inputs.build_run_id }}
|
||||||
|
run: |
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, os, subprocess
|
||||||
|
run = os.environ['BUILD_RUN']
|
||||||
|
if not run.isdigit():
|
||||||
|
raise RuntimeError('Invalid build run')
|
||||||
|
data = json.loads(subprocess.check_output(['gh', 'api', f'repos/Corfirean/coa-server-build/actions/runs/{run}']))
|
||||||
|
if data['conclusion'] != 'success' or data['path'] != '.github/workflows/manager-local.yml':
|
||||||
|
raise RuntimeError('Not a successful local Manager build')
|
||||||
|
subprocess.run(['gh', 'run', 'download', run, '-R', 'Corfirean/coa-server-build', '-n', 'unsigned-manager-windows', '-D', '_prepared-manager'], check=True)
|
||||||
|
from pathlib import Path
|
||||||
|
import hashlib
|
||||||
|
root = Path('_prepared-manager')
|
||||||
|
meta = json.loads((root / 'prepared-source.json').read_text())
|
||||||
|
version = json.loads(Path('package.json').read_text())['version']
|
||||||
|
name = meta['installer']
|
||||||
|
if Path(name).name != name or meta['source'] != os.environ['GITHUB_SHA'] or meta['version'] != version or str(meta['run']) != run:
|
||||||
|
raise RuntimeError('Installer identity differs')
|
||||||
|
if hashlib.sha256((root / name).read_bytes()).hexdigest() != meta['sha256']:
|
||||||
|
raise RuntimeError('Installer hash differs')
|
||||||
|
PY
|
||||||
|
- run: npm ci
|
||||||
|
- name: Sign exact locally compiled bytes
|
||||||
|
env:
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
node --input-type=module <<'JS'
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
const root = '_prepared-manager/';
|
||||||
|
const meta = JSON.parse(readFileSync(root + 'prepared-source.json'));
|
||||||
|
execFileSync('node_modules/.bin/tauri', ['signer', 'sign', '--app-version', meta.version, root + meta.installer], {stdio: 'inherit'});
|
||||||
|
if (createHash('sha256').update(readFileSync(root + meta.installer)).digest('hex') !== meta.sha256) throw new Error('Signed bytes changed');
|
||||||
|
const signature = readFileSync(root + meta.installer + '.sig', 'utf8').trim();
|
||||||
|
const url = `https://github.com/Corfirean/coa-server-manager/releases/download/v${meta.version}/${encodeURIComponent(meta.installer)}`;
|
||||||
|
writeFileSync(root + 'latest.json', JSON.stringify({version: meta.version, notes: 'See the release notes.', pub_date: new Date().toISOString(), platforms: {'windows-x86_64': {signature, url}}}, null, 2) + '\n');
|
||||||
|
meta.signingRun = process.env.GITHUB_RUN_ID;
|
||||||
|
writeFileSync(root + 'prepared-source.json', JSON.stringify(meta, null, 2) + '\n');
|
||||||
|
JS
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: prepared-manager-windows
|
||||||
|
path: _prepared-manager/*
|
||||||
|
retention-days: 14
|
||||||
|
if-no-files-found: error
|
||||||
@@ -9,3 +9,5 @@ src-tauri/gen
|
|||||||
services/*/target/
|
services/*/target/
|
||||||
# Disposable database fixtures and private recovery data
|
# Disposable database fixtures and private recovery data
|
||||||
.cache/
|
.cache/
|
||||||
|
|
||||||
|
release-preview/
|
||||||
@@ -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.
|
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.
|
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
|
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)
|
[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).
|
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
|
||||||
|
|||||||
@@ -8,6 +8,90 @@ Published releases and previews. Pre-release entries do not change the stable up
|
|||||||
|
|
||||||
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
||||||
|
|
||||||
|
## 0.9.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
|
## 0.9.1 — 2026-10-28
|
||||||
|
|
||||||
**Portable Characters are experimental and may contain bugs.**
|
**Portable Characters are experimental and may contain bugs.**
|
||||||
|
|||||||
Generated
+63
-20
@@ -586,7 +586,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-core"
|
name = "coa-core"
|
||||||
version = "0.9.2"
|
version = "0.9.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -606,6 +606,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha1",
|
"sha1",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"socket2",
|
||||||
"tar",
|
"tar",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
@@ -618,6 +619,15 @@ dependencies = [
|
|||||||
"zstd",
|
"zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coa-launcher"
|
||||||
|
version = "0.9.11"
|
||||||
|
dependencies = [
|
||||||
|
"coa-core",
|
||||||
|
"serde_json",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-registry-proto"
|
name = "coa-registry-proto"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -634,31 +644,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-release"
|
name = "coa-release"
|
||||||
version = "0.9.2"
|
version = "0.9.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "coa-server-manager"
|
|
||||||
version = "0.9.2"
|
|
||||||
dependencies = [
|
|
||||||
"coa-control-proto",
|
|
||||||
"coa-core",
|
|
||||||
"coa-registry-proto",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"tauri",
|
|
||||||
"tauri-build",
|
|
||||||
"tauri-plugin-dialog",
|
|
||||||
"tauri-plugin-opener",
|
|
||||||
"tauri-plugin-process",
|
|
||||||
"tauri-plugin-updater",
|
|
||||||
"tracing",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "combine"
|
name = "combine"
|
||||||
version = "4.6.8"
|
version = "4.6.8"
|
||||||
@@ -788,6 +780,26 @@ dependencies = [
|
|||||||
"typenum",
|
"typenum",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "csm-modules-preview"
|
||||||
|
version = "0.9.11"
|
||||||
|
dependencies = [
|
||||||
|
"coa-control-proto",
|
||||||
|
"coa-core",
|
||||||
|
"coa-registry-proto",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tauri",
|
||||||
|
"tauri-build",
|
||||||
|
"tauri-plugin-dialog",
|
||||||
|
"tauri-plugin-opener",
|
||||||
|
"tauri-plugin-process",
|
||||||
|
"tauri-plugin-single-instance",
|
||||||
|
"tauri-plugin-updater",
|
||||||
|
"tauri-plugin-window-state",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cssparser"
|
name = "cssparser"
|
||||||
version = "0.37.0"
|
version = "0.37.0"
|
||||||
@@ -4606,6 +4618,22 @@ dependencies = [
|
|||||||
"tauri-plugin",
|
"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]]
|
[[package]]
|
||||||
name = "tauri-plugin-updater"
|
name = "tauri-plugin-updater"
|
||||||
version = "2.13.1"
|
version = "2.13.1"
|
||||||
@@ -4639,6 +4667,21 @@ dependencies = [
|
|||||||
"zip 4.6.1",
|
"zip 4.6.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tauri-plugin-window-state"
|
||||||
|
version = "2.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"log",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tauri",
|
||||||
|
"tauri-plugin",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.12.0"
|
version = "2.12.0"
|
||||||
|
|||||||
+2
-2
@@ -1,10 +1,10 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
|
members = ["crates/coa-core", "crates/coa-launcher", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
|
||||||
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
|
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.9.2"
|
version = "0.9.11"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# Отчёт о реализации платформы модулей CoA и автономной редакции CSM Modules Preview
|
||||||
|
|
||||||
|
**Дата:** 2 ноября 2026 г.
|
||||||
|
**Ветка:** `preview/modules`
|
||||||
|
**Коммит:** `2c37c4e`
|
||||||
|
**Исполняемый файл Preview:** `C:\games\coa-server-manager-preview\target\release\csm-modules-preview.exe` (32.6 МБ, PE x64)
|
||||||
|
**Портативный дистрибутив:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable.zip` (22.7 МБ)
|
||||||
|
**Стабильная версия CSM:** `C:\games\coa-server-manager` (ветка `feat/multiruleset-realms-portable`, чистая, без изменений)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Итоговая матрица соответствия критериям (Acceptance Criteria)
|
||||||
|
|
||||||
|
| Ключ критерия | Статус | Подтверждение и параметры |
|
||||||
|
|---|---|---|
|
||||||
|
| `READY_FOR_USER_MANUAL_TESTING` | **YES** | Полный цикл: выбор реалма → анализ → сборка → проверка → установка → настройки → переключение |
|
||||||
|
| `CSM_MODULES_PREVIEW_BUILT` | **PASS** | Исполняемый файл скомпилирован в режиме release (PE x64, 32,652,288 байт) |
|
||||||
|
| `STABLE_CSM_UNCHANGED` | **YES** | `git status --porcelain` пуст; рабочее дерево стабильной CSM полностью сохранено |
|
||||||
|
| `APP_DATA_ISOLATED` | **PASS** | Изоляция в `%LOCALAPPDATA%\CSMModulesPreview` (`github_cache`, `staging`, настройки) |
|
||||||
|
| `PREVIEW_REALM_READY` | **PASS** | Тестовый реалм `C:\games\coa-work\plugin-spike\server-v03` с ABI `2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883` |
|
||||||
|
| `GITHUB_INSTALL_FLOW_IMPLEMENTED` | **PASS** | Полный реальный конвейер без фиктивных кнопок: инспектирование, DDL/DML проверка, сборка MSVC, установка |
|
||||||
|
| `CONTROLLED_BUILD_ENGINE_READY` | **PASS** | Изолированная среда сборки MSVC x64 + CMake + Ninja, исключены флаги `/Zi`, CP866/CP1251 декодирование |
|
||||||
|
| `ADAPTER_GENERATOR_INTEGRATED` | **PASS** | Автоматическая генерация `IPlugin`-адаптера и `CoaPluginQuery` для мастер-лоадеров AzerothCore |
|
||||||
|
| `DLL_QUALIFICATION_PASS` | **PASS** | Когорта T01–T04 + AH Bot скомпилированы и валидированы PE x64 с манифестами `plugin.json` |
|
||||||
|
| `TRANSACTIONAL_INSTALL_PASS` | **PASS** | Stop-Gate защита, атомарная установка в `.manager/plugin-store`, обновление `.manager/plugins.json` |
|
||||||
|
| `SQL_REVIEW_GATE_PASS` | **PASS** | Анализ схемы БД, модальное окно подтверждения миграций, запрет деструктивного DROP при удалении плагина |
|
||||||
|
| `T01_INSTALL_TEST` (Congrats On Level) | **PASS** | `congrats-on-level.dll` квалифицирована (L0–L4 PASS, L6 PASS) |
|
||||||
|
| `T02_INSTALL_TEST` (NPC Buffer) | **PASS** | `npc-buffer.dll` квалифицирована (L0–L4 PASS, L6 PASS) |
|
||||||
|
| `T03_INSTALL_TEST` (NPC Enchanter) | **PASS** | `npc-enchanter.dll` квалифицирована (L0–L4 PASS, L6 PASS) |
|
||||||
|
| `T04_INSTALL_TEST` (Reward Played Time) | **PASS** | `reward-played-time.dll` квалифицирована (L0–L4 PASS, L6 PASS) |
|
||||||
|
| `AH_BOT_BUILD_PASS` (Auction House Bot) | **PASS** | Сборка и связывание успешны за 11.7с на SDK v0.3.2 (устранены неразрешённые внешние символы) |
|
||||||
|
| `GUILDHOUSE_TIER3_CLASSIFICATION_PASS` | **PASS** | Анализатор автоматически детектирует обращение к ядру жизненного цикла и блокирует сборку DLL |
|
||||||
|
| `DIAGNOSTICS_EXPORT_READY` | **PASS** | Экспорт очищенного диагностического отчёта о среде сборки, ABI и активных плагинах |
|
||||||
|
| `PORTABLE_PACKAGE_CREATED` | **PASS** | Автономный zip-архив `CSM-Modules-Preview-Portable.zip` готов к запуску пользователем |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Разрешение проблемы с Auction House Bot (AH Bot Link Failure)
|
||||||
|
|
||||||
|
### Причина сбоя
|
||||||
|
При попытке сборки `mod-ah-bot` возникали 3 ошибки компоновщика MSVC `LNK2019`:
|
||||||
|
1. `??1Player@@UEAA@XZ` — вызов деструктора `Player::~Player()`. В методе `AuctionHouseBot::Update()` модуль создаёт локальный экземпляр `Player _AHBplayer(&_session)` на стеке. Конструктор `Player::Player` был экспортирован в `coa_plugin_exports.def`, а деструктор отсутствовал в таблице экспорта.
|
||||||
|
2. `?OnAuctionSuccessful@ScriptMgr@@...` — метод обратного вызова при успешном аукционе.
|
||||||
|
3. `?GetAuctionHouseEntryFromHouse@AuctionHouseMgr@@...` — метод поиска записи дома аукциона.
|
||||||
|
|
||||||
|
### Внесённые изменения
|
||||||
|
1. **Экспорт символов в ядре AzerothCore Host:**
|
||||||
|
В файл `C:\games\coa-work\plugin-spike\core\src\server\apps\worldserver\Plugins\coa_plugin_exports.def` добавлены:
|
||||||
|
- `??1Player@@UEAA@XZ`
|
||||||
|
- `?OnAuctionSuccessful@ScriptMgr@@QEAAXPEAVAuctionHouseObject@@PEAUAuctionEntry@@@Z`
|
||||||
|
- `?GetAuctionHouseEntryFromHouse@AuctionHouseMgr@@SAPEBUAuctionHouseEntry@@W4AuctionHouseId@@@Z`
|
||||||
|
2. **Перекомпиляция ядра Host:**
|
||||||
|
Выполнена сборка `worldserver.exe` и `worldserver.lib` с помощью Ninja в `C:\games\coa-work\plugin-spike\build-spike`.
|
||||||
|
3. **Обновление SDK v0.3.2:**
|
||||||
|
Экспортирован SDK в `C:\games\coa-work\plugin-spike\sdk-v03` (ABI fingerprint: `2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883`).
|
||||||
|
4. **Обновление тестового реалма:**
|
||||||
|
Файлы `worldserver.exe` и `worldserver.pdb` скопированы в `C:\games\coa-work\plugin-spike\server-v03`.
|
||||||
|
5. **Верификация сборки:**
|
||||||
|
Тест `test_controlled_build_ah_bot` в `build_engine.rs` выполнен успешно за 11.71 с. AH Bot компилируется и компонуется в валидную DLL без неразрешённых символов.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Классификация и диагностика Guildhouse (Tier 3 Core-Integrated)
|
||||||
|
|
||||||
|
### Анализ 26 ошибок компоновки
|
||||||
|
Модуль `mod-guildhouse` содержит вызовы:
|
||||||
|
- `WorldObject::AddObjectToRemoveList()`
|
||||||
|
- `Unit::GetPhaseByAuras()`
|
||||||
|
- `new GameObject()` / `delete gobject`
|
||||||
|
- `GameObject::SaveToDB()` / `GameObject::DeleteFromDB()` / `GameObject::LoadGameObjectFromDB()`
|
||||||
|
- `new Creature()` / `delete creature`
|
||||||
|
- `Creature::SaveToDB()` / `Creature::DeleteFromDB()` / `Creature::LoadCreatureFromDB()`
|
||||||
|
|
||||||
|
Данные методы представляют собой низкоуровневое управление жизненным циклом сущностей и распределением памяти в куче игрового ядра. Прямое создание и уничтожение сущностей через границу DLL в отдельном модуле без абстрагирующего сервиса (`GameObjectServices`) нарушает инварианты аллокатора памяти ядра и приводит к сбоям сервера.
|
||||||
|
|
||||||
|
### Реализация в Compatibility Analyzer
|
||||||
|
В `crates/coa-core/src/analyzer.rs`:
|
||||||
|
- Добавлено правило `RULE_OBJECT_LIFECYCLE_CORE_DEPENDENCY` (Severity: Critical, Confidence: High).
|
||||||
|
- Анализатор сканирует исходный код на наличие прямого создания сущностей и вызовов `SaveToDB`, `DeleteFromDB`, `AddObjectToRemoveList` без завязки на имя репозитория.
|
||||||
|
- При обнаружении модуль классифицируется как `CorePatchRequired` (`Tier 3: Core-Integrated Compatibility Required`).
|
||||||
|
- Статус сборки автоматически устанавливается в `BLOCKED`, статус рантайма — `BLOCKED`.
|
||||||
|
- В пользовательском интерфейсе кнопка сборки и установки отключается, а пользователю выводится понятное объяснение: *«Модуль обращается к внутренним структурам управления сущностями ядра. Требуется сборка в составе ядра (in-tree build)»*.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Устранение дефектов сборщика и интерфейса
|
||||||
|
|
||||||
|
1. **Разрешение идентификатора модуля вместо Git SHA:**
|
||||||
|
- Intake-кэш клонирует репозитории в `github_cache/github/<owner>/<repo>/<sha>`. Ранее `build_module_from_source` использовал имя конечной папки (SHA).
|
||||||
|
- Реализована функция `resolve_module_identity(source_dir)`, которая анализирует путь к репозиторию и извлекает канонический идентификатор (например, `npc-buffer`), человекочитаемое имя (`NPC Buffer`) и сохраняет Git-коммит в метаданных.
|
||||||
|
- В `preview.rs` добавлена автомиграция ранее установленных плагинов с 40-значными SHA в читаемые имена.
|
||||||
|
2. **Устранение иероглифов (mojibake) в логах MSVC:**
|
||||||
|
- Компилятор MSVC на русскоязычных Windows выводит сообщения в кодировках CP866/CP1251.
|
||||||
|
- В `build_engine.rs` добавлена функция `decode_msvc_output`, выполняющая декодирование с валидацией UTF-8 и откатом на CP866/CP1251.
|
||||||
|
- В скрипт сборщика `run_build.bat` добавлены директивы `set VSLANG=1033` и `chcp 65001`.
|
||||||
|
3. **Устранение предупреждения компилятора D9025 (`/Zi` vs `/Z7`):**
|
||||||
|
- Флаг `/Zi` конфликтовал с изолированным флагом `/Z7`.
|
||||||
|
- В конфигурации CMake `build_engine.rs` флаг `/Zi` автоматически удаляется из `CMAKE_CXX_FLAGS_RELWITHDEBINFO`, обеспечивая чистый вывод сборки.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Обновлённый интерфейс модулей (UI Architecture)
|
||||||
|
|
||||||
|
Интерфейс `ModulesPage.tsx` объединяет проверенный дизайн CSM и модульную платформу Preview:
|
||||||
|
|
||||||
|
1. **Вкладка «Официальные модули» (Official Modules):**
|
||||||
|
- Полная сетка встроенных модулей (CoA Companions, Content Scaling, TBC, WotLK, Auction House Bot, NPC Enchanter, SQUID's Playerbots, Custom Races, TimeIsTime).
|
||||||
|
- Переключатели с защитой взаимного исключения (активация CoA Companions автоматически отключает SQUID's Playerbots и наоборот).
|
||||||
|
- Управление патчем клиента Custom Races (статус MPQ, кнопки «Установить патч», «Восстановить патч», «Удалить патч», шкала прогресса).
|
||||||
|
- Выдвижные панели настроек `ModuleSettings` со строкой поиска, чекбоксом расширенных настроек и специализированным редактором `AuctionTypes`.
|
||||||
|
2. **Вкладка «Каталог модулей» (Verified Catalog):**
|
||||||
|
- Каталог из 10 проверенных модулей с фильтрами («Все», «Проверенные DLL», «Конфликты», «Требуют ядро») и поиском.
|
||||||
|
- Честные бейджи уровней квалификации:
|
||||||
|
- `INSTALL_VERIFIED` (`L0–L4 PASS, L6 PASS`): NPC Buffer, Congrats On Level, NPC Enchanter, Reward Played Time.
|
||||||
|
- `LINK_VERIFIED` (`L0–L3 PASS`): Auction House Bot (SDK v0.3.2).
|
||||||
|
- `BUILT` (`L0–L2 PASS`): Transmogrification.
|
||||||
|
- `POTENTIAL_CONFLICT` (`L0–L2 PASS`): Solocraft (требуется калибровка параметров).
|
||||||
|
- `CONFLICT_DETECTED` (`L0 PASS`): AutoBalance (прямой конфликт полномочий с Content Scaling).
|
||||||
|
- `CORE_INTEGRATED_REQUIRED` (`Tier 3`): Guildhouse (прямое управление жизненным циклом сущностей).
|
||||||
|
- `DEPENDENCY_MISSING` (`Tier 4`): ALE (отсутствует рантайм LuaJIT).
|
||||||
|
- Модальное окно «Подробнее» с полным описанием архитектурных ограничений и кнопкой быстрого перехода к сборке.
|
||||||
|
3. **Вкладка «Установка с GitHub» (Install from GitHub):**
|
||||||
|
- Ввод URL, быстрый выбор популярных модулей, многомерный статус (Сборка, Рантайм, Геймплей, БД, Безопасность), список находок аудита, управляемая сборка MSVC и установка в реалм с подтверждением SQL-миграций.
|
||||||
|
4. **Вкладка «Установленные плагины» (Installed Plugins):**
|
||||||
|
- Список установленных DLL с отображением понятных имён, версии, хэша коммита, переключателем включения/выключения и кнопкой безопасного удаления (без сброса таблиц БД).
|
||||||
|
5. **Вкладка «Сборка & логи MSVC» (Builds & MSVC Logs):**
|
||||||
|
- Результат последней сборки, расшифрованные ошибки MSVC с рекомендациями по устранению и терминал вывода в реальном времени.
|
||||||
|
6. **Вкладка «Среда сборки & SDK» (Toolchain & Environment):**
|
||||||
|
- Статус готовности MSVC x64, CMake, Ninja, SDK v0.3.2, слепок ABI хоста и текущий путь к реалму.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Пути к ключевым файлам и дистрибутивам
|
||||||
|
|
||||||
|
- **Автономный архив Preview:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable.zip`
|
||||||
|
- **Исполняемый файл Preview:** `C:\games\coa-server-manager-preview\dist\CSM-Modules-Preview-Portable\CSM Modules Preview.exe`
|
||||||
|
- **Бинарный файл сборки:** `C:\games\coa-server-manager-preview\target\release\csm-modules-preview.exe`
|
||||||
|
- **Тестовый реалм со сборкой v0.3.2:** `C:\games\coa-work\plugin-spike\server-v03`
|
||||||
|
- **Экспортированный SDK v0.3.2:** `C:\games\coa-work\plugin-spike\sdk-v03`
|
||||||
|
- **Отчёт о квалификации:** `C:\games\coa-work\plugin-spike\report\sdk-v032\csm-modules-preview-qualification.json`
|
||||||
|
- **Стабильная рабочая копия CSM (без изменений):** `C:\games\coa-server-manager`
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
# Отчёт об интеграции публичного каталога AzerothCore в Modules V2
|
||||||
|
|
||||||
|
**Проект:** CoA Server Manager (CSM)
|
||||||
|
**Ветка:** `preview/modules-v2`
|
||||||
|
**Рабочая директория:** `C:\games\coa-server-manager-preview`
|
||||||
|
**Дата реализации:** Ноябрь 2026 г.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Резюме выполненных работ
|
||||||
|
|
||||||
|
В существующую архитектуру системы **Modules V2** успешно интегрирован официальный публичный каталог модулей AzerothCore (`azerothcore.org/data/catalogue.json`).
|
||||||
|
|
||||||
|
Реализация строго следует принципу **непереизобретения колеса**:
|
||||||
|
- Полностью сохранён существующий конвейер Modules V2:
|
||||||
|
- GitHub Intake & Source Cache (`analyzer.rs`)
|
||||||
|
- Compatibility Analyzer (`analyze_github_module_for_realm`)
|
||||||
|
- Controlled DLL Builder на базе MSVC, CMake, Ninja и `IPlugin` (`build_engine.rs`)
|
||||||
|
- Transactional Installer (`preview.rs`)
|
||||||
|
- Plugin Registry & Manifest Storage (`plugins.rs`)
|
||||||
|
- Server Stop-Gate и SQL Review Gate
|
||||||
|
- Главное UX-требование выполнено:
|
||||||
|
- **Группа A (Recommended for CoA)** всегда отображается на самом верху каталога. Все существующие проверенные модули (включая официальные компоненты ядра и динамические DLL) сохранены в полном объёме с их текущими действиями.
|
||||||
|
- **Группа B (AzerothCore Community Modules)** отображается ниже и предоставляет доступ к 500+ модулям сообщества с информацией о звёздах, форках, тегах, статусе совместимости CoA и кнопкой установки, передающей URL репозитория в готовый конвейер `runAnalysis(url)`.
|
||||||
|
- Блокировка несовместимых модулей (например, `azerothcore/mod-ahbot`) защищена на трёх уровнях: в UI, в анализаторе AST/исходного кода и в сборочном движке (невозможно обойти даже прямой вставкой URL в инпут).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Архитектура и источники данных
|
||||||
|
|
||||||
|
### 2.1 Источник каталога
|
||||||
|
В ходе исследования было установлено, что файл `catalogue.json` в репозитории `azerothcore.github.io` является устаревшим статическим срезом (185 модулей). Реальным актуальным источником каталога AzerothCore является:
|
||||||
|
- **URL:** `https://www.azerothcore.org/data/catalogue.json`
|
||||||
|
- **Количество модулей:** 545+ репозиториев
|
||||||
|
- **Периодичность обновления:** каждые 30 минут через GitHub Actions на Cloudflare Pages CDN
|
||||||
|
- **Машиночитаемый формат:** JSON-объект с полями `categories` и `repos` (`id`, `name`, `owner`, `html_url`, `stargazers_count`, `forks_count`, `topics`, `category`, `license`, `pushed_at`).
|
||||||
|
|
||||||
|
### 2.2 Кэширование, ETag и автономный режим
|
||||||
|
Реализован движок в `crates/coa-core/src/catalogue.rs`:
|
||||||
|
1. **HTTP Conditional Requests:** При сетевом запросе отправляется заголовок `If-None-Match: <etag>`. При получении ответа `304 Not Modified` парсинг сетевого тела не производится, обновляется лишь метка времени кэша.
|
||||||
|
2. **TTL (12 часов):** Если локальный файл кэша свежее 12 часов и пользователь не нажал кнопку принудительного обновления, каталог отдаётся из локального дискового кэша мгновенно без блокирующих сетевых задержек.
|
||||||
|
3. **Атомарная запись:** Сохранение на диск осуществляется через `fsx::atomic_write_json` в `%LOCALAPPDATA%/coa-manager/catalogue/catalogue_cache.json`.
|
||||||
|
4. **Offline Fallback:** В случае отсутствия интернета, сбоя DNS или недоступности CDN сервер возвращает последнюю сохранённую копию кэша с флагом `is_offline = true`. В интерфейсе появляется информационная плашка с датой кэша и кнопкой повтора.
|
||||||
|
|
||||||
|
### 2.3 Нормализация и дедупликация
|
||||||
|
Функция `normalize_repo_slug` корректно приводит к единому виду `owner/repo`:
|
||||||
|
- URL с протоколом: `https://github.com/azerothcore/mod-npc-buffer.git` → `azerothcore/mod-npc-buffer`
|
||||||
|
- SSH-ссылки: `git@github.com:azerothcore/mod-npc-buffer.git` → `azerothcore/mod-npc-buffer`
|
||||||
|
- Ссылки на поддиректории: `https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/...`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Кураторский оверлей CoA (CoA Modules Overlay)
|
||||||
|
|
||||||
|
В `crates/coa-core/src/coa-modules-overlay.json` создан структурированный оверлей совместимости с ядром Conquest of Azeroth.
|
||||||
|
|
||||||
|
### 3.1 Статусы совместимости
|
||||||
|
1. `Recommended` — модуль оптимизирован для CoA и проверен на практике.
|
||||||
|
2. `Verified` — динамический плагин DLL компилируется и функционирует штатно.
|
||||||
|
3. `RequiresAdapter` — требует генерации адаптера точки входа `IPlugin`.
|
||||||
|
4. `Unverified` — сторонний модуль сообщества (по умолчанию).
|
||||||
|
5. `Incompatible` — содержит известные конфликты с механизмами CoA.
|
||||||
|
6. `Blocked` — модуль категорически запрещён к установке из-за разрушения специфики CoA (например, конфликтующие боты аукциона или параллельные реализации companion AI).
|
||||||
|
|
||||||
|
### 3.2 Защита на уровне движка
|
||||||
|
В `crates/coa-core/src/analyzer.rs` и `crates/coa-core/src/build_engine.rs` добавлена проверка `catalogue::is_blocked_repo`:
|
||||||
|
- Анализатор немедленно фиксирует критическое замечание (`CRITICAL`) с причиной блокировки и присваивает статус `SourceIncompatible`.
|
||||||
|
- Сборочный движок `build_engine::build_module_from_source` прерывает сборку до вызова MSVC/CMake с понятной ошибкой: `Module '...' is blocked for Conquest of Azeroth: ...`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Tauri IPC и клиентский API
|
||||||
|
|
||||||
|
1. **Команда Tauri (`src-tauri/src/lib.rs`):**
|
||||||
|
```rust
|
||||||
|
#[tauri::command]
|
||||||
|
async fn get_public_module_catalog(
|
||||||
|
force_refresh: Option<bool>,
|
||||||
|
) -> std::result::Result<coa_core::catalogue::PublicCatalogueResponse, UiError> {
|
||||||
|
let cache_dir = data_dir().join("catalogue");
|
||||||
|
let force = force_refresh.unwrap_or(false);
|
||||||
|
blocking(move || {
|
||||||
|
coa_core::catalogue::fetch_or_load_catalogue(&cache_dir, force)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Команда зарегистрирована в `invoke_handler!`.
|
||||||
|
|
||||||
|
2. **Клиентский API (`src/lib/api.ts`):**
|
||||||
|
- Добавлены TypeScript-интерфейсы `PublicCatalogueItem`, `PublicCatalogueResponse`, `CoaCompatibilityStatus`.
|
||||||
|
- Экспортирован типизированный метод:
|
||||||
|
```typescript
|
||||||
|
getPublicModuleCatalog: (forceRefresh = false) =>
|
||||||
|
invoke<PublicCatalogueResponse>("get_public_module_catalog", { forceRefresh }),
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Пользовательский интерфейс (`ModulesPage.tsx`)
|
||||||
|
|
||||||
|
### 5.1 Иерархия отображения
|
||||||
|
1. **Группа A — Рекомендовано для CoA:**
|
||||||
|
- 13 модулей `VERIFIED_CATALOG` отображаются в самом начале.
|
||||||
|
- Имеют золотой бейдж `★ CoA Recommended` / `CoA Verified`.
|
||||||
|
- Сохраняют все быстрые действия: для официальных — включение/выключение в ядре, для динамических DLL — прямая сборка и установка.
|
||||||
|
2. **Группа B — Каталог сообщества AzerothCore:**
|
||||||
|
- Все остальные модули каталога azerothcore.org (за вычетом модулей из группы A во избежание дублирования).
|
||||||
|
- Информативная карточка: название, автор, описание, звёзды GitHub, форки, категория, лицензия SPDX, теги topics.
|
||||||
|
- Бейдж статуса CoA (`CoaStatusBadge`):
|
||||||
|
- `Recommended` (золотой)
|
||||||
|
- `Verified` (зелёный)
|
||||||
|
- `RequiresAdapter` (голубой)
|
||||||
|
- `Community AC` (нейтральный)
|
||||||
|
- `Incompatible` (янтарный с предупреждением)
|
||||||
|
- `Blocked` (красный с причиной блокировки)
|
||||||
|
3. **Действия с модулями сообщества:**
|
||||||
|
- Для уже установленных: индикатор `✓ Установлен` и кнопка `Настроить`.
|
||||||
|
- Для заблокированных: заблокированная кнопка `⛔ Заблокирован` с подсказкой причины.
|
||||||
|
- Для доступных модулей: кнопка `Собрать и установить`, которая устанавливает `githubUrl`, запускает `runAnalysis(url)` и переводит пользователя на контролируемую сборку `startControlledBuild(url)`.
|
||||||
|
- Кнопка `Подробнее`: открывает модальное окно с полным набором метаданных репозитория, лицензией, веткой, историей обновлений и инженерными комментариями.
|
||||||
|
|
||||||
|
### 5.2 Поиск, фильтры и сортировка
|
||||||
|
- **Поиск:** фильтрация по названию, репозиторию, автору, описанию и тегам.
|
||||||
|
- **Фильтры:**
|
||||||
|
- `Все` (сумма групп A и B)
|
||||||
|
- `Рекомендовано CoA`
|
||||||
|
- `Официальные ядра`
|
||||||
|
- `Проверенные DLL`
|
||||||
|
- `Сообщество AC`
|
||||||
|
- `Несовместимые / Блок`
|
||||||
|
- **Сортировка модулей сообщества:**
|
||||||
|
- `★ По звёздам` (по умолчанию)
|
||||||
|
- `🕒 По дате обновления`
|
||||||
|
- `🔤 По имени (A-Z)`
|
||||||
|
- **Пагинация (Load More):** отображение порциями по 24 модуля с кнопкой `Показать ещё (+24)` и счётчиком показанных элементов.
|
||||||
|
- **Счётчик вкладки:** бейдж на вкладке «Каталог модулей» отображает общее число доступных модулей (`publicCatalog.total_count` ~ 545).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Тестирование и верификация
|
||||||
|
|
||||||
|
### 6.1 Модульные тесты бэкенда (`coa-core`)
|
||||||
|
Успешно пройдены все тесты каталога и смежных подсистем:
|
||||||
|
- `catalogue::tests::test_slug_normalization` — проверка нормализации URL, SSH-алиасов и суффиксов `.git`
|
||||||
|
- `catalogue::tests::test_overlay_loading_and_blocked_detection` — корректность загрузки оверлея и выявление блокированных модулей (`azerothcore/mod-ahbot`)
|
||||||
|
- `catalogue::tests::test_official_json_parsing_and_normalization` — парсинг структуры `catalogue.json` и применение оверлея
|
||||||
|
- `catalogue::tests::test_disk_caching_and_offline_fallback` — проверка ETag, TTL и возврата из автономного кэша
|
||||||
|
- `analyzer::tests::*` (17 тестов) — отсутствие регрессий в AST-анализаторе
|
||||||
|
- `build_engine::tests::test_controlled_build_cohort_t01_t04` и `test_controlled_build_ah_bot` — успешная проверка сборочного движка
|
||||||
|
|
||||||
|
### 6.2 Проверка фронтенда
|
||||||
|
- `tsc --project tsconfig.json --noEmit` — **0 ошибок, полная типизация**.
|
||||||
|
- `vite build` — **успешная сборка production-бандла** клиента за 4.12 сек.
|
||||||
|
- `cargo check` — **чистая компиляция Tauri бэкенда** без предупреждений.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Локальные коммиты в ветке `preview/modules-v2`
|
||||||
|
|
||||||
|
Все изменения закоммичены локально в рабочей ветке `preview/modules-v2` четырьмя атомарными коммитами:
|
||||||
|
|
||||||
|
1. `4e661e6` — `feat(core): implement AzerothCore module catalogue engine, overlay and caching`
|
||||||
|
- Создан `crates/coa-core/src/catalogue.rs`
|
||||||
|
- Создан `crates/coa-core/src/coa-modules-overlay.json`
|
||||||
|
- Зарегистрирован модуль в `crates/coa-core/src/lib.rs`
|
||||||
|
- Добавлен план интеграции `MODULE_CATALOG_V2_INTEGRATION_PLAN.md`
|
||||||
|
2. `6bbdef1` — `feat(analyzer): enforce CoA module blocklist in analyzer and build engine`
|
||||||
|
- Добавлена блокировка в `crates/coa-core/src/analyzer.rs`
|
||||||
|
- Добавлена проверка безопасности в `crates/coa-core/src/build_engine.rs`
|
||||||
|
3. `c53fc64` — `feat(ipc): expose public module catalogue Tauri command and API client`
|
||||||
|
- Зарегистрирована Tauri команда `get_public_module_catalog` в `src-tauri/src/lib.rs`
|
||||||
|
- Экспортированы типы и API-метод в `src/lib/api.ts`
|
||||||
|
4. `d0c57f9` — `feat(ui): integrate dual-group public AzerothCore catalogue into ModulesPage`
|
||||||
|
- Реализованы две группы (Группа A: Рекомендовано для CoA, Группа B: Сообщество AzerothCore)
|
||||||
|
- Добавлены бейджи статусов, поиск, фильтры, сортировка, пагинация, модальное окно деталей, плашка офлайн-режима и вызов `runAnalysis`
|
||||||
|
|
||||||
|
**Внимание:** В соответствии с инструкцией слияние в `master`, создание PR и push во внешний репозиторий **не выполнялись**. Все изменения готовы к локальному тестированию и ревью.
|
||||||
@@ -0,0 +1,477 @@
|
|||||||
|
# План интеграции публичного каталога AzerothCore в систему Modules V2 (CSM)
|
||||||
|
|
||||||
|
**Документ:** `MODULE_CATALOG_V2_INTEGRATION_PLAN.md`
|
||||||
|
**Дата аудита:** Ноябрь 2026 г.
|
||||||
|
**Проект:** [CoA Server Manager (CSM)](https://github.com/Corfirean/coa-server-manager)
|
||||||
|
**Исследуемая целевая ветка:** `preview/modules-v2`
|
||||||
|
**Рабочее дерево Preview:** `C:\games\coa-server-manager-preview`
|
||||||
|
**Статус:** Исследование и планирование архитектуры (без модификации рабочих компонентов)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Содержание
|
||||||
|
|
||||||
|
1. [Фактическая архитектура Modules V2](#1-фактическая-архитектура-modules-v2)
|
||||||
|
2. [Карта существующих компонентов с путями и функциями](#2-карта-существующих-компонентов-с-путями-и-функциями)
|
||||||
|
3. [Точки интеграции каталога](#3-точки-интеграции-каталога)
|
||||||
|
4. [Перечень уже реализованных возможностей](#4-перечень-уже-реализованных-возможностей)
|
||||||
|
5. [Перечень отсутствующих компонентов](#5-перечень-отсутствующих-компонентов)
|
||||||
|
6. [Предлагаемые минимальные изменения Backend](#6-предлагаемые-минимальные-изменения-backend)
|
||||||
|
7. [Предлагаемые изменения Frontend](#7-предлагаемые-изменения-frontend)
|
||||||
|
8. [Схема потоков данных](#8-схема-потоков-данных)
|
||||||
|
9. [Модель кэширования и обновления](#9-модель-кэширования-и-обновления)
|
||||||
|
10. [Интеграция с анализатором совместимости](#10-интеграция-с-анализатором-совместимости)
|
||||||
|
11. [План тестирования (Интеграционная матрица)](#11-план-тестирования-интеграционная-матрица)
|
||||||
|
12. [Риски и потенциальные регрессии](#12-риски-и-потенциальные-регрессии)
|
||||||
|
13. [План реализации небольшими независимыми этапами](#13-план-реализации-небольшими-независимыми-этапами)
|
||||||
|
14. [Сводная таблица компонентов](#14-сводная-таблица-компонентов)
|
||||||
|
15. [Анализ различий веток: `master` vs `preview/modules-v2`](#15-анализ-различий-веток-master-vs-previewmodules-v2)
|
||||||
|
16. [Главный вопрос и итоговый вердикт](#16-главный-вопрос-и-итоговый-вердикт)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Фактическая архитектура Modules V2
|
||||||
|
|
||||||
|
В ветке `preview/modules-v2` (развернута в рабочем дереве `C:\games\coa-server-manager-preview`) реализована полноценная платформа динамических модулей и плагинов для Conquest of Azeroth.
|
||||||
|
|
||||||
|
### 1.1. Классификация компонентов (Authoritative Inventory)
|
||||||
|
В отличие от старой архитектуры, где наличие `.conf` в папке считалось признаком установки, в Modules V2 введена строгая модель типов компонентов ([PREVIEW_DISTRIBUTION_ARCHITECTURE.md](file:///C:/games/coa-server-manager-preview/docs/PREVIEW_DISTRIBUTION_ARCHITECTURE.md)):
|
||||||
|
- `DYNAMIC_DLL`: динамически загружаемые C++ библиотеки, компилируемые под CoA Plugin SDK v0.3.2. Хранятся в `.manager/plugin-store/<id>/<version>/` и линкуются в `plugins/`. Поддерживают полный динамический жизненный цикл (`can_remove = true`).
|
||||||
|
- `CORE_EMBEDDED`: легаси C++ модули, монолитно вкомпилированные в `worldserver.exe`. Не могут быть удалены на лету (`can_remove = false`).
|
||||||
|
- `CONTENT_PACK`: пакеты контента (DBC, карты, спавны), неизменяемые в рантайме.
|
||||||
|
- `CLIENT_PATCH`: клиентские MPQ-патчи (`patch-Z.mpq`).
|
||||||
|
- `LOGICAL_FEATURE`: логические переключатели ядра (`client-compat`).
|
||||||
|
|
||||||
|
### 1.2. Конвейер сборки DLL и границы совместимости
|
||||||
|
Modules V2 содержит изолированный сборочный движок ([crates/coa-core/src/build_engine.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/build_engine.rs)):
|
||||||
|
- **Тулчейн:** автоматическое обнаружение MSVC x64 (`vcvars64.bat`), CMake, Ninja и дерева экспортированного SDK (`C:\games\coa-work\plugin-spike\sdk-v03`).
|
||||||
|
- **Генератор адаптера (`generate_adapter`):** лексически анализирует исходники модуля, находит функцию входа `Add...Scripts()`, генерирует файл `adapter.cpp`, реализующий интерфейс `IPlugin` и функцию запроса контракта `CoaPluginQuery`.
|
||||||
|
- **Границы совместимости DLL:**
|
||||||
|
1. *Поддерживаются:* модули, написанные на чистом C++ с использованием хуков ScriptMgr (`PlayerScript`, `WorldScript`, `CreatureScript`, `ItemScript` и т.д.), не модифицирующие ядро.
|
||||||
|
2. *Не поддерживаются:* модули, требующие изменений ядра (`CorePatchRequired` — патчи `Player.cpp`, DBC-структур), модули с внешними нелинкуемыми библиотеками (`ALE` без LuaJIT рантайма), или модули с отсутствующими экспортами ядра (`SdkExportMissing`).
|
||||||
|
3. *ABI-контроль:* сборка возможна только при совпадении хэша ABI хоста (`realm_sdk_fingerprint`) со слепком SDK.
|
||||||
|
|
||||||
|
### 1.3. Транзакционная установка и ворота безопасности
|
||||||
|
Установка модулей управляется через [crates/coa-core/src/preview.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/preview.rs) и [plugins.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/plugins.rs):
|
||||||
|
- **Stop-Gate (`require_server_stopped`):** установка, удаление или обновление DLL строго блокируются, если процесс `worldserver.exe` активен.
|
||||||
|
- **SQL Review Gate (`plan_sql_review`):** статический парсер SQL выявляет наличие DDL-мутаций (`CREATE/ALTER TABLE`) и требует явного подтверждения пользователя.
|
||||||
|
- **Реестр:** состояние фиксируется в `.manager/plugins.json` со слепками SHA-256 файлов, версиями и путями к конфигам.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Карта существующих компонентов с путями и функциями
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
UI["ModulesPage.tsx (React/Tailwind)"] -->|IPC Invoke| Tauri["src-tauri/src/lib.rs"]
|
||||||
|
Tauri --> Analyzer["analyzer.rs (Intake & L0 Static Audit)"]
|
||||||
|
Tauri --> Builder["build_engine.rs (MSVC / CMake / Adapter Gen)"]
|
||||||
|
Tauri --> Preview["preview.rs (Stop-Gate / SQL Gate / Orchestration)"]
|
||||||
|
Preview --> Plugins["plugins.rs (Store & .manager/plugins.json)"]
|
||||||
|
```
|
||||||
|
|
||||||
|
| Уровень / Назначение | Путь к файлу | Ключевые функции / Точки входа |
|
||||||
|
|---|---|---|
|
||||||
|
| **Intake & Static Audit** | `crates/coa-core/src/analyzer.rs` | `analyze_github_module_for_realm(&url, &realm_root, cache_dir)`<br>`analyze_github_repository(&url, cache_dir)`<br>`parse_and_validate_github_url(&url)` |
|
||||||
|
| **Controlled Build Engine** | `crates/coa-core/src/build_engine.rs` | `detect_toolchain()`<br>`build_module_from_source(&source_dir, &realm_root, ...)`<br>`generate_adapter(&module_dir)` |
|
||||||
|
| **Lifecycle & Orchestration** | `crates/coa-core/src/preview.rs` | `install_qualified_module(&realm_root, &id, &ver, apply_sql, ...)`<br>`list_installed_preview_plugins(&realm_root)`<br>`toggle_preview_module(&realm_root, &id, enable)`<br>`remove_preview_module(&realm_root, &id)`<br>`plan_sql_review(&module_id, &report)` |
|
||||||
|
| **Plugin Store & Registry** | `crates/coa-core/src/plugins.rs` | `load_registry(&root)` / `save_registry(&root, ®)`<br>`install(...)` / `remove(...)`<br>`require_server_stopped(&root)` |
|
||||||
|
| **Tauri IPC Bridge** | `src-tauri/src/lib.rs` | `analyze_github_module(url, realm_id)` (L2800)<br>`preview_build_module(realm_id, source)` (L2849)<br>`preview_install_module(realm_id, id, ver, sql)` (L2895)<br>`preview_toggle_module(realm_id, id, enable)` (L2919)<br>`preview_remove_module(realm_id, id)` (L2934)<br>`preview_list_installed_plugins(realm_id)` (L2948) |
|
||||||
|
| **Frontend API Layer** | `src/lib/api.ts` | `api.analyzeGithubModule(url, realmId)` (L733)<br>`api.previewBuildModule(realmId, source)`<br>`api.previewInstallModule(...)`<br>`api.previewToggleModule(...)` |
|
||||||
|
| **Modules V2 UI View** | `src/screens/ModulesPage.tsx` | Вкладка `installed` (L2151)<br>Вкладка `catalog` (L2813)<br>Вкладка `builds` (L3431)<br>Вкладка `toolchain` (L3500)<br>Функция интейка: `runAnalysis(url)` (L1328)<br>Функция сборки: `startControlledBuild(url)` (L1365) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Точки интеграции каталога
|
||||||
|
|
||||||
|
Существующая архитектура Modules V2 **полностью готова к приёму URL репозиториев**.
|
||||||
|
|
||||||
|
Точкой интеграции на стороне Frontend является функция:
|
||||||
|
```typescript
|
||||||
|
// src/screens/ModulesPage.tsx, строки 1328–1362
|
||||||
|
async function runAnalysis(urlToAnalyze?: string) {
|
||||||
|
const targetUrl = (urlToAnalyze || githubUrl).trim();
|
||||||
|
if (!targetUrl) return;
|
||||||
|
setGithubUrl(targetUrl);
|
||||||
|
setAnalyzing(true);
|
||||||
|
// ...
|
||||||
|
const rep = await api.analyzeGithubModule(targetUrl, serverId);
|
||||||
|
setReport(rep);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Принцип бесшовной стыковки:
|
||||||
|
1. Каталог модулей отображает карточки доступных репозиториев.
|
||||||
|
2. При нажатии на карточке кнопки **«Анализировать и подготовить к установке»** вызывается:
|
||||||
|
```typescript
|
||||||
|
runAnalysis(module.html_url);
|
||||||
|
```
|
||||||
|
3. CSM автоматически переключает контекст на анализ репозитория, скачивает исходники в кэш, выполняет L0-аудит и отображает модальное окно совместимости.
|
||||||
|
4. Пользователь нажимает **«Собрать DLL»** (`startControlledBuild()`), после чего срабатывает `previewInstallModule()`.
|
||||||
|
|
||||||
|
**Результат:** Не требуется создавать второй установщик, дублировать сборщик или менять логику реестра `.manager/plugins.json`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Перечень уже реализованных возможностей
|
||||||
|
|
||||||
|
В ветке `preview/modules-v2` уже полностью реализованы и протестированы:
|
||||||
|
1. Загрузка исходных кодов с GitHub с кэшированием в `%LOCALAPPDATA%\CSMModulesPreview\github_cache` и дедупликацией по SHA дерева коммита.
|
||||||
|
2. Статический анализатор совместимости (L0 Static Analysis) с проверкой сигнатур функций `Add...Scripts()`, детекцией core patches, парсингом SQL-миграций и проверкой лицензий.
|
||||||
|
3. Автоматический генератор C++ адаптеров `IPlugin` под CoA Plugin SDK.
|
||||||
|
4. Сборочный движок MSVC x64 + Ninja + CMake с захватом логов компиляции в реальном времени.
|
||||||
|
5. Stop-Gate валидация (защита от изменения DLL и баз данных работающего сервера).
|
||||||
|
6. SQL Review Gate (анализ рисков DDL/DML перед наложением на базу данных).
|
||||||
|
7. Установка DLL в хранилище `.manager/plugin-store/`, создание символических ссылок в `plugins/` и фиксация в `.manager/plugins.json`.
|
||||||
|
8. Полный жизненный цикл установленных плагинов: включение, отключение, безопасное удаление (с сохранением пользовательских таблиц БД).
|
||||||
|
9. Пользовательский интерфейс с вкладками «Установленные плагины», «Сборка & логи MSVC» и «Среда сборки & SDK».
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Перечень отсутствующих компонентов
|
||||||
|
|
||||||
|
Для полноценной работы каталога в Modules V2 отсутствуют исключительно компоненты **обнаружения и доставки метаданных**:
|
||||||
|
1. **Сетевой загрузчик официального JSON (`PublicCatalogueFetcher`):** сервис в `crates/coa-core`, скачивающий `https://www.azerothcore.org/data/catalogue.json` с поддержкой ETag и сохранением на диск.
|
||||||
|
2. **Локальный дисковый кэш каталога:** файл кэша в `%LOCALAPPDATA%\CSMModulesPreview\catalogue_cache.json` с оффлайн-фоллбэком.
|
||||||
|
3. **Парсер и фильтр категории `azerothcore-module`:** извлечение 545 репозиториев, нормализация данных, отсеивание заведомо нерелевантных проектов (чистые Lua/SQL).
|
||||||
|
4. **Кураторский оверлей CoA (`coa-modules-overlay.json`):** встроенный или подгружаемый файл, содержащий экспертные вердикты для ядра CoA (`Verified`, `Incompatible`, `RequiresAdapter`).
|
||||||
|
5. **Tauri IPC команда `get_public_module_catalog`:** эндпоинт передачи каталога во фронтенд.
|
||||||
|
6. **Динамический каталог в UI (`ModulesPage.tsx`):** расширение вкладки `catalog`, заменяющее жестко закодированный массив `VERIFIED_CATALOG` на динамический список с поиском, сортировкой и карточкой деталей.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Предлагаемые минимальные изменения Backend
|
||||||
|
|
||||||
|
### 6.1. Новый модуль `crates/coa-core/src/catalogue.rs`
|
||||||
|
Добавляется один изолированный файл со структурами и логикой:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// crates/coa-core/src/catalogue.rs
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
pub const OFFICIAL_CATALOGUE_URL: &str = "https://www.azerothcore.org/data/catalogue.json";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RawRepoEntry {
|
||||||
|
pub id: u64,
|
||||||
|
pub name: String,
|
||||||
|
pub full_name: String,
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub stargazers_count: u32,
|
||||||
|
pub default_branch: String,
|
||||||
|
pub html_url: String,
|
||||||
|
pub forks_count: u32,
|
||||||
|
pub watchers_count: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub pushed_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub updated_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license: Option<RawLicense>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub topics: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RawLicense {
|
||||||
|
pub spdx_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RawCatalogue {
|
||||||
|
pub global_search: bool,
|
||||||
|
pub organizations: BTreeMap<String, BTreeMap<String, Vec<RawRepoEntry>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PublicModuleCard {
|
||||||
|
pub id: u64,
|
||||||
|
pub name: String,
|
||||||
|
pub full_name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub stars: u32,
|
||||||
|
pub html_url: String,
|
||||||
|
pub default_branch: String,
|
||||||
|
pub last_pushed: String,
|
||||||
|
pub license: String,
|
||||||
|
pub topics: Vec<String>,
|
||||||
|
pub coa_status: String, // "verified", "unverified", "incompatible", "blocked"
|
||||||
|
pub coa_note: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CatalogueResponse {
|
||||||
|
pub modules: Vec<PublicModuleCard>,
|
||||||
|
pub cached_at: String,
|
||||||
|
pub is_offline: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_catalogue(cache_dir: &Path, force_refresh: bool) -> Result<CatalogueResponse> {
|
||||||
|
let cache_file = cache_dir.join("catalogue_cache.json");
|
||||||
|
let etag_file = cache_dir.join("catalogue_etag.txt");
|
||||||
|
|
||||||
|
// 1. Проверка необходимости обновления и загрузка с ETag через reqwest
|
||||||
|
// 2. Слияние с coa-modules-overlay.json
|
||||||
|
// 3. Возврат нормализованного списка
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2. Регистрация в `crates/coa-core/src/lib.rs`
|
||||||
|
Добавить строку:
|
||||||
|
```rust
|
||||||
|
pub mod catalogue;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3. Экспорт команды в `src-tauri/src/lib.rs`
|
||||||
|
Добавить одну команду:
|
||||||
|
```rust
|
||||||
|
#[tauri::command]
|
||||||
|
async fn get_public_module_catalog(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
force_refresh: bool,
|
||||||
|
) -> std::result::Result<coa_core::catalogue::CatalogueResponse, UiError> {
|
||||||
|
let cache_dir = data_dir().join("catalogue");
|
||||||
|
blocking(move || {
|
||||||
|
coa_core::catalogue::get_catalogue(&cache_dir, force_refresh)
|
||||||
|
.map_err(Into::into)
|
||||||
|
}).await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
И зарегистрировать её в `generate_handler!`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Предлагаемые изменения Frontend
|
||||||
|
|
||||||
|
### 7.1. Расширение `src/lib/api.ts`
|
||||||
|
Добавить один метод:
|
||||||
|
```typescript
|
||||||
|
getPublicModuleCatalog: (forceRefresh = false) =>
|
||||||
|
invoke<CatalogueResponse>("get_public_module_catalog", { forceRefresh }),
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2. Минимальные изменения в `src/screens/ModulesPage.tsx`
|
||||||
|
В существующей вкладке `catalog` (строки 2813–3100):
|
||||||
|
1. **Загрузка данных:** При открытии вкладки `catalog` вызывать `api.getPublicModuleCatalog()`.
|
||||||
|
2. **Панель фильтров и поиска:**
|
||||||
|
- Поле поиска: фильтрация списка по `name`, `description`, `topics`.
|
||||||
|
- Сортировка: «По звёздам (популярные)», «По дате обновления (свежие)».
|
||||||
|
- Фильтр категорий: «Все» (545), «Проверенные CoA», «Геймплей», «Утилиты».
|
||||||
|
3. **Карточка модуля:**
|
||||||
|
- Название, автор, описание, бейдж звёзд и лицензии.
|
||||||
|
- Бейдж совместимости с CoA:
|
||||||
|
- Зелёный: `Verified CoA` (из оверлея).
|
||||||
|
- Серый: `Unverified Public` (из официального каталога).
|
||||||
|
- Красный: `Incompatible with CoA` (известный конфликт).
|
||||||
|
- Кнопка действия:
|
||||||
|
- Если модуль уже установлен (совпадает `repo` с установленными в `installedPlugins`): отображать бейдж `Установлен` с версией.
|
||||||
|
- Если не установлен: кнопка **«Анализировать и установить»**.
|
||||||
|
4. **Обработчик кнопки установки:**
|
||||||
|
```typescript
|
||||||
|
onClick={() => {
|
||||||
|
runAnalysis(module.html_url);
|
||||||
|
}}
|
||||||
|
```
|
||||||
|
*Больше ничего не требуется:* клик переключает состояние, запускает L0-анализ, открывает окно совместимости и передает управление в готовый сборочный движок.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Схема потоков данных
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor User as Пользователь
|
||||||
|
participant UI as ModulesPage (Catalog Tab)
|
||||||
|
participant IPC as Tauri IPC (lib.rs)
|
||||||
|
participant Cat as CatalogueFetcher (crates/coa-core)
|
||||||
|
participant CDN as azerothcore.org (Cloudflare CDN)
|
||||||
|
participant Analyzer as analyzer.rs (Intake & L0)
|
||||||
|
participant Builder as build_engine.rs (MSVC)
|
||||||
|
participant Installer as preview.rs & plugins.rs
|
||||||
|
|
||||||
|
User->>UI: Переход во вкладку "Каталог"
|
||||||
|
UI->>IPC: get_public_module_catalog(force_refresh=false)
|
||||||
|
IPC->>Cat: get_catalogue(cache_dir)
|
||||||
|
alt Кэш отсутствует или устарел
|
||||||
|
Cat->>CDN: GET /data/catalogue.json (If-None-Match: etag)
|
||||||
|
CDN-->>Cat: 200 OK (804 KB JSON)
|
||||||
|
Cat->>Cat: Сохранение cache.json и etag.txt
|
||||||
|
else Кэш актуален
|
||||||
|
Cat->>CDN: GET /data/catalogue.json
|
||||||
|
CDN-->>Cat: 304 Not Modified
|
||||||
|
end
|
||||||
|
Cat->>Cat: Слияние с coa-modules-overlay.json
|
||||||
|
Cat-->>UI: CatalogueResponse (545 модулей)
|
||||||
|
UI-->>User: Отображение каталога с поиском и бейджами CoA
|
||||||
|
|
||||||
|
User->>UI: Клик "Анализировать и установить" (выбран mod-aoe-loot)
|
||||||
|
UI->>IPC: analyze_github_module(url, realm_id)
|
||||||
|
IPC->>Analyzer: analyze_github_module_for_realm()
|
||||||
|
Analyzer->>Analyzer: Git intake, AST аудит, проверка Add...Scripts, SQL аудит
|
||||||
|
Analyzer-->>UI: CompatibilityReport (L0 PASS, Buildable)
|
||||||
|
UI-->>User: Модальное окно аудита совместимости
|
||||||
|
|
||||||
|
User->>UI: Клик "Собрать DLL"
|
||||||
|
UI->>IPC: preview_build_module(realm_id, url)
|
||||||
|
IPC->>Builder: build_module_from_source()
|
||||||
|
Builder->>Builder: Генерация adapter.cpp, компиляция MSVC + Ninja
|
||||||
|
Builder-->>UI: BuildResult (Success, DLL SHA-256)
|
||||||
|
|
||||||
|
User->>UI: Клик "Установить в сервер"
|
||||||
|
UI->>IPC: preview_install_module(realm_id, module_id, ver, apply_sql)
|
||||||
|
IPC->>Installer: install_qualified_module()
|
||||||
|
Installer->>Installer: Stop-Gate check, копирование DLL, plugins.json
|
||||||
|
Installer-->>UI: PreviewInstallResult (Success)
|
||||||
|
UI-->>User: Модуль активен в сервере!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Модель кэширования и обновления
|
||||||
|
|
||||||
|
1. **Заголовки ETag / Conditional Requests:**
|
||||||
|
Сервер `azerothcore.org` возвращает стандартный HTTP заголовок `ETag: "88aa9d..."`. При повторном запросе CSM отправляет `If-None-Match`. Получение `304 Not Modified` полностью исключает передачу 800 КБ по сети.
|
||||||
|
2. **Дисковый кэш:**
|
||||||
|
Кэш сохраняется в `%LOCALAPPDATA%\CSMModulesPreview\catalogue\cache.json`.
|
||||||
|
3. **Оффлайн-режим:**
|
||||||
|
Если подключение к сети отсутствует (NetworkUnreachable, DNS failure), клиент не выдает ошибку, а прозрачно возвращает сохранённый `cache.json` с флагом `is_offline = true`.
|
||||||
|
4. **Защита от повреждений:**
|
||||||
|
Запись файла кэша производится атомарно через временный файл (`fsx::atomic_write`). При повреждении JSON кэш отбрасывается, и используется встроенный в бинарник минимальный снапшот.
|
||||||
|
5. **Дедупликация и переименования:**
|
||||||
|
Естественным ключом в каталоге является числовой `id` репозитория GitHub. При переименовании репозитория `id` сохраняется, обновляется только поле `full_name`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Интеграция с анализатором совместимости
|
||||||
|
|
||||||
|
Каталог и существующий анализатор [crates/coa-core/src/analyzer.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/analyzer.rs) работают в синергии:
|
||||||
|
- **В каталоге (до выбора):** пользователь видит метаданные GitHub (звезды, дату обновления) + кураторский статус CoA (`Verified`, `Incompatible`, `Unverified`).
|
||||||
|
- **После выбора модуля:** запускается глубокий анализ `analyze_github_module_for_realm`:
|
||||||
|
1. Вычисляется точный хэш исходного кода (`.coa_tree_digest`).
|
||||||
|
2. Проверяется наличие экспортов ядра через PE-парсинг `worldserver.exe` (`parse_pe_exports`).
|
||||||
|
3. Проверяется совпадение ABI-фингерпринта.
|
||||||
|
4. Проверяется канонический загрузчик `Add<module_name>Scripts()`.
|
||||||
|
5. Проводится аудит SQL-миграций на наличие `CREATE/ALTER TABLE`.
|
||||||
|
6. Формируется отчет `CompatibilityReport` с многомерным статусом (`BuildStatus`, `RuntimeStatus`, `GameplayStatus`).
|
||||||
|
|
||||||
|
Таким образом, публичный каталог выступает **витриной обнаружения**, а существующий анализатор Modules V2 — **воротами допуска**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. План тестирования (Интеграционная матрица)
|
||||||
|
|
||||||
|
| № | Тестовый сценарий | Ожидаемый результат | Метод проверки |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | Загрузка каталога онлайн | Загружено 545 модулей, статус 200 OK, сохранен кэш и ETag | Unit-тест `test_catalogue_fetch_online` с mock-сервером |
|
||||||
|
| 2 | Повторная загрузка с валидным ETag | Сервер отвечает 304 Not Modified, данные берутся из локального кэша | Mock HTTP тест с проверкой заголовка `If-None-Match` |
|
||||||
|
| 3 | Загрузка в оффлайн-режиме | Возвращаются данные из `cache.json`, флаг `is_offline == true` | Тест с отключенным сетевым адаптером / mock network error |
|
||||||
|
| 4 | Поврежденный кэш на диске | Ошибка перехватывается, загружается резервный снапшот, приложение не падает | Повреждение файла `cache.json` битыми байтами |
|
||||||
|
| 5 | Дедупликация репозиториев | В списке отсутствуют дублирующиеся ID репозиториев | Проверка `Set<id>.len() == list.len()` |
|
||||||
|
| 6 | Распознавание установленных модулей | Модуль, установленный в сервере, помечается в каталоге бейджем `Установлен` | Сверка `repo` каталога со списком `list_installed_preview_plugins` |
|
||||||
|
| 7 | Передача URL в `runAnalysis` | При клике по модулю поле `githubUrl` заполняется корректным URL, стартует L0-анализ | Проверка аргументов вызова `api.analyzeGithubModule` |
|
||||||
|
| 8 | Сохранение ручного ввода URL | Поле ввода произвольного GitHub URL продолжает функционировать | Ручной ввод `https://github.com/custom/repo` и запуск анализа |
|
||||||
|
| 9 | Передача данных в анализатор | Анализатор получает URL, загружает репозиторий и возвращает `CompatibilityReport` | Прогон анализатора на модуле `mod-aoe-loot` |
|
||||||
|
| 10 | Ворота безопасности (Stop-Gate) | Попытка установить модуль при работающем `worldserver.exe` блокируется | Интеграционный тест `require_server_stopped` |
|
||||||
|
| 11 | Отображение ошибок сборки | При ошибке компиляции в логах MSVC пользователь видит подсказку в UI | Сборка заведомо битого C++ модуля |
|
||||||
|
| 12 | Предупреждение о конфликтах CoA | Модуль `mod-learn-spells` отображает предупреждение о конфликте с драфтом | Проверка поля `coa_status == "incompatible"` |
|
||||||
|
| 13 | Фиксация версий установленных модулей | Обновление каталога не затрагивает скомпилированные DLL в `.manager/plugins/` | Сравнение хэшей DLL до и после обновления каталога |
|
||||||
|
| 14 | Производительность UI | Рендеринг 545 карточек с виртуализацией или пагинацией не вызывает фризов UI | React Profiler тест рендеринга страницы |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Риски и потенциальные регрессии
|
||||||
|
|
||||||
|
| Риск | Вероятность | Влияние | Мера предотвращения |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Регрессия существующего ручного ввода URL** | Низкая | Высокое | Ручной ввод GitHub URL остается в интерфейсе как приоритетный альтернативный способ; каталог только передает URL в ту же функцию `runAnalysis`. |
|
||||||
|
| **Падение UI при рендеринге 500+ элементов** | Средняя | Среднее | Использование поиска/фильтрации на клиенте с лимитом отображения (пагинация по 24 карточки или виртуальный скроллинг). |
|
||||||
|
| **Изменение формата JSON официального каталога AC** | Низкая | Среднее | Использование `serde(default)` для всех необязательных полей; строгие fallback-значения при отсутствии полей. |
|
||||||
|
| **Ложная уверенность пользователя в совместимости** | Высокая | Высокое | Яркие бейджи: статус `Unverified Public` для всех сторонних модулей из каталога до прохождения L0–L5 тестов. |
|
||||||
|
| **Блокировка сервером CDN (HTTP 429)** | Минимальная | Низкое | Запросы отправляются только раз в 12–24 часа или по явному клику пользователя «Обновить»; наличие оффлайн-кэша. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. План реализации небольшими независимыми этапами
|
||||||
|
|
||||||
|
### Этап 1: Backend & Сетевой кэш (Бэкенд-сервис каталога)
|
||||||
|
- Создать `crates/coa-core/src/catalogue.rs`.
|
||||||
|
- Реализовать загрузку `https://www.azerothcore.org/data/catalogue.json` с поддержкой ETag.
|
||||||
|
- Реализовать чтение локального файла `coa-modules-overlay.json` и слияние статусов.
|
||||||
|
- Написать модульные тесты парсинга и кэширования.
|
||||||
|
- *Результат:* Автономный протестированный Rust-модуль, готовый к вызову из Tauri.
|
||||||
|
|
||||||
|
### Этап 2: Tauri IPC Bridge & Frontend API
|
||||||
|
- Зарегистрировать команду `get_public_module_catalog` в `src-tauri/src/lib.rs`.
|
||||||
|
- Добавить типизированный метод в `src/lib/api.ts`.
|
||||||
|
- *Результат:* Фронтенд может запрашивать актуальный список модулей одной асинхронной функцией.
|
||||||
|
|
||||||
|
### Этап 3: UI интеграция в `ModulesPage.tsx`
|
||||||
|
- Во вкладке `catalog` заменить хардкод `VERIFIED_CATALOG` на динамическую загрузку через `api.getPublicModuleCatalog()`.
|
||||||
|
- Добавить строку поиска, фильтры категорий и селектор сортировки.
|
||||||
|
- Привязать кнопку действия карточки модуля к существующей функции `runAnalysis(module.html_url)`.
|
||||||
|
- *Результат:* Пользователь выбирает любой модуль из официального каталога AzerothCore и запускает штатный процесс анализа и сборки Modules V2 в один клик.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Сводная таблица компонентов
|
||||||
|
|
||||||
|
| Компонент | Уже существует | Требуется изменить | Новый компонент | Описание и роль |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **GitHub downloader** | `analyzer.rs` (`analyze_github_repository`) | **НЕ МЕНЯТЬ** | Нет | Клонирует и кэширует исходники репозитория в `%LOCALAPPDATA%\CSMModulesPreview\github_cache`. Полностью готов. |
|
||||||
|
| **Compatibility analyzer** | `analyzer.rs` (`analyze_github_module_for_realm`) | **НЕ МЕНЯТЬ** | Нет | Выполняет L0 Static Audit, проверяет хуки, сигнатуру `Add...Scripts`, структуру SQL и лицензии. Полностью готов. |
|
||||||
|
| **Module builder** | `build_engine.rs` (`build_module_from_source`) | **НЕ МЕНЯТЬ** | Нет | Генерирует C++ адаптер `IPlugin`, компилирует MSVC x64 + Ninja против CoA SDK v0.3. Полностью готов. |
|
||||||
|
| **Module installer** | `preview.rs` (`install_qualified_module`) & `plugins.rs` | **НЕ МЕНЯТЬ** | Нет | Контролирует Stop-Gate, SQL Review Gate, копирует DLL в `.manager/plugin-store/`, прописывает в `plugins.json`. Полностью готов. |
|
||||||
|
| **Module registry** | `.manager/plugins.json` (`plugins.rs`) | **НЕ МЕНЯТЬ** | Нет | Авторитетный реестр установленных плагинов realm'а. Полностью готов. |
|
||||||
|
| **Module Catalogue Fetcher** | Нет | Нет | **ДА (`catalogue.rs`)** | Скачивает официальный JSON с CDN AzerothCore с ETag-кэшированием и оверлеем CoA. Новый легковесный компонент. |
|
||||||
|
| **Modules UI** | `ModulesPage.tsx` | **Минимально расширить** | Нет | В существующую вкладку `catalog` добавляется вызов `getPublicModuleCatalog()` и связка с `runAnalysis()`. Без переписывания UI. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. Анализ различий веток: `master` vs `preview/modules-v2`
|
||||||
|
|
||||||
|
| Характеристика / Возможность | Состояние в `master` (предыдущий аудит) | Состояние в `preview/modules-v2` (целевая ветка) | Влияние на план интеграции |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Модель модулей** | Только монолитная компиляция в `worldserver.exe` | **Полноценная архитектура динамических DLL плагинов** | Отпала необходимость проектировать систему сборки и загрузки модулей. |
|
||||||
|
| **Сборочный движок** | Отсутствовал в коде CSM | **Реализован в `build_engine.rs` (MSVC + Ninja + Adapter Gen)** | Сборщик уже написан, отлажен и квалифицирован на тестовой когорте T01–T04. |
|
||||||
|
| **Анализатор совместимости** | Базовые заготовки | **Мощный модуль `analyzer.rs` (2445 строк, L0–L6 верификация)** | Анализатор готов к приему любого репозитория из каталога. |
|
||||||
|
| **Установщик и транзакции** | Только текстовая правка `.conf` файлов | **Транзакционный установщик в `preview.rs` со Stop-Gate и SQL Review** | Установщик готов и защищает сервер от крашей на лету. |
|
||||||
|
| **Интерфейс управления** | Простой список из 9 карточек | **4-вкладочный интерфейс `ModulesPage.tsx` (2737 строк)** | Интерфейс готов: нужно лишь заменить статический каталог на динамический. |
|
||||||
|
| **Каталог модулей** | Статический `modules/catalog.json` (9 шт.) | Статический `VERIFIED_CATALOG` в TypeScript (8 шт.) | **Единственная недостающая часть — подключение официального JSON к каталогу.** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Главный вопрос и итоговый вердикт
|
||||||
|
|
||||||
|
### Главный вопрос:
|
||||||
|
*Как добавить официальный публичный каталог AzerothCore в уже работающую систему Modules V2 с минимальными изменениями, без дублирования существующей логики и без регрессий установки модулей?*
|
||||||
|
|
||||||
|
### Итоговый технический вердикт:
|
||||||
|
|
||||||
|
1. **Готова ли Modules V2 к подключению каталога?**
|
||||||
|
**Да, на 100%.** Архитектура ветки `preview/modules-v2` находится в состоянии полной готовности: вся сквозная цепочка (`Intake URL -> Analyze -> Build DLL -> Review SQL -> Install -> Toggle -> Remove`) уже функционирует и протестирована. Каталог нужен исключительно как поставщик URL для этой цепочки.
|
||||||
|
|
||||||
|
2. **Сколько новых компонентов действительно необходимо?**
|
||||||
|
**Ровно один новый модуль на Backend:** `crates/coa-core/src/catalogue.rs` (~200 строк чистого кода на Rust) для загрузки `https://www.azerothcore.org/data/catalogue.json` с ETag-кэшированием и наложением кураторских статусов CoA.
|
||||||
|
|
||||||
|
3. **Какие существующие функции будут переиспользованы?**
|
||||||
|
- `analyze_github_module_for_realm` ([analyzer.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/analyzer.rs)) — для глубокого аудита выбранного модуля.
|
||||||
|
- `build_module_from_source` ([build_engine.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/build_engine.rs)) — для компиляции выбранного модуля в DLL.
|
||||||
|
- `install_qualified_module` ([preview.rs](file:///C:/games/coa-server-manager-preview/crates/coa-core/src/preview.rs)) — для безопасной установки плагина.
|
||||||
|
- `runAnalysis` ([ModulesPage.tsx](file:///C:/games/coa-server-manager-preview/src/screens/ModulesPage.tsx)) — как готовая точка запуска пайплайна по клику в UI.
|
||||||
|
|
||||||
|
4. **Есть ли архитектурные препятствия?**
|
||||||
|
**Архитектурных препятствий нет.** Никаких конфликтов зависимостей, ограничений по типам данных или блокеров в дизайне Modules V2 не обнаружено.
|
||||||
|
|
||||||
|
5. **Какой минимальный безопасный объём изменений требуется для первого рабочего релиза?**
|
||||||
|
1. Добавить `crates/coa-core/src/catalogue.rs` (загрузка JSON и дисковый кэш).
|
||||||
|
2. Зарегистрировать IPC-команду `get_public_module_catalog` в `src-tauri/src/lib.rs`.
|
||||||
|
3. В `src/screens/ModulesPage.tsx` заменить хардкод `VERIFIED_CATALOG` на рендеринг списка из API и вызов `runAnalysis(module.html_url)` при клике.
|
||||||
|
|
||||||
|
*Все остальные механизмы Modules V2 остаются нетронутыми.*
|
||||||
@@ -1,5 +1,39 @@
|
|||||||
# TODO
|
# TODO
|
||||||
|
|
||||||
|
## Подготовка 0.9.8, 2026-10-31
|
||||||
|
|
||||||
|
- Подготовлены исходники `C:/games/source/per-race-manager`, ветка `fix/launcher-validation-candidate-20261031`: изоляция bot configs на время проверки с точным восстановлением, повторное использование MySQL внутри validation, зависимость Dungeon Clear от SQUID, три режима логов и экспорт этапов launcher/control owner.
|
||||||
|
- Workspace: 840 тестов прошли, 60 ignored; последующие focused diagnostics: 11 прошли. Переводы новых заметок и UI подготовлены, web build/i18n/bridge/history checks прошли. Подробности и ограничения: `C:/games/source/candidate-preparation-20261031.md`.
|
||||||
|
- Не выпускать Manager до кандидата сервера. Installer ещё не собирался и не публиковался; подготовка источников не равна готовому кандидату.
|
||||||
|
|
||||||
|
## Приоритет: проверка установки и обновления (2026-10-31)
|
||||||
|
- **Локальные замеры массовых Companions (2026-10-31):** отчёт `C:/games/source/companions-benchmark-20261031/REPORT.md`, сырые выборки/qualification в той же папке. Native worldserver SHA `bd9f65ac7543fad8159231000d5ef6436a159aa009b65cbdc9541a0e9fe1ee7b`, Ryzen 7 7700X/32 GiB, `MapUpdate.Threads=1`, все CPU доступны. Перед условиями восстанавливался один снимок персонажей. Без записи логов медианы среднего тика: 0 ботов 4.5 ms; 500 — 39 ms; 1000 — 91 ms; 2000 — 246 ms, поздний замер 259 ms. С обычными логами: 500 — 43.5 ms; 1000 — 111 ms. Запуск 2000 с логами дал 1381 ms, последующий полный Logger-off 363 ms, но нагрузка хоста менялась; чистый множитель логирования этими числами не доказан. Всего 9 условий с подтверждённым online; исходная база 21 шаблон/0 тестовых аккаунтов восстановлена, тестовые процессы остановлены. Повтор 2000 с логами подготовлен, но НЕ выполнен: на C: осталось около 300 MiB. Соответствующий PDB для функционального профиля отсутствует.
|
||||||
|
- [ ] **Разобрать штатное завершение мира под большой популяцией**:
|
||||||
|
- В локальном бенчмарке ряд запусков (включая 2000 ботов и полностью отключённые логгеры) не завершились за 90 секунд после `server shutdown 1s 0`; пришлось завершать только тестовый процесс после сохранения измерений. Стек `2000-shutdown-stacks.txt` показывает ожидание `MSVCP140!Thrd_join`, точный ожидаемый поток без matching PDB не установлен. Не объявлять это доказанной причиной пользовательского control.lock или влиянием только логов.
|
||||||
|
|
||||||
|
- [ ] **Разобрать удержание control.lock после видимого запуска сервера**:
|
||||||
|
- Пользователь после hotfix v3 получил `Another start/stop action is in progress` при внешнем `with launcher["control_lock"]()`, хотя мир отвечал и Manager показывал работающий сервер. Не считать это доказательством «зависшего файла»: Windows блокирует диапазон живым дескриптором.
|
||||||
|
- На Python 3.14.7 точно воспроизведён конкурентный захват: второй лаунчер получает эту ошибку, после выхода владельца захват снова проходит. Причина долгого удержания у пользователя пока не установлена; нужны его свежие launch diagnostics.
|
||||||
|
- Добавить безопасную диагностику владельца (PID, время создания, действие, этап ожидания) и проверить сериализацию Start/Stop/Restart/validation/recovery. Различать реальную занятость и прочие OSError захвата, которые сейчас маскируются одним сообщением. Не удалять lock и не завершать чужие процессы ради обхода.
|
||||||
|
|
||||||
|
- **Проверка с ботами завершена (2026-10-31):** пользователь показал работающие MySQL/auth/world, 2000 Companions онлайн и вход своим клиентом в мир после обновления. Это подтверждает обычный запуск с ботами после hotfix, но не пригодность массового автологина для validation. Ранний снимок показывает около 11 тиков/с на 2m32s работы; результат замера после прогрева пока неизвестен.
|
||||||
|
|
||||||
|
- **Пользовательская проверка (2026-10-31):** после hotfix лаунчера v3 и отключения автологина Companions обновление завершилось успешно (server `0.261030.90`, Manager `0.9.7`). Отдельная проверка с включёнными ботами пока не завершена.
|
||||||
|
- [ ] **Сократить повторные запуски MySQL в установке/обновлении**:
|
||||||
|
- Пользователь после успешного обновления отметил большую длительность и многократные старты/остановки базы, в том числе на 85%. Проследить фактическую последовательность snapshot/SQL/schema/validation/recovery и повторно использовать уже запущенную, проверенную базу между совместимыми этапами.
|
||||||
|
- Не убирать остановки, необходимые для согласованного backup/restore, замены файлов и восстановления после отказа. Сохранить гарантии rollback и владения процессами. Записать число стартов/остановок и длительность этапов до/после; проверить обновление без ботов и восстановление после ошибки.
|
||||||
|
|
||||||
|
- [ ] **Временный конфиг проверки без массового запуска ботов**:
|
||||||
|
- Запрос владельца: грузить 2000 ботов ради проверки установки/обновления недопустимо. Облегчить все проверочные запуски, включая восстановление/повторную проверку, где применяется тот же путь запуска.
|
||||||
|
- Факты случая: этап обновления 85%, CoA Companions поставили в очередь 2000 ботов; пользователь сообщает об остановке продвижения на 519 за 6 минут. Логи показывают 518 уникальных имён в `ACTIVE_LIST`. Это не SQUID. Место зависания и причинная связь с автологином пока не установлены.
|
||||||
|
- Перед проверочным запуском временно отключать `CoaBots.AutoLoginOnStartup` и проверить другие пути автоматического входа/создания/заселения Companions, включая `CoaBots.RandomSpawn.AutoLogin`. Аналогично подавлять автоматическое заселение SQUID, если выбран этот модуль. Не подменять пользовательский выбор системы ботов и не отключать модуль целиком вместо проверки его инициализации.
|
||||||
|
- Сохранять исходные байты/отсутствие изменяемых конфигов в журнале восстановления; вернуть их до обычного запуска как при успехе, так и при ошибке, отмене, rollback и восстановлении после прерывания Manager. Не оставлять автологин выключенным пользователю. Проверить primary и дополнительные realms.
|
||||||
|
- Проверка должна подтверждать инициализацию ядра/выбранных модулей, SQL/schema, сервисы и отклик управляющего интерфейса; не ждать заполнения мира ботами и не создавать для этого тысячи персонажей. Вне validation обычный запуск сохраняет поведение пользовательских настроек.
|
||||||
|
- Проверить сценарии с Companions и лимитом 2000, SQUID, выключенными ботами; успех, отказ запуска, прерывание и восстановление исходных конфигов. Добавить регрессионные проверки и changelog после реализации.
|
||||||
|
|
||||||
|
- [ ] **Доставить исправление `manage.py` для PID 0 в согласованном серверном обновлении**:
|
||||||
|
- Серверная задача и готовый локальный hotfix описаны в `C:/games/coa-server-build/TODO.md`. Проверить импортируемый запуск через `runpy`/внешний вызов `main()` и штатный Manager update; диагностика должна работать при обоих способах загрузки.
|
||||||
|
|
||||||
## UI / UX
|
## UI / UX
|
||||||
- [x] **Предупреждение о несохранённых изменениях при переходе между вкладками (Unsaved Changes Guard / Modal)**:
|
- [x] **Предупреждение о несохранённых изменениях при переходе между вкладками (Unsaved Changes Guard / Modal)**:
|
||||||
- Если у пользователя есть несохранённые изменения в настройках (`ModulesPage`, `SettingsPage` — сервер, боты и др.) и он переходит на другую вкладку (в боковом меню `Shell.tsx` или кнопками навигации), показывать pop-up диалог подтверждения.
|
- Если у пользователя есть несохранённые изменения в настройках (`ModulesPage`, `SettingsPage` — сервер, боты и др.) и он переходит на другую вкладку (в боковом меню `Shell.tsx` или кнопками навигации), показывать pop-up диалог подтверждения.
|
||||||
@@ -27,3 +61,25 @@
|
|||||||
4. Анализировать последние строки `Core/Logs/Server.log` и `Errors.log` на критические маркеры (потеря соединения с MySQL, нехватка RAM/OOM, ошибка бинда портов).
|
4. Анализировать последние строки `Core/Logs/Server.log` и `Errors.log` на критические маркеры (потеря соединения с MySQL, нехватка RAM/OOM, ошибка бинда портов).
|
||||||
5. Проверять по встроенному словарю известных сигнатур (паттерны частых крашей с понятным описанием, например: «Сбой удаления объекта из сетки карты», «Ошибка запроса к базе данных», «Нехватка оперативной памяти»).
|
5. Проверять по встроенному словарю известных сигнатур (паттерны частых крашей с понятным описанием, например: «Сбой удаления объекта из сетки карты», «Ошибка запроса к базе данных», «Нехватка оперативной памяти»).
|
||||||
- *Fallback:* Если сигнатура не опознана в словаре известных проблем, показывать краткую техническую выжимку (код исключения + сработавший ассерт или вершина Call Stack) и кнопку разворота полного текста крашлога / копирования.
|
- *Fallback:* Если сигнатура не опознана в словаре известных проблем, показывать краткую техническую выжимку (код исключения + сработавший ассерт или вершина Call Stack) и кнопку разворота полного текста крашлога / копирования.
|
||||||
|
|
||||||
|
## Модули и контент
|
||||||
|
- [ ] **Следующий билд: переключатель Dungeon Clear только для SQUID** (запрос владельца 2026-10-31):
|
||||||
|
- Модуль: https://github.com/Zyth45/mod-dungeon-clear, ветка `coa`; серверная интеграция описана в `C:/games/coa-server-build/TODO.md`.
|
||||||
|
- Добавить в каталог отдельный модуль Dungeon Clear, по умолчанию выключенный. На старых серверах без модуля показывать недоступным.
|
||||||
|
- Разрешать включение только при установленном и включённом SQUID (`playerbots`). При выключенном SQUID блокировать переключатель и объяснять причину; CoA Companions не подходят.
|
||||||
|
- Проверять зависимость также в Rust backend при изменении модуля и его настроек. Отключение SQUID/переход на Companions отключает Dungeon Clear; обратное включение SQUID не включает Dungeon Clear автоматически.
|
||||||
|
- Проверить сохранение после перезапуска, ручные конфиги и отказ включения через API в обход UI. Серверный guard обязателен независимо от Manager.
|
||||||
|
- Все новые UI-тексты — на шести языках. После реализации добавить changelog fragments в соответствующие компоненты; пока это запланированная, не выпущенная возможность.
|
||||||
|
- [ ] **Внедрение модуля гильдхаусов (`mod-guildhouse`)**:
|
||||||
|
- **Репозиторий:** `https://github.com/azerothcore/mod-guildhouse`
|
||||||
|
- **Пайплайн сборки (`coa-server-build`):**
|
||||||
|
- Добавить checkout модуля в `.github/workflows/server-binaries.yml`, `build.yml` и `build-linux.yml` в директорию `modules/mod-guildhouse`.
|
||||||
|
- Добавить лицензию модуля и копирование в `scripts/assemble-tree.ps1` (`Licenses/` и `NOTICE.txt`).
|
||||||
|
- **Адаптация под Conquest of Azeroth (CoA):**
|
||||||
|
- В диалоге дворецкого (`mod_guildhouse_butler.cpp`) вместо 10 классических тренеров WotLK спавнить **Book of Ascension** (entry `499992`), которая открывает интерфейс `mod-spellbook` и заменяет всех тренеров для кастомных классов и прогрессии способностей.
|
||||||
|
- Оставить без изменений: профессии, порталы в столицы, банк, аукционы (включая нейтральный), почту, вендоров, парикмахера, горн и наковальню.
|
||||||
|
- **База данных:**
|
||||||
|
- Миграции модуля (`guild_house`, `guild_house_spawns`, `creature_template`, `gameobject_template`, `mod_guildhouse_locale`) подхватываются `coa-release` автоматически при валидации схемы контракта.
|
||||||
|
- **В игре:**
|
||||||
|
- Разместить NPC-продавца гильдхаусов (`.npc add 500030`) в ключевых хабах / столицах (Штормград, Оргриммар, Даларан).
|
||||||
|
|
||||||
+7247
File diff suppressed because it is too large.
Load diff
@@ -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: 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: Install the compiler for modules from the Manager
|
||||||
|
---
|
||||||
|
When the compiler modules need is missing or does not match the core, the Toolchain tab offers to install Visual Studio Build Tools with MSVC 14.44. The Manager checks Microsoft's signature on the installer and opens it with the needed parts selected.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: Modules are rebuilt automatically after a core update
|
||||||
|
---
|
||||||
|
After a core update, every enabled module is rebuilt for the new core before the first start, or an existing build is reused. A module that cannot be rebuilt is switched off with the reason shown. Rolling back the core restores the earlier builds.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: The Modules Preview follows its own signed update channel
|
||||||
|
---
|
||||||
|
The Modules Preview Manager gets server updates from a separate preview channel, signed with a key of its own, and falls back to the stable channel until the first preview release exists. A stable Manager never accepts preview packages.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: Moving to a core with modules installs the modules you used
|
||||||
|
---
|
||||||
|
On a core that loads Content Scaling, Companions or SQUID's Playerbots as modules, the Manager installs them at the versions the core names before the first start. Bots follow what the server used: SQUID if it was on, else Companions. Removed modules stay removed.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: Dungeon Clear is shown and switched as part of SQUID's Playerbots
|
||||||
|
---
|
||||||
|
Dungeon Clear no longer has a card of its own, which said "Always on" while SQUID was off. It goes on
|
||||||
|
and off together with SQUID's Playerbots, and its settings open from the SQUID card.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: Modules Preview installs a bare modular core and copies classic servers
|
||||||
|
---
|
||||||
|
A new server gets the modular core and compiles no module; add modules later on the Modules page. An existing classic server is not converted: a modular server is installed next to it with its accounts, characters, world, bots and module settings copied. The old server keeps working.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: 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: admins
|
||||||
|
title: Bot strength settings for CoA Companions
|
||||||
|
---
|
||||||
|
A Bot Strength section in the bot settings: turn bot help on or off, choose where it applies (dungeons, raids, PvP, open world) and set bot damage, healing, damage taken and tank threat. All multipliers start at 1, so nothing changes until you raise them.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: The Manager starts and stops servers without Python
|
||||||
|
---
|
||||||
|
Start, stop and forced stop run inside the Manager, and errors name their cause (a busy port, missing files, a startup failure). Servers that include Scripts/coa-launcher.exe also run the world supervisor and bug-report relay without Python.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Server Migration shows the real server and makes a real modular copy
|
||||||
|
---
|
||||||
|
The page read nothing and reported a transfer that did not happen. It now shows the server's version, database state and counts, then makes the same modular copy as "Manage another server". World settings from Server Configuration now go along with the copy.
|
||||||
@@ -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: The game cache 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: 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.
|
||||||
+166
-1
@@ -149,8 +149,36 @@
|
|||||||
"Corfirean/coa-server-manager:20261027-skill-gain-controls.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-checks-the-realm-class-setting.md",
|
||||||
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.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-existing-character-update-validation.md",
|
||||||
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.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": [
|
"releases": [
|
||||||
{
|
{
|
||||||
@@ -771,6 +799,143 @@
|
|||||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
|
"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",
|
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
|
||||||
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
|
"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
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
socket2 = "0.6"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
@@ -37,7 +38,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
|
|||||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
|
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
testkit = []
|
testkit = []
|
||||||
@@ -0,0 +1,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,7 @@
|
|||||||
|
//! Analyze a module by its GitHub link, as "Add from a link" does. usage: analyze_url <url> <cache dir>
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let r = coa_core::analyzer::analyze_github_repository(&a[0], Some(std::path::Path::new(&a[1]))).expect("analysis");
|
||||||
|
println!("{} @ {} cache_hit={:?}", r.repository_name, r.commit, r.cache_hit);
|
||||||
|
println!("classification {:?}; hooks {}; sql {}; cmake {}", r.classification, r.hooks.len(), r.sql_files.len(), r.has_cmakelists);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
//! Real MSVC + CMake + Ninja: after the build cache is packed and unpacked, a rebuild with nothing changed
|
||||||
|
//! compiles nothing, and a rebuild after one source changed compiles only that source.
|
||||||
|
//! usage: build_cache_ninja_check <empty folder>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn build(root: &Path, dir: &Path, tc: &coa_core::build_engine::ToolchainStatus) -> String {
|
||||||
|
let bat = root.join("run.bat");
|
||||||
|
let ninja = Path::new(tc.ninja_path.as_ref().unwrap()).parent().unwrap().display().to_string();
|
||||||
|
std::fs::write(&bat, format!(
|
||||||
|
"@echo off\r\ncall \"{}\" > nul 2>&1\r\nset \"PATH={};%PATH%\"\r\n\"{}\" -G Ninja -S \"{}\" -B \"{}\\build\" -DCMAKE_BUILD_TYPE=RelWithDebInfo > nul\r\n\"{}\" --build \"{}\\build\" -- -d explain\r\n",
|
||||||
|
tc.vcvars64_path.as_ref().unwrap(), ninja, tc.cmake_path.as_ref().unwrap(), dir.display(), dir.display(), tc.cmake_path.as_ref().unwrap(), dir.display()
|
||||||
|
)).unwrap();
|
||||||
|
let out = Command::new("cmd.exe").args(["/c", &bat.to_string_lossy()]).output().unwrap();
|
||||||
|
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compiled(log: &str) -> usize {
|
||||||
|
log.lines().filter(|l| l.contains("Building CXX object")).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("usage: build_cache_ninja_check <empty folder>"));
|
||||||
|
assert!(!root.exists() || std::fs::read_dir(&root).unwrap().next().is_none(), "folder must be new or empty");
|
||||||
|
std::fs::create_dir_all(root.join(".manager")).unwrap();
|
||||||
|
let tc = coa_core::build_engine::detect_toolchain();
|
||||||
|
assert!(tc.msvc_available && tc.cmake_available && tc.ninja_available, "toolchain: {tc:?}");
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
std::fs::write(dir.join("CMakeLists.txt"), "cmake_minimum_required(VERSION 3.22)\nproject(p CXX)\nadd_library(p SHARED a.cpp b.cpp c.cpp)\n").unwrap();
|
||||||
|
for f in ["a", "b", "c"] {
|
||||||
|
std::fs::write(dir.join(format!("{f}.cpp")), format!("#include <vector>\n#include <string>\n__declspec(dllexport) int {f}() {{ return (int)std::vector<std::string>(3).size(); }}\n")).unwrap();
|
||||||
|
}
|
||||||
|
let first = build(&root, &dir, &tc);
|
||||||
|
println!("first build compiled {}", compiled(&first));
|
||||||
|
assert_eq!(compiled(&first), 3);
|
||||||
|
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
let s = coa_core::build_cache::summary(&root, None);
|
||||||
|
println!("packed: {} bytes from {} unpacked", s.total_bytes, s.modules[0].unpacked_bytes);
|
||||||
|
assert!(!dir.exists());
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
let again = build(&root, &dir, &tc);
|
||||||
|
println!("after unpack, nothing changed: compiled {}\n{}", compiled(&again), again.lines().filter(|l| l.contains("explain")).take(8).collect::<Vec<_>>().join("\n"));
|
||||||
|
assert_eq!(compiled(&again), 0, "nothing should be recompiled");
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||||
|
std::fs::write(dir.join("b.cpp"), "__declspec(dllexport) int b() { return 2; }\n").unwrap();
|
||||||
|
let one = build(&root, &dir, &tc);
|
||||||
|
println!("after one change: compiled {}", compiled(&one));
|
||||||
|
assert_eq!(compiled(&one), 1);
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
println!("PASS");
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
//! Build the AzerothCore catalogue's modules against a plugin-host realm's SDK and record, per module, the
|
||||||
|
//! evidence: commit, analysis, build result, compiler errors and the core functions the host does not export.
|
||||||
|
//! A rerun skips modules that already have a result; `summary` aggregates the results.
|
||||||
|
//!
|
||||||
|
//! usage: catalog_build_sweep run <realm> <work dir> <how many, by stars>
|
||||||
|
//! catalog_build_sweep summary <work dir>
|
||||||
|
//! The realm needs only Core/worldserver.exe (a plugin host) and its .manager/sdk; use a disposable copy.
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
|
struct Outcome {
|
||||||
|
slug: String,
|
||||||
|
stars: u32,
|
||||||
|
category: String,
|
||||||
|
pushed_at: Option<String>,
|
||||||
|
commit: Option<String>,
|
||||||
|
/// "built" | "link-missing-exports" | "compile-error" | "not-a-plugin" | "analysis-failed" | "build-error"
|
||||||
|
result: String,
|
||||||
|
detail: Option<String>,
|
||||||
|
classification: Option<String>,
|
||||||
|
seconds: f64,
|
||||||
|
/// Core functions the plugin needs that worldserver.exe does not export (MSVC decorated names).
|
||||||
|
missing_exports: Vec<String>,
|
||||||
|
/// Demangled form of each missing export, for reading.
|
||||||
|
missing_readable: Vec<String>,
|
||||||
|
compile_errors: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_name(slug: &str) -> String {
|
||||||
|
slug.replace('/', "__")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decorated name and its readable form out of an LNK2019/LNK2001 message.
|
||||||
|
fn missing_symbol(message: &str) -> Option<(String, String)> {
|
||||||
|
let readable = message.split('"').nth(1).unwrap_or("").to_string();
|
||||||
|
let start = message.find("(?")?;
|
||||||
|
let end = message[start..].find(')')? + start;
|
||||||
|
Some((message[start + 1..end].to_string(), readable))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(realm: &Path, work: &Path, count: usize) {
|
||||||
|
let results = work.join("results");
|
||||||
|
std::fs::create_dir_all(&results).unwrap();
|
||||||
|
let sources = work.join("sources");
|
||||||
|
let catalogue = coa_core::catalogue::fetch_or_load_catalogue(&work.join("catalogue"), false).expect("catalogue");
|
||||||
|
let mut items: Vec<_> = catalogue
|
||||||
|
.items
|
||||||
|
.into_iter()
|
||||||
|
.filter(|i| !matches!(i.coa_status, coa_core::catalogue::CoaCompatibilityStatus::Incompatible | coa_core::catalogue::CoaCompatibilityStatus::Blocked))
|
||||||
|
.collect();
|
||||||
|
items.sort_by(|a, b| b.stars.cmp(&a.stars));
|
||||||
|
let tc = coa_core::build_engine::detect_toolchain_for(Some(realm));
|
||||||
|
assert!(tc.msvc_available && tc.cmake_available && tc.ninja_available && tc.sdk_dir.is_some(), "toolchain/SDK for the realm: {tc:?}");
|
||||||
|
|
||||||
|
for (n, item) in items.iter().take(count).enumerate() {
|
||||||
|
let out = results.join(format!("{}.json", file_name(&item.full_name)));
|
||||||
|
if out.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let mut o = Outcome {
|
||||||
|
slug: item.full_name.clone(),
|
||||||
|
stars: item.stars,
|
||||||
|
category: item.category.clone(),
|
||||||
|
pushed_at: item.pushed_at.clone(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
println!("[{}/{}] {} ★{}", n + 1, count.min(items.len()), item.full_name, item.stars);
|
||||||
|
match coa_core::analyzer::analyze_github_repository(&item.html_url, Some(&sources)) {
|
||||||
|
Err(e) => {
|
||||||
|
o.result = "analysis-failed".into();
|
||||||
|
o.detail = Some(e.to_string());
|
||||||
|
}
|
||||||
|
Ok(report) => {
|
||||||
|
o.commit = Some(report.commit.clone());
|
||||||
|
o.classification = Some(format!("{:?}", report.classification));
|
||||||
|
let path = PathBuf::from(&report.repository_path);
|
||||||
|
let path = if path.is_dir() { path } else {
|
||||||
|
sources.join("github").join(&item.owner).join(&item.name).join(&report.commit)
|
||||||
|
};
|
||||||
|
match coa_core::build_engine::build_module_with_bundle(&path, &[], realm, None, None) {
|
||||||
|
Err(e) => {
|
||||||
|
let text = e.to_string();
|
||||||
|
o.result = if text.contains("NO_LOADER_FOUND") || text.contains("No C++") || text.contains("MANUAL_ADAPTER") {
|
||||||
|
"not-a-plugin".into()
|
||||||
|
} else {
|
||||||
|
"build-error".into()
|
||||||
|
};
|
||||||
|
o.detail = Some(text);
|
||||||
|
}
|
||||||
|
Ok(b) if b.success => o.result = "built".into(),
|
||||||
|
Ok(b) => {
|
||||||
|
for e in &b.errors {
|
||||||
|
if e.error_code == "LNK2019" || e.error_code == "LNK2001" {
|
||||||
|
if let Some((mangled, readable)) = missing_symbol(&e.message) {
|
||||||
|
if !o.missing_exports.contains(&mangled) {
|
||||||
|
o.missing_exports.push(mangled);
|
||||||
|
o.missing_readable.push(readable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !e.error_code.starts_with("LNK") {
|
||||||
|
o.compile_errors.push(format!("{} {}:{} {}", e.error_code, e.file.rsplit(['/', '\\']).next().unwrap_or(""), e.line, e.message.lines().next().unwrap_or("")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.result = if o.compile_errors.is_empty() && !o.missing_exports.is_empty() {
|
||||||
|
"link-missing-exports".into()
|
||||||
|
} else {
|
||||||
|
"compile-error".into()
|
||||||
|
};
|
||||||
|
o.compile_errors.truncate(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.seconds = started.elapsed().as_secs_f64();
|
||||||
|
println!(" -> {} ({:.0}s){}", o.result, o.seconds, if o.missing_exports.is_empty() { String::new() } else { format!(", {} missing exports", o.missing_exports.len()) });
|
||||||
|
std::fs::write(&out, serde_json::to_vec_pretty(&o).unwrap()).unwrap();
|
||||||
|
// source downloads of finished modules are not needed again
|
||||||
|
let _ = std::fs::remove_dir_all(sources.join("github").join(&item.owner).join(&item.name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn summary(work: &Path) {
|
||||||
|
let mut all: Vec<Outcome> = std::fs::read_dir(work.join("results")).unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|e| serde_json::from_slice(&std::fs::read(e.path()).ok()?).ok())
|
||||||
|
.collect();
|
||||||
|
all.sort_by(|a, b| b.stars.cmp(&a.stars));
|
||||||
|
let mut by_result: BTreeMap<&str, usize> = BTreeMap::new();
|
||||||
|
for o in &all {
|
||||||
|
*by_result.entry(o.result.as_str()).or_default() += 1;
|
||||||
|
}
|
||||||
|
let mut symbols: BTreeMap<String, (String, Vec<String>)> = BTreeMap::new();
|
||||||
|
for o in all.iter().filter(|o| o.result == "link-missing-exports") {
|
||||||
|
for (m, r) in o.missing_exports.iter().zip(&o.missing_readable) {
|
||||||
|
symbols.entry(m.clone()).or_insert_with(|| (r.clone(), Vec::new())).1.push(o.slug.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut lines = vec![format!("modules: {}", all.len())];
|
||||||
|
for (r, n) in &by_result {
|
||||||
|
lines.push(format!(" {r}: {n}"));
|
||||||
|
}
|
||||||
|
lines.push(format!("distinct missing exports (modules that only lack exports): {}", symbols.len()));
|
||||||
|
let mut sym: Vec<_> = symbols.iter().collect();
|
||||||
|
sym.sort_by(|a, b| b.1 .1.len().cmp(&a.1 .1.len()));
|
||||||
|
for (_, (readable, mods)) in sym.iter().take(40) {
|
||||||
|
lines.push(format!(" {:>3} {}", mods.len(), readable));
|
||||||
|
}
|
||||||
|
// why modules do not compile: a header they need is not there (a dependency: playerbots, a library), or
|
||||||
|
// the core's API differs from the one they were written for
|
||||||
|
let mut kinds: BTreeMap<String, usize> = BTreeMap::new();
|
||||||
|
for o in all.iter().filter(|o| o.result == "compile-error") {
|
||||||
|
let header = o.compile_errors.iter().find(|e| e.starts_with("C1083")).and_then(|e| {
|
||||||
|
let start = e.find(": ")? + 2;
|
||||||
|
Some(e[start..].split(':').next()?.trim().to_string())
|
||||||
|
});
|
||||||
|
let kind = match header {
|
||||||
|
Some(h) => format!("missing header {h}"),
|
||||||
|
None => format!("core API differs ({})", o.compile_errors.first().map(|e| e.split(' ').next().unwrap_or("")).unwrap_or("")),
|
||||||
|
};
|
||||||
|
*kinds.entry(kind).or_default() += 1;
|
||||||
|
}
|
||||||
|
lines.push(String::new());
|
||||||
|
lines.push("compile errors by cause:".into());
|
||||||
|
let mut k: Vec<_> = kinds.into_iter().collect();
|
||||||
|
k.sort_by(|a, b| b.1.cmp(&a.1));
|
||||||
|
for (kind, n) in k.iter().take(25) {
|
||||||
|
lines.push(format!(" {n:>3} {kind}"));
|
||||||
|
}
|
||||||
|
lines.push(String::new());
|
||||||
|
for o in &all {
|
||||||
|
lines.push(format!("{:<22} ★{:<5} {:<48} {}", o.result, o.stars, o.slug,
|
||||||
|
if o.result == "link-missing-exports" { format!("{} exports", o.missing_exports.len()) }
|
||||||
|
else { o.detail.clone().or_else(|| o.compile_errors.first().cloned()).unwrap_or_default().chars().take(110).collect() }));
|
||||||
|
}
|
||||||
|
let text = lines.join("\n");
|
||||||
|
println!("{text}");
|
||||||
|
std::fs::write(work.join("summary.txt"), &text).unwrap();
|
||||||
|
// the exports a core build would add, one decorated name per line
|
||||||
|
let def: Vec<&String> = symbols.keys().collect();
|
||||||
|
std::fs::write(work.join("missing-exports.txt"), def.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("\n")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
match a.first().map(String::as_str) {
|
||||||
|
Some("run") => run(Path::new(&a[1]), Path::new(&a[2]), a[3].parse().unwrap()),
|
||||||
|
Some("summary") => summary(Path::new(&a[1])),
|
||||||
|
_ => eprintln!("usage: catalog_build_sweep run <realm> <work> <count> | summary <work>"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//! How the module categories fall on a real catalogue: counts per category and a few modules of each.
|
||||||
|
//! usage: catalogue_categories <catalogue.json downloaded from azerothcore.org>
|
||||||
|
fn main() {
|
||||||
|
let path = std::env::args().nth(1).expect("usage: catalogue_categories <catalogue.json>");
|
||||||
|
let raw: coa_core::catalogue::OfficialCatalogueRaw =
|
||||||
|
serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
|
||||||
|
let overlay = coa_core::catalogue::load_coa_overlay(None);
|
||||||
|
let items = coa_core::catalogue::normalize_catalogue(&raw, &overlay);
|
||||||
|
let mut by: std::collections::BTreeMap<String, Vec<(u32, String, String)>> = Default::default();
|
||||||
|
for i in &items {
|
||||||
|
let c = coa_core::catalogue::categorize(&i.full_name, &i.name, &i.description, &i.topics);
|
||||||
|
by.entry(c).or_default().push((i.stars, i.full_name.clone(), i.description.chars().take(70).collect()));
|
||||||
|
}
|
||||||
|
println!("modules: {}", items.len());
|
||||||
|
for c in coa_core::catalogue::categories() {
|
||||||
|
let mut list = by.remove(&c.code).unwrap_or_default();
|
||||||
|
list.sort_by(|a, b| b.0.cmp(&a.0));
|
||||||
|
println!("\n== {} ({}) {}", c.code, c.ru, list.len());
|
||||||
|
for (s, n, d) in list.iter().take(6) {
|
||||||
|
println!(" {s:>5} {n:<45} {d}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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,197 @@
|
|||||||
|
//! 0.9.10 install paths of the Modules Preview, end to end on DISPOSABLE servers under <work>:
|
||||||
|
//!
|
||||||
|
//! 1. fresh: a new server goes on to the preview core with the bare core (no module is compiled).
|
||||||
|
//! 2. copy: a classic server (stopped) gets a modular copy next to it: accounts, characters, the world and
|
||||||
|
//! module settings arrive, the old server's files are byte-for-byte unchanged, the copy takes the
|
||||||
|
//! preview core with the modules the old server had switched on.
|
||||||
|
//! 3. copy-running: the same copy step from a classic server whose database is running.
|
||||||
|
//!
|
||||||
|
//! usage: preview_bare_and_copy_e2e <empty work folder> [fresh|copy|all]
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use coa_core::install::{install_base, Params, Source};
|
||||||
|
use coa_core::registry::Registry;
|
||||||
|
use coa_core::update::{self, RepackEnv};
|
||||||
|
|
||||||
|
const KEY: &str = coa_core::signing::EMBEDDED_PUBLIC_KEY;
|
||||||
|
type R<T> = Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
coa_core::backup::with_database(root, |db| db.query(q)).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install(root: &Path, reg: &Registry) -> R<()> {
|
||||||
|
let image = coa_core::channels::stable_source()?;
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let done = install_base(
|
||||||
|
&Params { source: Source::Installation(Box::new(image)), dest: root.into(), trusted_key: KEY, registry: reg, cancel: Default::default() },
|
||||||
|
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
|
||||||
|
)?;
|
||||||
|
println!("[{}] installed {} in {:?}", root.display(), done.version, t.elapsed());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_free_ports(root: &Path) -> R<()> {
|
||||||
|
let repack = root.join("Settings/repack.json");
|
||||||
|
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack)?)?;
|
||||||
|
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
|
||||||
|
cfg[k] = free_port().into();
|
||||||
|
}
|
||||||
|
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg)?)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same steps as the Manager's install_preview_core.
|
||||||
|
fn preview_core(root: &Path) -> R<update::Outcome> {
|
||||||
|
let meta_dir = coa_core::registry::metadata_dir_for(root)?;
|
||||||
|
let (_, meta) = coa_core::registry::MetaDir::open(&meta_dir)?;
|
||||||
|
let source = coa_core::update_route::select(&meta, coa_core::channels::preview_update_source()?, KEY)?.source;
|
||||||
|
let env = RepackEnv { root, meta_dir: &meta_dir };
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let out = coa_core::install::with_scratch_ports(root, || update::apply(
|
||||||
|
&update::Params { root, meta_dir: &meta_dir, source, trusted_key: KEY, cancel: Default::default(), resolutions: Default::default(), env: &env, fail_after_ops: None },
|
||||||
|
&|phase, percent| println!(" {percent}% {phase}"),
|
||||||
|
));
|
||||||
|
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||||
|
let out = out?;
|
||||||
|
println!("[{}] preview core: {:?} in {:?}; modules {:?}", root.display(), out.txn.state, t.elapsed(), out.modules);
|
||||||
|
assert_eq!(out.txn.state, update::State::Committed);
|
||||||
|
assert!(coa_core::provenance::realm_host_fingerprint(root).is_some(), "the plugin host is installed");
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sha256 of every file under the old server, except the launcher's own run state.
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, String> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, String>) {
|
||||||
|
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p.strip_prefix(base).unwrap().to_string_lossy().replace('\\', "/");
|
||||||
|
out.insert(rel, coa_core::fsx::sha256_file(&p).unwrap_or_else(|e| format!("unreadable: {e}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fresh(work: &Path, reg: &Registry) -> R<()> {
|
||||||
|
let root = work.join("fresh-fixture");
|
||||||
|
install(&root, reg)?; // shipped ports, as in the Manager: another server may be running on them
|
||||||
|
coa_core::rebuild::decline_recommended(&root)?;
|
||||||
|
let out = preview_core(&root)?;
|
||||||
|
assert!(out.modules.is_empty(), "a new server compiles nothing: {:?}", out.modules);
|
||||||
|
let registry = coa_core::plugins::load_registry(&root)?;
|
||||||
|
assert!(registry.plugins.values().all(|e| !e.installed), "no plugin installed: {:?}", registry.plugins.keys());
|
||||||
|
let boot: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("Core/plugins/plugin-boot-report.json"))?)?;
|
||||||
|
println!("boot report: {boot}");
|
||||||
|
assert_eq!(boot["anyFaulted"], serde_json::json!(false));
|
||||||
|
println!("FRESH PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||||
|
// A classic server with data of its own.
|
||||||
|
let old = work.join("classic-fixture");
|
||||||
|
install(&old, reg)?;
|
||||||
|
set_free_ports(&old)?; // the test runs this "old" server; it must not meet a real one on the shipped ports
|
||||||
|
sql(&old, "INSERT INTO acore_auth.account (username, salt, verifier, email, reg_mail) \
|
||||||
|
VALUES ('E2ECOPY', UNHEX(REPEAT('11',32)), UNHEX(REPEAT('22',32)), '', '')");
|
||||||
|
let account = sql(&old, "SELECT id FROM acore_auth.account WHERE username='E2ECOPY'").trim().to_string();
|
||||||
|
sql(&old, &format!("SET SESSION sql_mode=''; INSERT INTO acore_characters.characters (guid, account, name, race, class, gender, level, money) \
|
||||||
|
VALUES (900001, {account}, 'Copytest', 1, 1, 0, 42, 123456)"));
|
||||||
|
let conf = old.join("Core/configs/modules/mod-coa-content-scaling.conf");
|
||||||
|
let conf_text = std::fs::read_to_string(&conf).unwrap_or_default() + "\n# e2e owner edit\n";
|
||||||
|
std::fs::write(&conf, &conf_text)?;
|
||||||
|
let fingerprint = |root: &Path| sql(root, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters),'|',\
|
||||||
|
(SELECT CONCAT(name,':',level,':',money) FROM acore_characters.characters WHERE guid=900001))").trim().to_string();
|
||||||
|
let expected = fingerprint(&old);
|
||||||
|
let counts = sql(&old, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters))").trim().to_string();
|
||||||
|
// A world setting changed on the Server Configuration page lives in the old server's template.
|
||||||
|
let old_meta = coa_core::registry::metadata_dir_for(&old)?;
|
||||||
|
let rate = BTreeMap::from([("Rate.XP.Kill".to_string(), "3".to_string())]);
|
||||||
|
assert_eq!(coa_core::allsettings::save(&old, &old_meta, &rate)?, ["Rate.XP.Kill"]);
|
||||||
|
let _ = coa_core::driver::run(&old, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("old server data: {expected}");
|
||||||
|
assert!(coa_core::modular_copy::is_classic(&old));
|
||||||
|
let before_preview = tree(&old);
|
||||||
|
let p = coa_core::modular_copy::preview(&old)?;
|
||||||
|
println!("preview (stopped): {p:?}");
|
||||||
|
assert!(p.classic && !p.modular && p.database == "stopped" && p.accounts.is_none());
|
||||||
|
assert!(p.database_bytes > 0 && p.config_files.iter().any(|f| f.ends_with("mod-coa-content-scaling.conf")));
|
||||||
|
assert_eq!(tree(&old), before_preview, "the preview changed the old server's files");
|
||||||
|
|
||||||
|
// 2. copy of the stopped server, then the preview core on the copy.
|
||||||
|
let before = tree(&old);
|
||||||
|
let new = work.join("copy-fixture");
|
||||||
|
install(&new, reg)?;
|
||||||
|
let report = coa_core::modular_copy::copy_data(&old, &new, &|w| println!(" copy: {w}"))?;
|
||||||
|
println!("copy report: {report:?}");
|
||||||
|
assert_eq!(report.read_from, "copy of the stopped database");
|
||||||
|
assert_eq!(tree(&old), before, "the old server's files changed");
|
||||||
|
let observed = coa_core::process::observe(&new, &coa_core::layout::read_ports(&new));
|
||||||
|
assert_eq!(observed.mysql.state, coa_core::process::ServiceState::Stopped, "a database of the copy is still running: {:?}", observed.mysql);
|
||||||
|
assert!(!coa_core::registry::metadata_dir_for(&new)?.join("import").exists(), "the private copy of the old data is removed");
|
||||||
|
assert_eq!(std::fs::read_to_string(new.join("Core/configs/modules/mod-coa-content-scaling.conf"))?, conf_text);
|
||||||
|
assert_eq!(report.world_settings, ["Rate.XP.Kill"], "skipped: {:?}", report.world_settings_skipped);
|
||||||
|
let world_value = |root: &Path| coa_core::allsettings::list(root).unwrap().into_iter().find(|i| i.key == "Rate.XP.Kill").map(|i| i.value);
|
||||||
|
assert_eq!(world_value(&new).as_deref(), Some("3"));
|
||||||
|
let out = preview_core(&new)?;
|
||||||
|
println!("modules on the copy: {:?}", out.modules);
|
||||||
|
let got = fingerprint(&new);
|
||||||
|
let _ = coa_core::driver::run(&new, coa_core::driver::Verb::StopAll);
|
||||||
|
assert_eq!(got, expected, "data of the copy after the preview core");
|
||||||
|
assert_eq!(tree(&old), before, "the old server's files changed");
|
||||||
|
println!("COPY (stopped) PASS");
|
||||||
|
|
||||||
|
// 3. copy while the old database runs: read from it, change nothing.
|
||||||
|
let started = coa_core::driver::run(&old, coa_core::driver::Verb::StartMysql)?;
|
||||||
|
assert!(started.ok, "{}", started.output);
|
||||||
|
let data_before: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||||
|
let rows_before = fingerprint(&old);
|
||||||
|
let p = coa_core::modular_copy::preview(&old)?;
|
||||||
|
println!("preview (running): accounts {:?} characters {:?} schemas {:?}", p.accounts, p.characters, p.schemas);
|
||||||
|
assert_eq!(p.database, "running");
|
||||||
|
assert_eq!(format!("{}|{}", p.accounts.unwrap(), p.characters.unwrap()), counts);
|
||||||
|
assert!(p.schemas.iter().any(|s| s == "acore_characters"));
|
||||||
|
let new2 = work.join("copy-running-fixture");
|
||||||
|
install(&new2, reg)?;
|
||||||
|
let report = coa_core::modular_copy::copy_data(&old, &new2, &|w| println!(" copy: {w}"));
|
||||||
|
let rows_after = fingerprint(&old);
|
||||||
|
let _ = coa_core::driver::run(&old, coa_core::driver::Verb::StopAll);
|
||||||
|
let report = report?;
|
||||||
|
assert_eq!(report.read_from, "running database");
|
||||||
|
assert_eq!(rows_after, rows_before);
|
||||||
|
let data_after: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||||
|
assert_eq!(data_after, data_before, "files outside the database changed");
|
||||||
|
assert_eq!(fingerprint(&new2), expected);
|
||||||
|
assert_eq!(world_value(&new2).as_deref(), Some("3"));
|
||||||
|
let _ = coa_core::driver::run(&new2, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("COPY (running) PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> R<()> {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let work = PathBuf::from(a.first().expect("usage: preview_bare_and_copy_e2e <empty work folder> [fresh|copy|all]"));
|
||||||
|
let mode = a.get(1).map(String::as_str).unwrap_or("all");
|
||||||
|
assert!(!work.exists() || std::fs::read_dir(&work)?.next().is_none(), "work folder must be new or empty");
|
||||||
|
std::fs::create_dir_all(&work)?;
|
||||||
|
let reg = Registry::at(work.join("installs.json"));
|
||||||
|
if mode == "fresh" || mode == "all" {
|
||||||
|
fresh(&work, ®)?;
|
||||||
|
}
|
||||||
|
if mode == "copy" || mode == "all" {
|
||||||
|
copy(&work, ®)?;
|
||||||
|
}
|
||||||
|
println!("ALL PASS ({mode})");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
//! The published Modules Preview channel, end to end on a DISPOSABLE server, through the same source selection
|
||||||
|
//! the Manager uses when the owner does not choose a package: install from the stable channel's installation
|
||||||
|
//! image, check for updates (the preview channel), apply the preview update (modules are built on this PC and
|
||||||
|
//! the plugin host starts with them), then check again: the server must now be current.
|
||||||
|
//!
|
||||||
|
//! usage: preview_channel_e2e <new folder ending in -fixture>
|
||||||
|
//! The server gets its own free ports before anything starts; it never uses another server's database.
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use coa_core::install::{install_base, Params, Source};
|
||||||
|
use coa_core::registry::{MetaDir, Registry};
|
||||||
|
use coa_core::update::{self, DatabaseAccess, Env, RepackEnv};
|
||||||
|
|
||||||
|
const KEY: &str = coa_core::signing::EMBEDDED_PUBLIC_KEY;
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
coa_core::backup::with_database(root, |db| db.query(q)).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Manager's "up to date" rule (src/lib/serverUpdateStatus.ts).
|
||||||
|
fn is_current(p: &update::Preview) -> bool {
|
||||||
|
p.from_version.as_deref() == Some(p.to_version.as_str())
|
||||||
|
&& p.items.iter().all(|i| format!("{:?}", i.action).eq_ignore_ascii_case("skip"))
|
||||||
|
&& (p.database_check_error.is_some() || !p.database_checked || p.pending_migrations == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(root: &Path, meta_dir: &Path) -> Result<(Source, update::Preview), Box<dyn std::error::Error>> {
|
||||||
|
let (_, meta) = MetaDir::open(meta_dir)?;
|
||||||
|
let selection = coa_core::update_route::select(&meta, coa_core::channels::preview_update_source()?, KEY)?;
|
||||||
|
let preview = update::preview_with(root, &meta, &selection.source, KEY, &Default::default(), DatabaseAccess::Start)?;
|
||||||
|
Ok((selection.source, preview))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
assert_eq!(a.len(), 1, "usage: preview_channel_e2e <new-folder-fixture>");
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
assert!(a[0].ends_with("-fixture") && !root.exists(), "a new folder ending in -fixture is required");
|
||||||
|
let reg_dir = std::env::temp_dir().join("coa-preview-channel-e2e-registry");
|
||||||
|
let _ = std::fs::remove_dir_all(®_dir);
|
||||||
|
let reg = Registry::at(reg_dir.join("installs.json"));
|
||||||
|
|
||||||
|
// 1. New server: the Manager installs the stable channel's image (the preview publishes updates only).
|
||||||
|
let image = coa_core::channels::stable_source()?;
|
||||||
|
println!("installation image: {image:?}");
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let installed = install_base(
|
||||||
|
&Params { source: Source::Installation(Box::new(image)), dest: root.into(), trusted_key: KEY, registry: ®, cancel: Default::default() },
|
||||||
|
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
|
||||||
|
)?;
|
||||||
|
println!("installed {} in {:?}", installed.version, t.elapsed());
|
||||||
|
|
||||||
|
let repack = root.join("Settings/repack.json");
|
||||||
|
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack)?)?;
|
||||||
|
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
|
||||||
|
cfg[k] = free_port().into();
|
||||||
|
}
|
||||||
|
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg)?)?;
|
||||||
|
sql(root, "INSERT INTO acore_auth.account (username, salt, verifier, email, reg_mail) \
|
||||||
|
VALUES ('E2ECHANNEL', UNHEX(REPEAT('11',32)), UNHEX(REPEAT('22',32)), '', '')");
|
||||||
|
let accounts = sql(root, "SELECT COUNT(*) FROM acore_auth.account").trim().to_string();
|
||||||
|
|
||||||
|
// 2. Check for updates: the preview channel offers the preview.
|
||||||
|
let meta_dir = coa_core::registry::metadata_dir_for(root)?;
|
||||||
|
let (source, preview) = check(root, &meta_dir)?;
|
||||||
|
println!("check: {:?} -> {} from {source:?}, {} items, {} migrations", preview.from_version, preview.to_version, preview.items.len(), preview.migrations);
|
||||||
|
assert!(!is_current(&preview), "a fresh stable server must be offered the preview");
|
||||||
|
|
||||||
|
// 3. Apply it, exactly as the Update button does.
|
||||||
|
let env = RepackEnv { root, meta_dir: &meta_dir };
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let outcome = update::apply(
|
||||||
|
&update::Params { root, meta_dir: &meta_dir, source, trusted_key: KEY, cancel: Default::default(), resolutions: Default::default(), env: &env, fail_after_ops: None },
|
||||||
|
&|phase, percent| println!("{percent}% {phase}"),
|
||||||
|
);
|
||||||
|
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||||
|
let outcome = outcome?;
|
||||||
|
println!("update {:?} to {:?} in {:?}; modules {:?}", outcome.txn.state, outcome.txn.to_version, t.elapsed(), outcome.modules);
|
||||||
|
if let Ok(t) = std::fs::read_to_string(root.join("Core/plugins/plugin-boot-report.json")) {
|
||||||
|
println!("--- boot report\n{t}");
|
||||||
|
}
|
||||||
|
assert_eq!(outcome.txn.state, update::State::Committed);
|
||||||
|
|
||||||
|
// 4. Check again: nothing newer, nothing to change.
|
||||||
|
let (_, again) = check(root, &meta_dir)?;
|
||||||
|
let changing: Vec<_> = again.items.iter().filter(|i| !format!("{:?}", i.action).eq_ignore_ascii_case("skip")).map(|i| format!("{i:?}")).collect();
|
||||||
|
println!("second check: {:?} -> {}, pending migrations {}, changing items {changing:?}", again.from_version, again.to_version, again.pending_migrations);
|
||||||
|
assert_eq!(sql(root, "SELECT COUNT(*) FROM acore_auth.account").trim(), accounts, "accounts changed");
|
||||||
|
env.ensure_stopped()?;
|
||||||
|
assert!(is_current(&again), "the updated server is not reported as current");
|
||||||
|
println!("PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
//! A core update with a NEW plugin ABI on a DISPOSABLE preview server that already runs modules: the production
|
||||||
|
//! updater must rebuild every enabled module for the new core before the trial start. With `break <module>` that
|
||||||
|
//! module's sources are replaced (for this server only) by a copy that does not compile: the core update must
|
||||||
|
//! still commit, the module must be switched off with a reason, and the world must start without it.
|
||||||
|
//!
|
||||||
|
//! usage: preview_core_update_e2e <existing folder ending in -fixture> <preview package dir> [break <module id>] [same-core]
|
||||||
|
//! `same-core`: the package keeps the server's plugin ABI (a module the manager switched off is retried).
|
||||||
|
//! The shared source cache is never modified: the broken copy lives next to the fixture.
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use coa_core::install::Source;
|
||||||
|
use coa_core::update::{self, Env, RepackEnv};
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
coa_core::backup::with_database(root, |db| db.query(q)).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accounts and every character row, read the same way before and after.
|
||||||
|
fn data(root: &Path) -> String {
|
||||||
|
sql(root, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account), '|', COUNT(*), '|', \
|
||||||
|
COALESCE(SUM(CRC32(CONCAT_WS('|', guid, account, name, level, xp, money))), 0)) FROM acore_characters.characters")
|
||||||
|
.trim()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_fingerprint(root: &Path) -> Option<String> {
|
||||||
|
let t = std::fs::read_to_string(root.join("Core/plugins/plugin-boot-report.json")).ok()?;
|
||||||
|
let v: serde_json::Value = serde_json::from_str(&t).ok()?;
|
||||||
|
v["hostAbiFingerprint"].as_str().map(str::to_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
|
std::fs::create_dir_all(to)?;
|
||||||
|
for e in std::fs::read_dir(from)? {
|
||||||
|
let e = e?;
|
||||||
|
let dest = to.join(e.file_name());
|
||||||
|
if e.file_type()?.is_dir() {
|
||||||
|
copy_dir(&e.path(), &dest)?;
|
||||||
|
} else {
|
||||||
|
std::fs::copy(e.path(), dest)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_cpp(dir: &Path) -> Option<PathBuf> {
|
||||||
|
let mut entries: Vec<_> = std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).collect();
|
||||||
|
entries.sort();
|
||||||
|
entries.iter().find(|p| p.extension().is_some_and(|x| x == "cpp")).cloned()
|
||||||
|
.or_else(|| entries.iter().filter(|p| p.is_dir()).find_map(|p| first_cpp(p)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Points this server's build recipe for `id` at a copy of its sources with a compile error.
|
||||||
|
fn break_module(root: &Path, id: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let recipe_path = coa_core::plugins::meta_dir(root).join("build-recipes").join(format!("{id}.json"));
|
||||||
|
let mut recipe: serde_json::Value = serde_json::from_slice(&std::fs::read(&recipe_path)?)?;
|
||||||
|
let src = PathBuf::from(recipe["source_dir"].as_str().ok_or("recipe has no source_dir")?);
|
||||||
|
// Next to the fixture, never inside the shared cache. Same <repo>/<commit> tail as the cache, because the
|
||||||
|
// manager reads the module's identity from it: the build itself must be what fails.
|
||||||
|
let tail: PathBuf = src.components().rev().take(2).collect::<Vec<_>>().into_iter().rev().collect();
|
||||||
|
let broken = root.parent().unwrap().join("brk").join(tail);
|
||||||
|
if src == broken {
|
||||||
|
println!("{id} already builds from the broken copy {}", broken.display());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
copy_dir(&src, &broken)?; // a fresh copy over any earlier one
|
||||||
|
let cpp = ["src", "module/src"].iter().find_map(|d| first_cpp(&broken.join(d))).ok_or("no .cpp in the module sources")?;
|
||||||
|
let text = std::fs::read_to_string(&cpp)?;
|
||||||
|
std::fs::write(&cpp, format!("#error coa e2e: this module deliberately does not build\n{text}"))?;
|
||||||
|
println!("broke {id}: {} (recipe now -> {})", cpp.display(), broken.display());
|
||||||
|
recipe["source_dir"] = broken.to_string_lossy().into_owned().into();
|
||||||
|
std::fs::write(&recipe_path, serde_json::to_vec_pretty(&recipe)?)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let same_core = a.last().is_some_and(|x| x == "same-core");
|
||||||
|
let a: Vec<String> = if same_core { a[..a.len() - 1].to_vec() } else { a };
|
||||||
|
assert!(a.len() == 2 || (a.len() == 4 && a[2] == "break"), "usage: preview_core_update_e2e <fixture> <package dir> [break <id>] [same-core]");
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
assert!(a[0].ends_with("-fixture") && root.is_dir(), "an existing folder ending in -fixture is required");
|
||||||
|
let broken = a.get(3).cloned();
|
||||||
|
let meta_dir = coa_core::registry::metadata_dir_for(root)?;
|
||||||
|
let env = RepackEnv { root, meta_dir: &meta_dir };
|
||||||
|
env.ensure_stopped()?;
|
||||||
|
|
||||||
|
let fp_before = host_fingerprint(root);
|
||||||
|
let data_before = data(root);
|
||||||
|
let lock_before = std::fs::read_to_string(root.join("Core/plugins/plugins.lock")).unwrap_or_default();
|
||||||
|
println!("before: host {fp_before:?}, data {data_before}\n--- plugins.lock before\n{lock_before}");
|
||||||
|
if let Some(id) = &broken {
|
||||||
|
break_module(root, id)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let outcome = update::apply(
|
||||||
|
&update::Params {
|
||||||
|
root,
|
||||||
|
meta_dir: &meta_dir,
|
||||||
|
source: Source::Dir(a[1].clone().into()),
|
||||||
|
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
|
cancel: Default::default(),
|
||||||
|
resolutions: Default::default(),
|
||||||
|
env: &env,
|
||||||
|
fail_after_ops: None,
|
||||||
|
},
|
||||||
|
&|phase, percent| println!("{percent}% {phase}"),
|
||||||
|
);
|
||||||
|
let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("shutdown after update: {:?}", stopped.map(|r| r.ok));
|
||||||
|
let outcome = outcome?;
|
||||||
|
println!("update {:?} to {:?} in {:?}; modules {:#?}", outcome.txn.state, outcome.txn.to_version, t.elapsed(), outcome.modules);
|
||||||
|
|
||||||
|
let fp_after = host_fingerprint(root);
|
||||||
|
let data_after = data(root);
|
||||||
|
let lock_after = std::fs::read_to_string(root.join("Core/plugins/plugins.lock")).unwrap_or_default();
|
||||||
|
println!("after: host {fp_after:?}, data {data_after}\n--- plugins.lock after\n{lock_after}");
|
||||||
|
if let Ok(t) = std::fs::read_to_string(root.join("Core/plugins/plugin-boot-report.json")) {
|
||||||
|
println!("--- boot report\n{t}");
|
||||||
|
}
|
||||||
|
let reg = coa_core::plugins::load_registry(root)?;
|
||||||
|
for (id, e) in ®.plugins {
|
||||||
|
println!("registry {id}: enabled={} disabled_reason={:?}", e.enabled, e.disabled_reason);
|
||||||
|
}
|
||||||
|
env.ensure_stopped()?;
|
||||||
|
|
||||||
|
assert_eq!(outcome.txn.state, update::State::Committed, "the core update must always commit");
|
||||||
|
if same_core {
|
||||||
|
assert_eq!(fp_before, fp_after, "same-core: the host fingerprint changed");
|
||||||
|
} else {
|
||||||
|
assert_ne!(fp_before, fp_after, "the host fingerprint did not change");
|
||||||
|
}
|
||||||
|
assert_eq!(data_before, data_after, "accounts or characters changed");
|
||||||
|
let shown: Vec<String> = outcome.modules.iter().map(|m| format!("{m:?}")).collect();
|
||||||
|
for (id, e) in reg.plugins.iter().filter(|(_, e)| e.installed) {
|
||||||
|
let line = shown.iter().find(|m| m.contains(&format!("\"{id}\""))).cloned().unwrap_or_default();
|
||||||
|
if broken.as_deref() == Some(id.as_str()) {
|
||||||
|
assert!(line.starts_with("Disabled") && !e.enabled && e.disabled_reason.is_some(), "{id} must be switched off with a reason: {line}");
|
||||||
|
assert!(line.contains("does not build"), "{id} must be switched off because it does not build: {line}");
|
||||||
|
assert!(!lock_after.contains(&format!("{id}|")), "{id} is still in plugins.lock");
|
||||||
|
} else if lock_before.contains(&format!("{id}|")) {
|
||||||
|
let ok = line.starts_with("Rebuilt") || line.starts_with("Reused") || (same_core && line.starts_with("UpToDate"));
|
||||||
|
assert!(ok, "{id} was not rebuilt for the new core: {line}");
|
||||||
|
assert!(e.enabled && lock_after.contains(&format!("{id}|")), "{id} is not loaded after the update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let report = std::fs::read_to_string(root.join("Core/plugins/plugin-boot-report.json"))?;
|
||||||
|
assert!(report.contains("\"anyFaulted\": false"), "the trial start reported a faulted plugin");
|
||||||
|
println!("PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
//! Stable -> Modules Preview on a DISPOSABLE server: install a stable release, seed a test account and
|
||||||
|
//! character and a changed module setting, apply a signed preview update with the production updater (which
|
||||||
|
//! builds the recommended modules and starts the plugin-host core with them), and check that the data and the
|
||||||
|
//! setting survived.
|
||||||
|
//!
|
||||||
|
//! usage: preview_migration_e2e <new folder ending in -fixture> <stable release URL> <preview package dir or URL> [squid]
|
||||||
|
//! With `squid` the stable server runs SQUID's Playerbots (started once so its SQL is imported) before the update;
|
||||||
|
//! SQUID's own SQL journals must come through unchanged.
|
||||||
|
//! The server gets its own free ports before anything starts; it never uses another server's database.
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use coa_core::install::{install_base, Params, Source};
|
||||||
|
use coa_core::registry::{MetaDir, Registry};
|
||||||
|
use coa_core::update::{self, Env, RepackEnv};
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
coa_core::backup::with_database(root, |db| db.query(q)).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fingerprint of the seeded rows, read the same way before and after.
|
||||||
|
fn fingerprint(root: &Path) -> String {
|
||||||
|
sql(root, "SELECT CONCAT_WS('|', a.id, a.username, c.guid, c.name, c.level, c.xp, c.money, \
|
||||||
|
(SELECT COUNT(*) FROM acore_characters.character_spell s WHERE s.guid = c.guid)) \
|
||||||
|
FROM acore_auth.account a JOIN acore_characters.characters c ON c.account = a.id WHERE a.username = 'E2EPREVIEW'")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SQUID's journals and its database, read the same way before and after (absent tables read as "-").
|
||||||
|
fn squid_journals(root: &Path) -> String {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for db in ["acore_characters", "acore_world", "acore_playerbots"] {
|
||||||
|
for t in ["coa_squid_migrations", "coa_squid_pending", "coa_bots_installed"] {
|
||||||
|
let exists = sql(root, &format!("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='{db}' AND TABLE_NAME='{t}'"));
|
||||||
|
if exists.trim() == "0" {
|
||||||
|
out.push(format!("{db}.{t}=-"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cols = sql(root, &format!("SELECT GROUP_CONCAT(COLUMN_NAME ORDER BY ORDINAL_POSITION) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='{db}' AND TABLE_NAME='{t}'"));
|
||||||
|
out.push(format!("{db}.{t}={}", sql(root, &format!(
|
||||||
|
"SELECT CONCAT(COUNT(*), ':', COALESCE(SUM(CRC32(CONCAT_WS('|', {}))), 0)) FROM {db}.{t}", cols.trim()))
|
||||||
|
.trim()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(format!("playerbots tables={}", sql(root, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='acore_playerbots'").trim()));
|
||||||
|
out.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
assert!(a.len() == 3 || (a.len() == 4 && a[3] == "squid"), "usage: preview_migration_e2e <new-folder-fixture> <stable release URL> <preview package dir or URL> [squid]");
|
||||||
|
let squid = a.len() == 4;
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
assert!(a[0].ends_with("-fixture") && !root.exists(), "a new folder ending in -fixture is required");
|
||||||
|
let reg_dir = std::env::temp_dir().join("coa-preview-e2e-registry");
|
||||||
|
let _ = std::fs::remove_dir_all(®_dir);
|
||||||
|
let reg = Registry::at(reg_dir.join("installs.json"));
|
||||||
|
|
||||||
|
// 1. Stable server from its signed installation image.
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let installed = install_base(
|
||||||
|
&Params {
|
||||||
|
source: Source::Installation(Box::new(Source::Url(a[1].clone()))),
|
||||||
|
dest: root.into(),
|
||||||
|
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
|
registry: ®,
|
||||||
|
cancel: Default::default(),
|
||||||
|
},
|
||||||
|
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
|
||||||
|
)?;
|
||||||
|
println!("installed stable {} in {:?}", installed.version, t.elapsed());
|
||||||
|
|
||||||
|
// 2. Own ports, before the server is ever started.
|
||||||
|
let repack = root.join("Settings/repack.json");
|
||||||
|
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack)?)?;
|
||||||
|
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
|
||||||
|
cfg[k] = free_port().into();
|
||||||
|
}
|
||||||
|
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg)?)?;
|
||||||
|
println!("ports {}", serde_json::json!({"mysql": cfg["mysqlPort"], "auth": cfg["authPort"], "world": cfg["worldPort"], "ra": cfg["raPort"]}));
|
||||||
|
|
||||||
|
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||||
|
if squid {
|
||||||
|
// The owner switches the bots to SQUID (Companions off) and starts the server once: the launcher imports
|
||||||
|
// SQUID's SQL into its own journals.
|
||||||
|
coa_core::modules::set_enabled(root, &meta, "companions", false)?;
|
||||||
|
coa_core::modules::set_enabled(root, &meta, "playerbots", true)?;
|
||||||
|
let started = coa_core::driver::run(root, coa_core::driver::Verb::StartAll)?;
|
||||||
|
println!("stable with SQUID started: {}", started.ok);
|
||||||
|
let mut stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll)?;
|
||||||
|
if !stopped.ok {
|
||||||
|
// Known stable launcher behaviour: a stop right after SQUID starts its random bots can outlast the
|
||||||
|
// launcher's 90 s wait. The owner is told to try again; so does this test, and reports it.
|
||||||
|
println!("FINDING: first stop after the SQUID start failed: {}", stopped.output.trim());
|
||||||
|
stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll)?;
|
||||||
|
}
|
||||||
|
assert!(started.ok && stopped.ok, "the stable server with SQUID did not start and stop: {}", stopped.output.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Test data: an account with a character and a spell; a changed module setting.
|
||||||
|
let cols = sql(root, "SELECT GROUP_CONCAT(CONCAT(COLUMN_NAME, ':', DATA_TYPE)) FROM information_schema.COLUMNS \
|
||||||
|
WHERE TABLE_SCHEMA='acore_characters' AND TABLE_NAME='characters' AND IS_NULLABLE='NO' AND COLUMN_DEFAULT IS NULL");
|
||||||
|
sql(root, "INSERT INTO acore_auth.account (username, salt, verifier, email, reg_mail) \
|
||||||
|
VALUES ('E2EPREVIEW', UNHEX(REPEAT('11',32)), UNHEX(REPEAT('22',32)), '', '')");
|
||||||
|
let account = sql(root, "SELECT id FROM acore_auth.account WHERE username='E2EPREVIEW'").trim().to_string();
|
||||||
|
let mut names = vec!["guid", "account", "name", "race", "class", "gender", "level", "xp", "money"].into_iter().map(String::from).collect::<Vec<_>>();
|
||||||
|
let mut values = vec!["990001".to_string(), account, "'Eeprev'".into(), "1".into(), "1".into(), "0".into(), "42".into(), "777".into(), "123456".into()];
|
||||||
|
for c in cols.trim().split(',').filter(|c| !c.is_empty()) {
|
||||||
|
let (name, ty) = c.split_once(':').unwrap();
|
||||||
|
if names.iter().any(|n| n == name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
names.push(name.to_string());
|
||||||
|
values.push(if ty.contains("char") || ty.contains("text") || ty.contains("blob") { "''".into() } else { "0".into() });
|
||||||
|
}
|
||||||
|
sql(root, &format!("INSERT INTO acore_characters.characters ({}) VALUES ({})", names.join(","), values.join(",")));
|
||||||
|
sql(root, "INSERT INTO acore_characters.character_spell (guid, spell, specMask) VALUES (990001, 133, 255)");
|
||||||
|
let conf = root.join("Core/configs/modules/mod-coa-content-scaling.conf");
|
||||||
|
let text = std::fs::read_to_string(&conf)?;
|
||||||
|
let line = text.lines().find(|l| !l.trim_start().starts_with('#') && l.contains(" = ")).expect("a setting").to_string();
|
||||||
|
let changed = format!("{} = 7", line.split(" = ").next().unwrap().trim());
|
||||||
|
std::fs::write(&conf, text.replacen(&line, &changed, 1))?;
|
||||||
|
let before = fingerprint(root);
|
||||||
|
let journals_before = squid_journals(root);
|
||||||
|
println!("squid journals before: {journals_before}");
|
||||||
|
println!("before: {before}\nsetting: {changed}");
|
||||||
|
assert!(!before.trim().is_empty());
|
||||||
|
|
||||||
|
// 4. The preview update, through the production updater.
|
||||||
|
let (_, info) = MetaDir::open(&meta)?;
|
||||||
|
assert_eq!(coa_core::fsx::canonicalize_lenient(Path::new(&info.server_path))?, coa_core::fsx::canonicalize_lenient(root)?);
|
||||||
|
let env = RepackEnv { root, meta_dir: &meta };
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let outcome = update::apply(
|
||||||
|
&update::Params {
|
||||||
|
root,
|
||||||
|
meta_dir: &meta,
|
||||||
|
source: if a[2].starts_with("http") { Source::Url(a[2].clone()) } else { Source::Dir(a[2].clone().into()) },
|
||||||
|
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
|
cancel: Default::default(),
|
||||||
|
resolutions: Default::default(),
|
||||||
|
env: &env,
|
||||||
|
fail_after_ops: None,
|
||||||
|
},
|
||||||
|
&|phase, percent| println!("{percent}% {phase}"),
|
||||||
|
);
|
||||||
|
let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("shutdown after update: {:?}", stopped.map(|r| r.ok));
|
||||||
|
let outcome = outcome?;
|
||||||
|
println!("update {:?} in {:?}; modules {:#?}", outcome.txn.state, t.elapsed(), outcome.modules);
|
||||||
|
|
||||||
|
// 5. Same data, same setting, plugin host with its modules.
|
||||||
|
let after = fingerprint(root);
|
||||||
|
let journals_after = squid_journals(root);
|
||||||
|
println!("squid journals after: {journals_after}");
|
||||||
|
let text = std::fs::read_to_string(&conf)?;
|
||||||
|
println!("after: {after}");
|
||||||
|
println!("setting kept: {}", text.lines().any(|l| l.trim() == changed));
|
||||||
|
for p in ["Core/plugins/plugins.lock", "Core/plugins/plugin-boot-report.json"] {
|
||||||
|
if let Ok(t) = std::fs::read_to_string(root.join(p)) {
|
||||||
|
println!("--- {p}\n{t}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
env.ensure_stopped()?;
|
||||||
|
assert_eq!(outcome.txn.state, update::State::Committed);
|
||||||
|
assert_eq!(before, after, "seeded character data changed");
|
||||||
|
assert!(text.lines().any(|l| l.trim() == changed), "module setting lost");
|
||||||
|
assert_eq!(journals_before, journals_after, "SQUID's journals changed");
|
||||||
|
let ids: Vec<String> = outcome.modules.iter().map(|m| format!("{m:?}")).collect();
|
||||||
|
let has = |id: &str| ids.iter().any(|m| m.contains(&format!("\"{id}\"")));
|
||||||
|
if squid {
|
||||||
|
assert!(has("playerbots") && !has("companions"), "SQUID server must get SQUID's Playerbots, not Companions: {ids:?}");
|
||||||
|
} else {
|
||||||
|
assert!(has("companions") && !has("playerbots"), "Companions server must get Companions, not SQUID: {ids:?}");
|
||||||
|
}
|
||||||
|
println!("PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
//! The Rust bug-report relay against the repack's `BugReport/relay.py`, offline (a scripted service, no network):
|
||||||
|
//!
|
||||||
|
//! 1. the same reports and the same service answers give the same `.status` files and journal rows;
|
||||||
|
//! 2. each relay continues the other's journal: what one delivered is never sent again by the other, and a post the
|
||||||
|
//! other left in progress is uncertain.
|
||||||
|
//!
|
||||||
|
//! usage: relay_equivalence <repack folder with Runtime/python and BugReport/relay.py>
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use coa_core::launcher::relay::{Failure, Relay, Service};
|
||||||
|
|
||||||
|
const REPORTS: [(&str, &str); 5] = [
|
||||||
|
("1-00000000000000a1", "COABUG1\r\nQuest broken\r\nThe NPC is gone.\r\n"),
|
||||||
|
("9-00000000000000b2", "COABUG1\nRate limited\nBody text\n"),
|
||||||
|
("3-00000000000000c3", "COABUG1\nRejected\nBody\n"),
|
||||||
|
("4-00000000000000d4", "COABUG1\nxy\nTitle too short\n"),
|
||||||
|
("5-00000000000000e5", "COABUG1\nUnknown outcome\nBody\n"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The answers per title, in the vocabulary of both relays.
|
||||||
|
fn answer(title: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
match title {
|
||||||
|
"Quest broken" => Ok(101),
|
||||||
|
"Rate limited" => Err(Failure::Limited(60)),
|
||||||
|
"Rejected" => Err(Failure::Invalid),
|
||||||
|
_ => Err(Failure::Uncertain),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const PYTHON: &str = r#"
|
||||||
|
import importlib.util, sys, json
|
||||||
|
from pathlib import Path
|
||||||
|
spec = importlib.util.spec_from_file_location("relay", sys.argv[1]); relay = importlib.util.module_from_spec(spec); spec.loader.exec_module(relay)
|
||||||
|
spool = Path(sys.argv[2]); calls = []
|
||||||
|
class Fake:
|
||||||
|
def create(self, title, body):
|
||||||
|
calls.append(title)
|
||||||
|
if title == "Quest broken": return 101
|
||||||
|
if title == "Rate limited": raise relay.DeliveryError("limited", 60)
|
||||||
|
if title == "Rejected": raise relay.DeliveryError("invalid")
|
||||||
|
raise relay.DeliveryError("uncertain")
|
||||||
|
t = [float(sys.argv[3])]
|
||||||
|
def clock():
|
||||||
|
t[0] += 3
|
||||||
|
return t[0]
|
||||||
|
r = relay.Relay(spool, Fake(), clock=clock)
|
||||||
|
for path in sorted(spool.glob("*.report")):
|
||||||
|
r.process(path)
|
||||||
|
r.close()
|
||||||
|
print(json.dumps(calls))
|
||||||
|
"#;
|
||||||
|
|
||||||
|
struct Scripted(Arc<Mutex<Vec<String>>>);
|
||||||
|
impl Service for Scripted {
|
||||||
|
fn create(&self, title: &str, _: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
self.0.lock().unwrap().push(title.into());
|
||||||
|
answer(title)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spool(dir: &Path) -> PathBuf {
|
||||||
|
std::fs::create_dir_all(dir).unwrap();
|
||||||
|
for (key, text) in REPORTS {
|
||||||
|
std::fs::write(dir.join(format!("{key}.report")), text).unwrap();
|
||||||
|
}
|
||||||
|
dir.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn python(repack: &Path, spool: &Path, start: f64) -> Vec<String> {
|
||||||
|
let out = Command::new(repack.join("Runtime/python/python.exe"))
|
||||||
|
.args(["-I", "-B", "-c", PYTHON])
|
||||||
|
.arg(repack.join("BugReport/relay.py"))
|
||||||
|
.arg(spool)
|
||||||
|
.arg(start.to_string())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||||
|
serde_json::from_slice(&out.stdout).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The clock of both relays: `start`, then 3 seconds later at every reading.
|
||||||
|
fn rust(spool: &Path, start: f64) -> Vec<String> {
|
||||||
|
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let t = Mutex::new(start);
|
||||||
|
let clock = move || {
|
||||||
|
let mut v = t.lock().unwrap();
|
||||||
|
*v += 3.0;
|
||||||
|
*v
|
||||||
|
};
|
||||||
|
let relay = Relay::with_clock(spool, Scripted(calls.clone()), Box::new(clock)).unwrap();
|
||||||
|
relay.pass().unwrap();
|
||||||
|
drop(relay);
|
||||||
|
let c = calls.lock().unwrap().clone();
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `.status` files and journal rows (without the post time).
|
||||||
|
fn snapshot(spool: &Path) -> (Vec<(String, String)>, Vec<String>) {
|
||||||
|
let mut statuses: Vec<(String, String)> = std::fs::read_dir(spool)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| e.path().extension().is_some_and(|x| x == "status"))
|
||||||
|
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read_to_string(e.path()).unwrap()))
|
||||||
|
.collect();
|
||||||
|
statuses.sort();
|
||||||
|
let db = rusqlite::Connection::open(spool.join("relay.sqlite3")).unwrap();
|
||||||
|
let mut q = db.prepare("SELECT key, digest, marker, state, number, next_try FROM deliveries ORDER BY key").unwrap();
|
||||||
|
let rows = q
|
||||||
|
.query_map([], |r| {
|
||||||
|
Ok(format!(
|
||||||
|
"{}|{}|{}|{}|{:?}|{}",
|
||||||
|
r.get::<_, String>(0)?,
|
||||||
|
r.get::<_, String>(1)?,
|
||||||
|
r.get::<_, String>(2)?,
|
||||||
|
r.get::<_, String>(3)?,
|
||||||
|
r.get::<_, Option<i64>>(4)?,
|
||||||
|
r.get::<_, f64>(5)?
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.map(Result::unwrap)
|
||||||
|
.collect();
|
||||||
|
(statuses, rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let repack = PathBuf::from(std::env::args().nth(1).expect("repack folder"));
|
||||||
|
let work = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
// 1
|
||||||
|
let (a, b) = (spool(&work.path().join("python")), spool(&work.path().join("rust")));
|
||||||
|
let py_calls = python(&repack, &a, 1000.0);
|
||||||
|
let rs_calls = rust(&b, 1000.0);
|
||||||
|
println!("python posted {py_calls:?}\nrust posted {rs_calls:?}");
|
||||||
|
assert_eq!(py_calls, rs_calls, "the same reports are posted");
|
||||||
|
let (pa, pb) = (snapshot(&a), snapshot(&b));
|
||||||
|
for s in &pa.0 {
|
||||||
|
println!(" {} = {}", s.0, s.1.trim());
|
||||||
|
}
|
||||||
|
assert_eq!(pa, pb, "the same statuses and journal");
|
||||||
|
|
||||||
|
|
||||||
|
// 2: each continues the other's journal. Before the retry times nothing is sent again; after them only the
|
||||||
|
// rate-limited report is (created, rejected and uncertain ones never are).
|
||||||
|
assert!(python(&repack, &b, 1000.0).is_empty(), "Python does not resend what Rust handled");
|
||||||
|
assert!(rust(&a, 1000.0).is_empty(), "Rust does not resend what Python handled");
|
||||||
|
// Later passes: the queued reports go out, a refused or uncertain one never again.
|
||||||
|
for start in [5000.0, 6000.0, 7000.0] {
|
||||||
|
let (p, r) = (python(&repack, &b, start), rust(&a, start));
|
||||||
|
println!("at {start}: python on rust's journal posted {p:?}, rust on python's posted {r:?}");
|
||||||
|
assert_eq!(p, r, "the same retries");
|
||||||
|
assert!(!p.iter().any(|t| t == "Quest broken" || t == "Unknown outcome"), "created and uncertain are final");
|
||||||
|
}
|
||||||
|
assert_eq!(snapshot(&a), snapshot(&b), "the same after a retry by the other relay");
|
||||||
|
for dir in [&a, &b] {
|
||||||
|
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
|
||||||
|
db.execute("UPDATE deliveries SET state='posting' WHERE key='9-00000000000000b2'", []).unwrap();
|
||||||
|
}
|
||||||
|
python(&repack, &b, 9000.0);
|
||||||
|
rust(&a, 9000.0);
|
||||||
|
for dir in [&a, &b] {
|
||||||
|
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
|
||||||
|
let state: String = db.query_row("SELECT state FROM deliveries WHERE key='9-00000000000000b2'", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_eq!(state, "uncertain", "an interrupted post is not retried ({})", dir.display());
|
||||||
|
}
|
||||||
|
assert_eq!(snapshot(&a), snapshot(&b), "still the same after the crossover");
|
||||||
|
println!("PASS: relay journals, statuses and posts are the same in Python and Rust");
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
//! SQUID database provisioning in Rust gives exactly what Scripts/squid_playerbots.py gives, on a DISPOSABLE repack:
|
||||||
|
//! the same journals (coa_squid_migrations, coa_squid_pending) in every schema, the same acore_playerbots tables
|
||||||
|
//! with the same row counts, the same playerbots.conf. Each side starts from the same state (SQUID never
|
||||||
|
//! provisioned), and a second run of each must change nothing.
|
||||||
|
//!
|
||||||
|
//! usage: squid_equivalence <fixture ending in -fixture> <coa-launcher.exe>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use coa_core::launcher::{services, squid};
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
services::mysql(root, Some(q), None).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What provisioning leaves behind, comparable between runs.
|
||||||
|
fn snapshot(root: &Path) -> String {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for schema in ["acore_characters", "acore_world", "acore_playerbots"] {
|
||||||
|
let tables = sql(root, &format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}' ORDER BY TABLE_NAME;"));
|
||||||
|
for t in tables.lines() {
|
||||||
|
if schema != "acore_playerbots" && !t.starts_with("coa_squid") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let n = sql(root, &format!("SELECT COUNT(*) FROM `{schema}`.`{t}`;"));
|
||||||
|
out.push(format!("{schema}.{t} rows={n}"));
|
||||||
|
if t == "coa_squid_migrations" || t == "coa_squid_pending" {
|
||||||
|
for row in sql(root, &format!("SELECT path, sha256 FROM `{schema}`.`{t}` ORDER BY path;")).lines() {
|
||||||
|
out.push(format!(" {row}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let conf = std::fs::read_to_string(root.join("Core/configs/modules/playerbots.conf")).unwrap();
|
||||||
|
out.push(format!("playerbots.conf:\n{}", conf.replace("\r\n", "\n")));
|
||||||
|
out.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset(root: &Path, conf: &[u8]) {
|
||||||
|
sql(root, "DROP DATABASE IF EXISTS acore_playerbots;");
|
||||||
|
for schema in ["acore_characters", "acore_world"] {
|
||||||
|
sql(root, &format!("DROP TABLE IF EXISTS `{schema}`.coa_squid_migrations, `{schema}`.coa_squid_pending;"));
|
||||||
|
}
|
||||||
|
std::fs::write(root.join("Core/configs/modules/playerbots.conf"), conf).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn python(root: &Path) {
|
||||||
|
let harness = root.join(".state/squid_harness.py");
|
||||||
|
std::fs::write(
|
||||||
|
&harness,
|
||||||
|
"import sys, pathlib\nroot = pathlib.Path(sys.argv[1])\nsys.path.insert(0, str(root / 'Scripts'))\nsys.argv = ['manage.py']\nimport manage\nfrom squid_playerbots import prepare_playerbots\nprepare_playerbots(manage.ROOT, manage.settings(), manage.mysql)\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let out = Command::new(root.join("Runtime/python/python.exe")).arg("-B").arg(&harness).arg(root).output().unwrap();
|
||||||
|
assert!(out.status.success(), "python: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
print!("{}", String::from_utf8_lossy(&out.stdout));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rust(root: &Path) {
|
||||||
|
let cfg = coa_core::launcher::Settings::load(root, 0).unwrap();
|
||||||
|
squid::prepare_playerbots(root, cfg.mysql_port, &|q| services::mysql(root, Some(q), None), &|m| println!("{m}")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
let exe = Path::new(&a[1]);
|
||||||
|
assert!(a[0].ends_with("-fixture"));
|
||||||
|
let modules = root.join("Core/configs/modules");
|
||||||
|
// SQUID on, Companions off
|
||||||
|
let companions = std::fs::read_to_string(modules.join("mod_coa_playerbots.conf")).unwrap();
|
||||||
|
std::fs::write(modules.join("mod_coa_playerbots.conf"), companions.replace("CoaBots.Enable = 1", "CoaBots.Enable = 0")).unwrap();
|
||||||
|
let squid_conf = std::fs::read_to_string(modules.join("playerbots.conf")).unwrap().replace("AiPlayerbot.Enabled = 0", "AiPlayerbot.Enabled = 1");
|
||||||
|
let r = root.to_string_lossy().into_owned();
|
||||||
|
let started = Command::new(exe).args(["--root", &r, "start-mysql"]).output().unwrap();
|
||||||
|
assert!(started.status.success(), "{}", String::from_utf8_lossy(&started.stderr));
|
||||||
|
|
||||||
|
reset(root, squid_conf.as_bytes());
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
python(root);
|
||||||
|
println!("python provisioned in {:?}", t.elapsed());
|
||||||
|
let by_python = snapshot(root);
|
||||||
|
python(root);
|
||||||
|
assert_eq!(snapshot(root), by_python, "a second Python run changed something");
|
||||||
|
|
||||||
|
reset(root, squid_conf.as_bytes());
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
rust(root);
|
||||||
|
println!("rust provisioned in {:?}", t.elapsed());
|
||||||
|
let by_rust = snapshot(root);
|
||||||
|
rust(root);
|
||||||
|
assert_eq!(snapshot(root), by_rust, "a second Rust run changed something");
|
||||||
|
|
||||||
|
if by_python != by_rust {
|
||||||
|
std::fs::write(root.join(".state/squid-python.txt"), &by_python).unwrap();
|
||||||
|
std::fs::write(root.join(".state/squid-rust.txt"), &by_rust).unwrap();
|
||||||
|
panic!("Rust and Python differ: see .state/squid-python.txt and squid-rust.txt");
|
||||||
|
}
|
||||||
|
println!("{} lines of journal/table/config state are identical", by_rust.lines().count());
|
||||||
|
let stopped = Command::new(exe).args(["--root", &r, "stop-all"]).output().unwrap();
|
||||||
|
assert!(stopped.status.success());
|
||||||
|
println!("SQUID EQUIVALENCE PASS");
|
||||||
|
}
|
||||||
@@ -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()
|
.unwrap()
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.starts_with("coa-update-recovery-fixture-"));
|
.starts_with("coa-update-recovery-fixture-"));
|
||||||
assert!(
|
let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered");
|
||||||
!root.join("recovery-e2e-started").exists(),
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||||
"Use a new fixture; never reuse an owned server"
|
if resume {
|
||||||
);
|
assert!(root.join("recovery-e2e-started").is_file());
|
||||||
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
|
let manifest = coa_core::manifest::Manifest::parse(&std::fs::read(
|
||||||
let result = exercise(&root);
|
root.join("fixture-package/manifest.json"),
|
||||||
let stopped = driver::run(&root, Verb::StopAll)?;
|
)?)?;
|
||||||
assert!(stopped.ok);
|
verify_recovered(&root, &manifest)
|
||||||
result
|
} 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<()> {
|
fn exercise(root: &Path) -> Result<()> {
|
||||||
@@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> {
|
|||||||
assert!(
|
assert!(
|
||||||
error
|
error
|
||||||
.to_string()
|
.to_string()
|
||||||
.contains("private update rehearsal failed"),
|
.contains("files and databases were restored to the recovery point"),
|
||||||
"{error}"
|
"{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!(!root.join("Core/recovery-probe.txt").exists());
|
||||||
assert!(update::unfinished(&meta).is_none());
|
assert!(update::unfinished(&meta).is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> {
|
|||||||
Db::from_repack(root, Account::Admin)?.realm(),
|
Db::from_repack(root, Account::Admin)?.realm(),
|
||||||
coa_core::realms::Mode::Coa
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -80,6 +80,60 @@ fn upper(name: &str) -> Result<String> {
|
|||||||
Ok(name.to_ascii_uppercase())
|
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
|
/// 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.
|
/// 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<()> {
|
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 {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn rows_from_the_client_become_accounts() {
|
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";
|
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-")));
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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 db = Db::from_repack(root, Account::Admin)?;
|
||||||
let observed = process::observe(root, &read_ports(root));
|
let observed = process::observe(root, &read_ports(root));
|
||||||
let mysql_was_up = observed.mysql.state == ServiceState::Running && db.ping();
|
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)?;
|
let out = driver::run(root, Verb::StartMysql)?;
|
||||||
if !out.ok {
|
if !out.ok {
|
||||||
// Keep the launcher's own last lines: the title alone ("Something went wrong") hides the cause.
|
// 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)
|
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);
|
let result = f(&db);
|
||||||
if !mysql_was_up {
|
if !mysql_was_up {
|
||||||
let now = process::observe(root, &read_ports(root));
|
let now = process::observe(root, &read_ports(root));
|
||||||
|
|||||||
@@ -0,0 +1,441 @@
|
|||||||
|
//! CLI tool for CoA Server Manager plugin operations (testing, qualification and automation).
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use coa_core::plugins::{self, PluginMetadata};
|
||||||
|
|
||||||
|
fn print_usage() {
|
||||||
|
eprintln!(
|
||||||
|
r#"csm_plugins CLI
|
||||||
|
Usage:
|
||||||
|
csm_plugins install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable] [--crash-at <point>]
|
||||||
|
csm_plugins update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--crash-at <point>]
|
||||||
|
csm_plugins enable <server> <id> [--crash-at <point>]
|
||||||
|
csm_plugins disable <server> <id> [--crash-at <point>]
|
||||||
|
csm_plugins remove <server> <id> [--crash-at <point>]
|
||||||
|
csm_plugins repair <server> [--crash-at <point>]
|
||||||
|
csm_plugins recover <server>
|
||||||
|
csm_plugins prune <server>
|
||||||
|
csm_plugins list <server>
|
||||||
|
csm_plugins reconcile_squid <server> [char_schema]
|
||||||
|
csm_plugins multiworld <server> <second_root> [--allow <a,b>] [--crash-at <point>]
|
||||||
|
csm_plugins analyze <local_repository_path> [--json]
|
||||||
|
csm_plugins analyze-github <url> [--cache-dir <dir>] [--contract <v02|v03>] [--json]
|
||||||
|
csm_plugins verify-artifact-provenance <worldserver_path> [--sdk-json <path>] [--json]
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let args: Vec<String> = std::env::args().collect();
|
||||||
|
if args.len() < 3 {
|
||||||
|
print_usage();
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inspect for --crash-at argument
|
||||||
|
for i in 0..args.len() {
|
||||||
|
if args[i] == "--crash-at" && i + 1 < args.len() {
|
||||||
|
std::env::set_var("CSM_CRASH_AT", &args[i + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cmd = &args[1];
|
||||||
|
let server = Path::new(&args[2]);
|
||||||
|
|
||||||
|
match cmd.as_str() {
|
||||||
|
"install" => {
|
||||||
|
if args.len() < 7 {
|
||||||
|
eprintln!("Usage: install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable]");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let id = &args[3];
|
||||||
|
let name = &args[4];
|
||||||
|
let version = &args[5];
|
||||||
|
let dll_path = Path::new(&args[6]);
|
||||||
|
let dll_bytes = fs::read(dll_path)?;
|
||||||
|
let digest = plugins::sha256_digest(&dll_bytes);
|
||||||
|
|
||||||
|
let mut pdb_bytes = None;
|
||||||
|
let mut conf_list = Vec::new();
|
||||||
|
let mut deps = Vec::new();
|
||||||
|
let mut enable = false;
|
||||||
|
|
||||||
|
let mut i = 7;
|
||||||
|
while i < args.len() {
|
||||||
|
match args[i].as_str() {
|
||||||
|
"--pdb" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
pdb_bytes = Some(fs::read(&args[i])?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--conf" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
for item in args[i].split(',') {
|
||||||
|
if !item.is_empty() {
|
||||||
|
let p = Path::new(item);
|
||||||
|
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
|
||||||
|
let bytes = fs::read(p)?;
|
||||||
|
conf_list.push((file_name, bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--deps" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
deps = args[i].split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--enable" => {
|
||||||
|
enable = true;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
|
||||||
|
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
|
||||||
|
|
||||||
|
let meta = PluginMetadata {
|
||||||
|
id: id.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
version: version.clone(),
|
||||||
|
description: BTreeMap::new(),
|
||||||
|
sha256: digest,
|
||||||
|
required: true,
|
||||||
|
deps,
|
||||||
|
conf_files: conf_names,
|
||||||
|
enable_key: None,
|
||||||
|
status: Some("release".into()),
|
||||||
|
icon: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
plugins::install(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs, enable)?;
|
||||||
|
println!("Installed plugin '{}' successfully (enabled: {})", id, enable);
|
||||||
|
}
|
||||||
|
"update" => {
|
||||||
|
if args.len() < 7 {
|
||||||
|
eprintln!("Usage: update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>]");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let id = &args[3];
|
||||||
|
let name = &args[4];
|
||||||
|
let version = &args[5];
|
||||||
|
let dll_path = Path::new(&args[6]);
|
||||||
|
let dll_bytes = fs::read(dll_path)?;
|
||||||
|
let digest = plugins::sha256_digest(&dll_bytes);
|
||||||
|
|
||||||
|
let mut pdb_bytes = None;
|
||||||
|
let mut conf_list = Vec::new();
|
||||||
|
|
||||||
|
let mut i = 7;
|
||||||
|
while i < args.len() {
|
||||||
|
match args[i].as_str() {
|
||||||
|
"--pdb" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
pdb_bytes = Some(fs::read(&args[i])?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--conf" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
for item in args[i].split(',') {
|
||||||
|
if !item.is_empty() {
|
||||||
|
let p = Path::new(item);
|
||||||
|
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
|
||||||
|
let bytes = fs::read(p)?;
|
||||||
|
conf_list.push((file_name, bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
|
||||||
|
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
|
||||||
|
|
||||||
|
let meta = PluginMetadata {
|
||||||
|
id: id.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
version: version.clone(),
|
||||||
|
description: BTreeMap::new(),
|
||||||
|
sha256: digest,
|
||||||
|
required: true,
|
||||||
|
deps: vec![],
|
||||||
|
conf_files: conf_names,
|
||||||
|
enable_key: None,
|
||||||
|
status: Some("release".into()),
|
||||||
|
icon: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
plugins::update(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs)?;
|
||||||
|
println!("Updated plugin '{}' to version {} successfully", id, version);
|
||||||
|
}
|
||||||
|
"enable" => {
|
||||||
|
if args.len() < 4 {
|
||||||
|
eprintln!("Usage: enable <server> <id>");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let id = &args[3];
|
||||||
|
plugins::set_enabled(server, id, true)?;
|
||||||
|
println!("Enabled plugin '{}' successfully", id);
|
||||||
|
}
|
||||||
|
"disable" => {
|
||||||
|
if args.len() < 4 {
|
||||||
|
eprintln!("Usage: disable <server> <id>");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let id = &args[3];
|
||||||
|
plugins::set_enabled(server, id, false)?;
|
||||||
|
println!("Disabled plugin '{}' successfully", id);
|
||||||
|
}
|
||||||
|
"remove" => {
|
||||||
|
if args.len() < 4 {
|
||||||
|
eprintln!("Usage: remove <server> <id>");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let id = &args[3];
|
||||||
|
plugins::remove(server, id)?;
|
||||||
|
println!("Removed plugin '{}' successfully", id);
|
||||||
|
}
|
||||||
|
"repair" => {
|
||||||
|
let restored = plugins::repair(server)?;
|
||||||
|
println!("Repair complete. Restored {} plugin(s): {:?}", restored.len(), restored);
|
||||||
|
}
|
||||||
|
"recover" => {
|
||||||
|
plugins::ensure_durable_recovered(server)?;
|
||||||
|
println!("Durable transaction recovery complete (clean state restored).");
|
||||||
|
}
|
||||||
|
"prune" => {
|
||||||
|
let pruned = plugins::prune_store(server)?;
|
||||||
|
println!("Pruned {} unused store version(s): {:?}", pruned.len(), pruned);
|
||||||
|
}
|
||||||
|
"reconcile_squid" => {
|
||||||
|
let char_schema = if args.len() >= 4 { &args[3] } else { "acore_characters" };
|
||||||
|
let port_str = std::env::var("MYSQL_PORT").unwrap_or_else(|_| "3417".into());
|
||||||
|
let user = std::env::var("MYSQL_USER").unwrap_or_else(|_| "root".into());
|
||||||
|
let pass = std::env::var("MYSQL_PWD").unwrap_or_default();
|
||||||
|
let mysql_exe = std::env::var("MYSQL_EXE").unwrap_or_else(|_| "mysql".into());
|
||||||
|
|
||||||
|
let query_fn = |sql: &str| -> Result<String, coa_core::error::Error> {
|
||||||
|
let mut cmd = std::process::Command::new(&mysql_exe);
|
||||||
|
cmd.args(["-h", "127.0.0.1", "-P", &port_str, "-u", &user, "-e", sql]);
|
||||||
|
if !pass.is_empty() && pass != "trap" {
|
||||||
|
cmd.env("MYSQL_PWD", &pass);
|
||||||
|
} else {
|
||||||
|
cmd.env_remove("MYSQL_PWD");
|
||||||
|
}
|
||||||
|
let out = cmd.output().map_err(coa_core::error::Error::Io)?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(coa_core::error::Error::Invalid(String::from_utf8_lossy(&out.stderr).into_owned()));
|
||||||
|
}
|
||||||
|
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||||
|
};
|
||||||
|
let audit = plugins::reconcile_squid_migrations(server, char_schema, Some(&query_fn))?;
|
||||||
|
println!("SQUID Reconciliation: status={:?}, applied={}", audit.db_status, audit.effective_applied);
|
||||||
|
}
|
||||||
|
"list" => {
|
||||||
|
let reg = plugins::load_registry(server)?;
|
||||||
|
println!("Plugins schema {}:", reg.schema);
|
||||||
|
for (id, p) in reg.plugins {
|
||||||
|
println!(
|
||||||
|
" - {}: enabled={}, version={}, sha256={}",
|
||||||
|
id, p.enabled, p.version, p.sha256
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"multiworld" => {
|
||||||
|
if args.len() < 4 {
|
||||||
|
eprintln!("Usage: multiworld <server> <second_root> [--allow <a,b>]");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let second_root = Path::new(&args[3]);
|
||||||
|
let mut allowlist = None;
|
||||||
|
if args.len() >= 6 && args[4] == "--allow" {
|
||||||
|
allowlist = Some(args[5].split(',').filter(|s| !s.is_empty()).map(str::to_string).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
plugins::prepare_multiworld_realm(server, second_root, allowlist.as_deref())?;
|
||||||
|
println!("Prepared multiworld realm at {} successfully", second_root.display());
|
||||||
|
}
|
||||||
|
"analyze" => {
|
||||||
|
let repo_path = Path::new(&args[2]);
|
||||||
|
let as_json = args.iter().any(|a| a == "--json");
|
||||||
|
let contract = if args.iter().any(|a| a == "--sdk-v02") {
|
||||||
|
coa_core::analyzer::SdkExportContract::v02()
|
||||||
|
} else {
|
||||||
|
coa_core::analyzer::SdkExportContract::v03()
|
||||||
|
};
|
||||||
|
let report = coa_core::analyzer::analyze_repository_with_contract(repo_path, &contract)?;
|
||||||
|
if as_json {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||||
|
} else {
|
||||||
|
println!("=== Module Compatibility Report v0.2 ===");
|
||||||
|
println!("Repository: {}", report.repository_name);
|
||||||
|
println!("Commit : {}", report.commit);
|
||||||
|
println!("License : {}", report.license_info.primary_license);
|
||||||
|
if let Some(ref lf) = report.license_info.license_file {
|
||||||
|
println!("License File: {}", lf);
|
||||||
|
}
|
||||||
|
if !report.license_info.vendored_licenses.is_empty() {
|
||||||
|
println!("Vendored Licenses: {:?}", report.license_info.vendored_licenses);
|
||||||
|
}
|
||||||
|
println!("Verdict : {:?}", report.classification);
|
||||||
|
println!("Status L0-L6: static={}, compile={}, link={}, contract={}, boot={}, gameplay={}, teardown={}",
|
||||||
|
report.verification_status.l0_static,
|
||||||
|
report.verification_status.l1_compile,
|
||||||
|
report.verification_status.l2_link,
|
||||||
|
report.verification_status.l3_contract,
|
||||||
|
report.verification_status.l4_engine_boot,
|
||||||
|
report.verification_status.l5_gameplay,
|
||||||
|
report.verification_status.l6_teardown);
|
||||||
|
println!("Hooks ({}):", report.hooks.len());
|
||||||
|
for h in &report.hooks {
|
||||||
|
println!(" - {} : {} ({}:{})", h.class_name, h.script_type, h.file, h.line);
|
||||||
|
}
|
||||||
|
println!("SQL Files ({}):", report.sql_files.len());
|
||||||
|
for s in &report.sql_files {
|
||||||
|
println!(" - {} [schema: {}] (create={}, alter={}, lines={})", s.file, s.target_schema, s.has_create_table, s.has_alter_table, s.line_count);
|
||||||
|
}
|
||||||
|
println!("Findings ({}):", report.findings.len());
|
||||||
|
for f in &report.findings {
|
||||||
|
println!(" [{:?}] {} (at {}:{}): {}", f.severity, f.rule_id, f.file, f.line, f.explanation);
|
||||||
|
println!(" Guidance: {}", f.recommended_action);
|
||||||
|
}
|
||||||
|
println!("Summary Reasons: {:?}", report.reasons);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"analyze-github" => {
|
||||||
|
let url = &args[2];
|
||||||
|
let mut cache_dir = None;
|
||||||
|
let mut json_out = false;
|
||||||
|
|
||||||
|
let mut i = 3;
|
||||||
|
while i < args.len() {
|
||||||
|
match args[i].as_str() {
|
||||||
|
"--cache-dir" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
cache_dir = Some(std::path::PathBuf::from(&args[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--json" => {
|
||||||
|
json_out = true;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
match coa_core::analyzer::analyze_github_repository(url, cache_dir.as_deref()) {
|
||||||
|
Ok(report) => {
|
||||||
|
if json_out {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||||
|
} else {
|
||||||
|
println!("Repository: {}", report.repository_name);
|
||||||
|
println!("Classification: {:?}", report.classification);
|
||||||
|
println!("License: {}", report.license_info.primary_license);
|
||||||
|
println!("Cache Hit: {:?}", report.cache_hit);
|
||||||
|
println!("Tree Digest: {:?}", report.tree_digest);
|
||||||
|
println!("Commit: {:?}", report.commit);
|
||||||
|
println!("Loaders: {:?}", report.script_loaders);
|
||||||
|
println!("Hooks: {}", report.hooks.len());
|
||||||
|
println!("SQL Files: {}", report.sql_files.len());
|
||||||
|
println!("Findings: {}", report.findings.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("ERROR: {}", e);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"generate-adapter" => {
|
||||||
|
let repo_path = Path::new(&args[2]);
|
||||||
|
let res = coa_core::analyzer::generate_adapter(repo_path)?;
|
||||||
|
match res {
|
||||||
|
coa_core::analyzer::AdapterGenerationResult::Success { canonical_loader, adapter_source, delegated_count } => {
|
||||||
|
println!("Canonical Master Loader: {} (delegates to {} scripts)", canonical_loader, delegated_count);
|
||||||
|
if let Some(pos) = args.iter().position(|a| a == "--output") {
|
||||||
|
if pos + 1 < args.len() {
|
||||||
|
let out_path = Path::new(&args[pos + 1]);
|
||||||
|
if let Some(p) = out_path.parent() {
|
||||||
|
std::fs::create_dir_all(p)?;
|
||||||
|
}
|
||||||
|
std::fs::write(out_path, &adapter_source)?;
|
||||||
|
println!("Adapter successfully written to: {}", out_path.display());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("--- Generated Adapter Source ---");
|
||||||
|
println!("{}", adapter_source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
coa_core::analyzer::AdapterGenerationResult::ManualAdapterRequired { reason, candidate_loaders } => {
|
||||||
|
eprintln!("MANUAL_ADAPTER_REQUIRED: {}", reason);
|
||||||
|
eprintln!("Candidate Loaders: {:?}", candidate_loaders);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
coa_core::analyzer::AdapterGenerationResult::NoLoaderFound => {
|
||||||
|
eprintln!("NO_LOADER_FOUND: Unable to discover any Add*Scripts() functions.");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"verify-artifact-provenance" => {
|
||||||
|
let exe_path = Path::new(&args[2]);
|
||||||
|
let mut sdk_json = None;
|
||||||
|
let mut json_out = false;
|
||||||
|
|
||||||
|
let mut i = 3;
|
||||||
|
while i < args.len() {
|
||||||
|
match args[i].as_str() {
|
||||||
|
"--sdk-json" => {
|
||||||
|
i += 1;
|
||||||
|
if i < args.len() {
|
||||||
|
sdk_json = Some(Path::new(&args[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--json" => {
|
||||||
|
json_out = true;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
match coa_core::provenance::verify_worldserver_provenance(exe_path, sdk_json) {
|
||||||
|
Ok(rec) => {
|
||||||
|
if json_out {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&rec)?);
|
||||||
|
} else {
|
||||||
|
println!("Artifact: {}", rec.file_path);
|
||||||
|
println!("SHA-256: {}", rec.file_sha256);
|
||||||
|
println!("Arch: {}", rec.machine_architecture);
|
||||||
|
println!("Exports: {}", rec.total_export_count);
|
||||||
|
println!("Embedded ABI: {:?}", rec.embedded_abi_fingerprint);
|
||||||
|
println!("Status: {}", rec.provenance_status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("ERROR: {}", e);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
eprintln!("Unknown command: {}", cmd);
|
||||||
|
print_usage();
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
//! The compiler's work kept between builds of a module, small on disk.
|
||||||
|
//!
|
||||||
|
//! A build works in `<meta>/build-cache/<module>/` (sources, CMake/Ninja state, object files). Between builds
|
||||||
|
//! that folder is packed into `<module>.tar.zst` (object files compress about 4x) with a small record of the
|
||||||
|
//! core it was made for. Before the next build it is unpacked again, so Ninja recompiles only what changed.
|
||||||
|
//!
|
||||||
|
//! Object files made for another core are useless (every one depends on the core's headers), so a cache for
|
||||||
|
//! another core is dropped instead of unpacked. The whole cache is kept under a size limit: the modules built
|
||||||
|
//! longest ago go first. Incremental-link files (`.ilk`) and linker maps are not kept.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::io::{BufReader, BufWriter};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
/// Packed caches above this total are removed, the least recently built first.
|
||||||
|
pub const LIMIT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
struct Record {
|
||||||
|
/// ABI fingerprint of the core the objects were compiled for.
|
||||||
|
fingerprint: String,
|
||||||
|
/// Unix seconds of the last build.
|
||||||
|
last_used: i64,
|
||||||
|
unpacked_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CacheEntry {
|
||||||
|
pub module: String,
|
||||||
|
/// Bytes on disk now (packed, or unpacked while a build runs).
|
||||||
|
pub bytes: u64,
|
||||||
|
pub unpacked_bytes: u64,
|
||||||
|
pub last_used: i64,
|
||||||
|
/// Made for the core this server runs now (otherwise it is dropped at the next build).
|
||||||
|
pub current_core: bool,
|
||||||
|
pub packed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CacheSummary {
|
||||||
|
pub modules: Vec<CacheEntry>,
|
||||||
|
pub total_bytes: u64,
|
||||||
|
/// Downloaded module sources (shared by all servers of this Manager).
|
||||||
|
pub sources_bytes: u64,
|
||||||
|
pub limit_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn root(realm_root: &Path) -> PathBuf {
|
||||||
|
crate::plugins::meta_dir(realm_root).join("build-cache")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 100 && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && id != "." && id != ".."
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paths(realm_root: &Path, id: &str) -> Result<(PathBuf, PathBuf, PathBuf)> {
|
||||||
|
if !valid_id(id) {
|
||||||
|
return Err(Error::Invalid(format!("Invalid module id for the build cache: {id}")));
|
||||||
|
}
|
||||||
|
let r = root(realm_root);
|
||||||
|
Ok((r.join(id), r.join(format!("{id}.tar.zst")), r.join(format!("{id}.json"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn dir_bytes(dir: &Path) -> u64 {
|
||||||
|
fs::read_dir(dir)
|
||||||
|
.map(|rd| {
|
||||||
|
rd.flatten()
|
||||||
|
.map(|e| match e.metadata() {
|
||||||
|
Ok(m) if m.is_dir() => dir_bytes(&e.path()),
|
||||||
|
Ok(m) => m.len(),
|
||||||
|
Err(_) => 0,
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
})
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_record(path: &Path) -> Option<Record> {
|
||||||
|
serde_json::from_slice(&fs::read(path).ok()?).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The working folder for a build of `id` for the core `fingerprint`, with the earlier work of a build for the
|
||||||
|
/// same core unpacked into it. A cache for another core is dropped.
|
||||||
|
pub fn prepare(realm_root: &Path, id: &str, fingerprint: &str) -> Result<PathBuf> {
|
||||||
|
let (dir, archive, record) = paths(realm_root, id)?;
|
||||||
|
let rec = read_record(&record);
|
||||||
|
let same_core = rec.as_ref().is_some_and(|r| r.fingerprint == fingerprint);
|
||||||
|
if !same_core {
|
||||||
|
// made for another core (or unknown): its objects would all be rebuilt anyway
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(&dir)?;
|
||||||
|
}
|
||||||
|
let _ = fs::remove_file(&archive);
|
||||||
|
let _ = fs::remove_file(&record);
|
||||||
|
} else if archive.is_file() {
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(&dir)?; // an older, interrupted working folder: the archive is the newer state
|
||||||
|
}
|
||||||
|
unpack(&archive, &dir).map_err(|e| {
|
||||||
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
Error::Invalid(format!("The build cache of {id} could not be unpacked: {e}"))
|
||||||
|
})?;
|
||||||
|
fs::remove_file(&archive)?;
|
||||||
|
}
|
||||||
|
fs::create_dir_all(&dir)?;
|
||||||
|
let unpacked_bytes = dir_bytes(&dir);
|
||||||
|
crate::fsx::atomic_write_json(&record, &Record { fingerprint: fingerprint.into(), last_used: now(), unpacked_bytes })?;
|
||||||
|
Ok(dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a build (successful or not): drop what does not speed up the next one, pack the rest, keep the total
|
||||||
|
/// under the limit. Never fails the build: problems only cost the cache.
|
||||||
|
pub fn finish(realm_root: &Path, id: &str) {
|
||||||
|
let Ok((dir, archive, record)) = paths(realm_root, id) else { return };
|
||||||
|
if !dir.is_dir() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remove_by_ext(&dir, &["ilk", "map"]);
|
||||||
|
let unpacked_bytes = dir_bytes(&dir);
|
||||||
|
let tmp = archive.with_extension("zst.partial");
|
||||||
|
match pack(&dir, &tmp).and_then(|_| fs::rename(&tmp, &archive).map_err(Into::into)) {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
if let Some(mut r) = read_record(&record) {
|
||||||
|
r.last_used = now();
|
||||||
|
r.unpacked_bytes = unpacked_bytes;
|
||||||
|
let _ = crate::fsx::atomic_write_json(&record, &r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(module = id, error = %e, "build cache not packed; it is kept unpacked");
|
||||||
|
let _ = fs::remove_file(&tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
enforce_limit(realm_root, LIMIT_BYTES, Some(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_by_ext(dir: &Path, exts: &[&str]) {
|
||||||
|
for e in fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
remove_by_ext(&p, exts);
|
||||||
|
} else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| exts.iter().any(|w| w.eq_ignore_ascii_case(x))) {
|
||||||
|
let _ = fs::remove_file(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pack(dir: &Path, out: &Path) -> Result<()> {
|
||||||
|
let file = BufWriter::new(fs::File::create(out)?);
|
||||||
|
let mut enc = zstd::Encoder::new(file, 3)?;
|
||||||
|
let _ = enc.multithread(std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(1).min(8));
|
||||||
|
{
|
||||||
|
let mut tar = tar::Builder::new(&mut enc);
|
||||||
|
tar.follow_symlinks(false);
|
||||||
|
// modification times are kept: Ninja decides from them what is up to date
|
||||||
|
tar.mode(tar::HeaderMode::Complete);
|
||||||
|
tar.append_dir_all(".", dir)?;
|
||||||
|
tar.finish()?;
|
||||||
|
}
|
||||||
|
enc.finish()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unpack(archive: &Path, dir: &Path) -> Result<()> {
|
||||||
|
fs::create_dir_all(dir)?;
|
||||||
|
let dec = zstd::Decoder::new(BufReader::new(fs::File::open(archive)?))?;
|
||||||
|
let mut tar = tar::Archive::new(dec);
|
||||||
|
tar.set_preserve_mtime(true);
|
||||||
|
for entry in tar.entries()? {
|
||||||
|
let mut entry = entry?;
|
||||||
|
// unpack_in refuses paths that would leave `dir`
|
||||||
|
if !entry.unpack_in(dir)? {
|
||||||
|
return Err(Error::PathRejected(format!("build cache entry {}", entry.path()?.display())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything in the build cache of this server, largest first.
|
||||||
|
pub fn summary(realm_root: &Path, sources_dir: Option<&Path>) -> CacheSummary {
|
||||||
|
let current = crate::provenance::realm_host_fingerprint(realm_root);
|
||||||
|
let r = root(realm_root);
|
||||||
|
let mut modules = Vec::new();
|
||||||
|
for e in fs::read_dir(&r).into_iter().flatten().flatten() {
|
||||||
|
let name = e.file_name().to_string_lossy().into_owned();
|
||||||
|
let Some(id) = name.strip_suffix(".json") else { continue };
|
||||||
|
let Ok((dir, archive, record)) = paths(realm_root, id) else { continue };
|
||||||
|
let Some(rec) = read_record(&record) else { continue };
|
||||||
|
let packed = archive.is_file();
|
||||||
|
let bytes = if packed { fs::metadata(&archive).map(|m| m.len()).unwrap_or(0) } else { dir_bytes(&dir) };
|
||||||
|
modules.push(CacheEntry {
|
||||||
|
module: id.to_string(),
|
||||||
|
bytes,
|
||||||
|
unpacked_bytes: rec.unpacked_bytes,
|
||||||
|
last_used: rec.last_used,
|
||||||
|
current_core: current.as_deref() == Some(rec.fingerprint.as_str()),
|
||||||
|
packed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// working folders of an older Manager, without a record
|
||||||
|
for e in fs::read_dir(&r).into_iter().flatten().flatten() {
|
||||||
|
let name = e.file_name().to_string_lossy().into_owned();
|
||||||
|
if e.path().is_dir() && valid_id(&name) && !modules.iter().any(|m| m.module == name) {
|
||||||
|
let bytes = dir_bytes(&e.path());
|
||||||
|
modules.push(CacheEntry { module: name, bytes, unpacked_bytes: bytes, last_used: 0, current_core: false, packed: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
modules.sort_by(|a, b| b.bytes.cmp(&a.bytes));
|
||||||
|
CacheSummary {
|
||||||
|
total_bytes: modules.iter().map(|m| m.bytes).sum(),
|
||||||
|
sources_bytes: sources_dir.map(dir_bytes).unwrap_or(0),
|
||||||
|
limit_bytes: LIMIT_BYTES,
|
||||||
|
modules,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the cache of one module, or of all. The next build of a module compiles it in full.
|
||||||
|
pub fn clear(realm_root: &Path, module: Option<&str>) -> Result<u64> {
|
||||||
|
let before = summary(realm_root, None).total_bytes;
|
||||||
|
match module {
|
||||||
|
Some(id) => {
|
||||||
|
let (dir, archive, record) = paths(realm_root, id)?;
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let _ = fs::remove_file(archive);
|
||||||
|
let _ = fs::remove_file(record);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let r = root(realm_root);
|
||||||
|
if r.exists() {
|
||||||
|
fs::remove_dir_all(&r)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(before.saturating_sub(summary(realm_root, None).total_bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep the packed caches under `limit`, dropping the least recently built (never `keep`).
|
||||||
|
fn enforce_limit(realm_root: &Path, limit: u64, keep: Option<&str>) {
|
||||||
|
let mut s = summary(realm_root, None);
|
||||||
|
s.modules.sort_by_key(|m| m.last_used);
|
||||||
|
let mut total = s.total_bytes;
|
||||||
|
for m in &s.modules {
|
||||||
|
if total <= limit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if Some(m.module.as_str()) == keep {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if clear(realm_root, Some(&m.module)).is_ok() {
|
||||||
|
tracing::info!(module = %m.module, bytes = m.bytes, "build cache over its limit: oldest removed");
|
||||||
|
total = total.saturating_sub(m.bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloaded module sources the Manager keeps (`<cache>/github`, `<cache>/staging`).
|
||||||
|
pub fn clear_sources(sources_dir: &Path) -> Result<u64> {
|
||||||
|
let before = dir_bytes(sources_dir);
|
||||||
|
for sub in ["github", "staging"] {
|
||||||
|
let p = sources_dir.join(sub);
|
||||||
|
if p.exists() {
|
||||||
|
fs::remove_dir_all(p)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(before.saturating_sub(dir_bytes(sources_dir)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
|
fn server() -> tempfile::TempDir {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
fs::create_dir_all(d.path().join(".manager")).unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cache_is_packed_between_builds_and_comes_back_with_its_times() {
|
||||||
|
let s = server();
|
||||||
|
let dir = prepare(s.path(), "companions", "fp1").unwrap();
|
||||||
|
fs::create_dir_all(dir.join("build/obj")).unwrap();
|
||||||
|
fs::write(dir.join("build/obj/a.obj"), vec![7u8; 100_000]).unwrap();
|
||||||
|
fs::write(dir.join("build/x.ilk"), b"incremental link").unwrap();
|
||||||
|
let old = SystemTime::now() - Duration::from_secs(3600);
|
||||||
|
fs::File::options().write(true).open(dir.join("build/obj/a.obj")).unwrap().set_modified(old).unwrap();
|
||||||
|
finish(s.path(), "companions");
|
||||||
|
assert!(!dir.exists(), "packed between builds");
|
||||||
|
let sum = summary(s.path(), None);
|
||||||
|
assert_eq!(sum.modules.len(), 1);
|
||||||
|
assert!(sum.modules[0].packed && sum.modules[0].bytes < 100_000 / 4, "compressed: {}", sum.modules[0].bytes);
|
||||||
|
|
||||||
|
let dir = prepare(s.path(), "companions", "fp1").unwrap();
|
||||||
|
assert_eq!(fs::read(dir.join("build/obj/a.obj")).unwrap().len(), 100_000);
|
||||||
|
assert!(!dir.join("build/x.ilk").exists(), "incremental-link files are not kept");
|
||||||
|
let mtime = fs::metadata(dir.join("build/obj/a.obj")).unwrap().modified().unwrap();
|
||||||
|
let drift = mtime.duration_since(old).unwrap_or_else(|e| e.duration());
|
||||||
|
assert!(drift < Duration::from_secs(2), "modification time kept (drift {drift:?})");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cache_for_another_core_is_dropped() {
|
||||||
|
let s = server();
|
||||||
|
let dir = prepare(s.path(), "scaling", "old-core").unwrap();
|
||||||
|
fs::write(dir.join("a.obj"), b"old").unwrap();
|
||||||
|
finish(s.path(), "scaling");
|
||||||
|
let dir = prepare(s.path(), "scaling", "new-core").unwrap();
|
||||||
|
assert!(!dir.join("a.obj").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clear_removes_one_module_or_all_and_bad_ids_are_refused() {
|
||||||
|
let s = server();
|
||||||
|
for id in ["a", "b"] {
|
||||||
|
let d = prepare(s.path(), id, "fp").unwrap();
|
||||||
|
fs::write(d.join("x.obj"), b"x").unwrap();
|
||||||
|
finish(s.path(), id);
|
||||||
|
}
|
||||||
|
clear(s.path(), Some("a")).unwrap();
|
||||||
|
assert_eq!(summary(s.path(), None).modules.iter().map(|m| m.module.as_str()).collect::<Vec<_>>(), ["b"]);
|
||||||
|
clear(s.path(), None).unwrap();
|
||||||
|
assert!(summary(s.path(), None).modules.is_empty());
|
||||||
|
assert!(clear(s.path(), Some("../x")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_least_recently_built_go_first_over_the_limit() {
|
||||||
|
let s = server();
|
||||||
|
for (n, id) in ["old", "new"].iter().enumerate() {
|
||||||
|
let d = prepare(s.path(), id, "fp").unwrap();
|
||||||
|
fs::write(d.join("x.obj"), vec![n as u8; 50_000]).unwrap();
|
||||||
|
finish(s.path(), id);
|
||||||
|
let rec = root(s.path()).join(format!("{id}.json"));
|
||||||
|
let mut r = read_record(&rec).unwrap();
|
||||||
|
r.last_used = 1000 + n as i64;
|
||||||
|
crate::fsx::atomic_write_json(&rec, &r).unwrap();
|
||||||
|
}
|
||||||
|
let total = summary(s.path(), None).total_bytes;
|
||||||
|
enforce_limit(s.path(), total - 1, None);
|
||||||
|
let left: Vec<String> = summary(s.path(), None).modules.into_iter().map(|m| m.module).collect();
|
||||||
|
assert_eq!(left, ["new"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,992 @@
|
|||||||
|
//! Public AzerothCore Module Catalogue integration for CoA Server Manager.
|
||||||
|
//!
|
||||||
|
//! Provides cached, prioritized, and overlay-enriched discovery of AzerothCore modules
|
||||||
|
//! sourced from `https://www.azerothcore.org/data/catalogue.json`.
|
||||||
|
//!
|
||||||
|
//! Features:
|
||||||
|
//! - Thread-safe periodic synchronization with ETag (`If-None-Match`) support
|
||||||
|
//! - Transparent offline caching with atomic disk persistence
|
||||||
|
//! - Priority ordering: CoA Recommended / Verified modules always appear first
|
||||||
|
//! - Seamless deduplication by GitHub Repository ID and normalized slug
|
||||||
|
//! - Deep integration with the CoA Compatibility Overlay (`coa-modules-overlay.json`)
|
||||||
|
//! - Hard policy blocking to prevent installation of known crashers or security risks
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, HashSet};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::fsx;
|
||||||
|
|
||||||
|
pub const OFFICIAL_CATALOGUE_URL: &str = "https://www.azerothcore.org/data/catalogue.json";
|
||||||
|
pub const DEFAULT_CACHE_TTL_SECS: i64 = 12 * 3600; // 12 hours
|
||||||
|
const CONNECT_TIMEOUT_SECS: u64 = 10;
|
||||||
|
const READ_TIMEOUT_SECS: u64 = 25;
|
||||||
|
|
||||||
|
static CATALOGUE_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
static EMBEDDED_OVERLAY_JSON: &str = include_str!("coa-modules-overlay.json");
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// External Data Models (matching official AzerothCore JSON)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct OfficialCatalogueRaw {
|
||||||
|
#[serde(default)]
|
||||||
|
pub global_search: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub organizations: BTreeMap<String, BTreeMap<String, Vec<OfficialRepoRaw>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct OfficialRepoRaw {
|
||||||
|
pub id: u64,
|
||||||
|
pub name: String,
|
||||||
|
pub full_name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub description: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub stargazers_count: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub created_at: Option<String>,
|
||||||
|
#[serde(default = "default_branch_val")]
|
||||||
|
pub default_branch: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub owner: Option<OfficialOwnerRaw>,
|
||||||
|
pub html_url: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub forks_count: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub watchers_count: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub pushed_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub updated_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license: Option<OfficialLicenseRaw>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub topics: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_branch_val() -> String {
|
||||||
|
"master".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct OfficialOwnerRaw {
|
||||||
|
pub login: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub avatar_url: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub html_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct OfficialLicenseRaw {
|
||||||
|
#[serde(default)]
|
||||||
|
pub spdx_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// CoA Overlay Models
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CoaOverlayDocument {
|
||||||
|
pub version: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub rules: Vec<CoaOverlayRule>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CoaOverlayRule {
|
||||||
|
#[serde(default)]
|
||||||
|
pub repo_id: Option<u64>,
|
||||||
|
pub repo_slug: String,
|
||||||
|
pub status: CoaCompatibilityStatus,
|
||||||
|
#[serde(default)]
|
||||||
|
pub is_recommended: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub reason: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub tested_version: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub tested_abi: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
pub enum CoaCompatibilityStatus {
|
||||||
|
Recommended,
|
||||||
|
Verified,
|
||||||
|
RequiresAdapter,
|
||||||
|
Unverified,
|
||||||
|
Incompatible,
|
||||||
|
Blocked,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for CoaCompatibilityStatus {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Recommended => write!(f, "Recommended"),
|
||||||
|
Self::Verified => write!(f, "Verified"),
|
||||||
|
Self::RequiresAdapter => write!(f, "RequiresAdapter"),
|
||||||
|
Self::Unverified => write!(f, "Unverified"),
|
||||||
|
Self::Incompatible => write!(f, "Incompatible"),
|
||||||
|
Self::Blocked => write!(f, "Blocked"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Internal Normalized Item & API Response
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct PublicCatalogueItem {
|
||||||
|
pub id: u64,
|
||||||
|
pub name: String,
|
||||||
|
pub full_name: String,
|
||||||
|
pub owner: String,
|
||||||
|
pub html_url: String,
|
||||||
|
pub description: String,
|
||||||
|
pub stars: u32,
|
||||||
|
pub forks: u32,
|
||||||
|
pub default_branch: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub pushed_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub updated_at: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub topics: Vec<String>,
|
||||||
|
pub coa_status: CoaCompatibilityStatus,
|
||||||
|
pub coa_status_source: String, // "Overlay", "VerifiedCatalog", "AutoPublic"
|
||||||
|
pub conflict_reason: Option<String>,
|
||||||
|
pub is_coa_recommended: bool,
|
||||||
|
/// Functional category code (see `coa-module-categories.json`); "other" when nothing fits.
|
||||||
|
#[serde(default)]
|
||||||
|
pub category: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CategoryInfo {
|
||||||
|
pub code: String,
|
||||||
|
pub ru: String,
|
||||||
|
pub en: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub keywords: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct CategoryDocument {
|
||||||
|
categories: Vec<CategoryInfo>,
|
||||||
|
/// Owner-reviewed assignments (lowercase `owner/repo` -> category code).
|
||||||
|
repos: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static EMBEDDED_CATEGORIES_JSON: &str = include_str!("coa-module-categories.json");
|
||||||
|
|
||||||
|
fn category_document() -> &'static CategoryDocument {
|
||||||
|
static DOC: std::sync::OnceLock<CategoryDocument> = std::sync::OnceLock::new();
|
||||||
|
DOC.get_or_init(|| {
|
||||||
|
serde_json::from_str(EMBEDDED_CATEGORIES_JSON).unwrap_or(CategoryDocument { categories: Vec::new(), repos: BTreeMap::new() })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn categories() -> Vec<CategoryInfo> {
|
||||||
|
category_document().categories.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lowercase words of a text: letters and digits, so `mod-pvp-titles` gives `mod`, `pvp`, `titles`.
|
||||||
|
fn words(text: &str) -> Vec<String> {
|
||||||
|
text.to_lowercase()
|
||||||
|
.split(|c: char| !c.is_alphanumeric() && c != '+')
|
||||||
|
.filter(|w| !w.is_empty())
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyword_hits(keyword: &str, text_words: &[String]) -> usize {
|
||||||
|
let kw = words(keyword);
|
||||||
|
match kw.as_slice() {
|
||||||
|
[] => 0,
|
||||||
|
// one word: whole-word match; words of 4+ letters also match their plural or longer forms
|
||||||
|
[k] => text_words.iter().filter(|w| *w == k || (k.chars().count() >= 4 && w.starts_with(k.as_str()))).count(),
|
||||||
|
// a phrase: its words in a row
|
||||||
|
many => text_words.windows(many.len()).filter(|win| win.iter().zip(many).all(|(a, b)| a == b)).count(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The category of a module: the owner-reviewed list first, then the keywords of each category against the
|
||||||
|
/// repository's name (counted twice), description and topics; "other" when no keyword matches.
|
||||||
|
pub fn categorize(slug: &str, name: &str, description: &str, topics: &[String]) -> String {
|
||||||
|
let doc = category_document();
|
||||||
|
if let Some(code) = doc.repos.get(&normalize_repo_slug(slug)) {
|
||||||
|
return code.clone();
|
||||||
|
}
|
||||||
|
let name_words = words(name);
|
||||||
|
let mut body = words(description);
|
||||||
|
for t in topics.iter().filter(|t| !t.starts_with("azerothcore") && !matches!(t.as_str(), "wow" | "wotlk" | "world-of-warcraft")) {
|
||||||
|
body.extend(words(t));
|
||||||
|
}
|
||||||
|
let mut best: Option<(&str, usize)> = None;
|
||||||
|
for c in &doc.categories {
|
||||||
|
let score: usize = c.keywords.iter().map(|k| 2 * keyword_hits(k, &name_words) + keyword_hits(k, &body)).sum();
|
||||||
|
if score > 0 && best.is_none_or(|(_, s)| score > s) {
|
||||||
|
best = Some((&c.code, score));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best.map(|(c, _)| c.to_string()).unwrap_or_else(|| "other".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Statuses and categories come from the current overlay and category list on every read, never from what a
|
||||||
|
/// cache stored: a corrected overlay must show at once. Entries an earlier version made up for overlay rules the
|
||||||
|
/// public catalogue does not contain (marked with the `coa-verified` topic) are dropped.
|
||||||
|
fn finalize(items: Vec<PublicCatalogueItem>, overlay: &CoaOverlayDocument) -> Vec<PublicCatalogueItem> {
|
||||||
|
let rules: BTreeMap<String, &CoaOverlayRule> =
|
||||||
|
overlay.rules.iter().map(|r| (normalize_repo_slug(&r.repo_slug), r)).collect();
|
||||||
|
items
|
||||||
|
.into_iter()
|
||||||
|
.filter(|i| !i.topics.iter().any(|t| t == "coa-verified"))
|
||||||
|
.map(|mut i| {
|
||||||
|
let slug = normalize_repo_slug(&i.full_name);
|
||||||
|
match rules.get(&slug) {
|
||||||
|
Some(rule) => {
|
||||||
|
i.coa_status = rule.status;
|
||||||
|
i.coa_status_source = "Overlay".into();
|
||||||
|
i.conflict_reason = rule.reason.clone();
|
||||||
|
i.is_coa_recommended = rule.is_recommended || rule.status == CoaCompatibilityStatus::Recommended;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
i.coa_status = CoaCompatibilityStatus::Unverified;
|
||||||
|
i.coa_status_source = "AutoPublic".into();
|
||||||
|
i.conflict_reason = None;
|
||||||
|
i.is_coa_recommended = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i.category = categorize(&slug, &i.name, &i.description, &i.topics);
|
||||||
|
i
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn respond(items: Vec<PublicCatalogueItem>, overlay: &CoaOverlayDocument, cached_at: String, is_offline: bool, etag: Option<String>) -> PublicCatalogueResponse {
|
||||||
|
let items = finalize(items, overlay);
|
||||||
|
PublicCatalogueResponse {
|
||||||
|
total_count: items.len(),
|
||||||
|
recommended_count: items.iter().filter(|i| i.is_coa_recommended).count(),
|
||||||
|
cached_at,
|
||||||
|
is_offline,
|
||||||
|
etag,
|
||||||
|
items,
|
||||||
|
categories: categories().into_iter().map(|c| CategoryInfo { keywords: Vec::new(), ..c }).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Last push (`pushed_at`) of GitHub repositories given as `owner/name`, for modules the public catalogue does
|
||||||
|
/// not list. Kept in `cache_file` for 12 hours; a repository GitHub does not answer for is `None` and asked
|
||||||
|
/// again next time.
|
||||||
|
pub fn repo_last_push(cache_file: &Path, repos: &[String]) -> Result<BTreeMap<String, Option<String>>> {
|
||||||
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
|
struct Cache {
|
||||||
|
at: i64,
|
||||||
|
pushed: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
let now = Utc::now().timestamp();
|
||||||
|
let mut cache: Cache = fs::read(cache_file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||||
|
if now - cache.at > 12 * 3600 {
|
||||||
|
cache = Cache { at: now, pushed: BTreeMap::new() };
|
||||||
|
}
|
||||||
|
let name_ok = |s: Option<&str>| {
|
||||||
|
s.is_some_and(|s| !s.is_empty() && s.len() <= 100 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')))
|
||||||
|
};
|
||||||
|
let valid = |r: &str| {
|
||||||
|
let mut parts = r.split('/');
|
||||||
|
name_ok(parts.next()) && name_ok(parts.next()) && parts.next().is_none()
|
||||||
|
};
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
|
||||||
|
.timeout(Duration::from_secs(10))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
for repo in repos.iter().map(|r| r.trim().to_ascii_lowercase()).filter(|r| valid(r)) {
|
||||||
|
if let Some(v) = cache.pushed.get(&repo) {
|
||||||
|
out.insert(repo, Some(v.clone()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let pushed = client
|
||||||
|
.get(format!("https://api.github.com/repos/{repo}"))
|
||||||
|
.header(reqwest::header::USER_AGENT, "CSM-Modules-Preview")
|
||||||
|
.header(reqwest::header::ACCEPT, "application/vnd.github+json")
|
||||||
|
.send()
|
||||||
|
.ok()
|
||||||
|
.filter(|r| r.status().is_success())
|
||||||
|
.and_then(|r| r.text().ok())
|
||||||
|
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
|
||||||
|
.and_then(|v| v.get("pushed_at")?.as_str().map(str::to_string));
|
||||||
|
if let Some(p) = &pushed {
|
||||||
|
cache.pushed.insert(repo.clone(), p.clone());
|
||||||
|
}
|
||||||
|
out.insert(repo, pushed);
|
||||||
|
}
|
||||||
|
if let Some(dir) = cache_file.parent() {
|
||||||
|
let _ = fs::create_dir_all(dir);
|
||||||
|
}
|
||||||
|
let _ = fsx::atomic_write_json(cache_file, &cache);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CachedDocument {
|
||||||
|
pub schema_version: u32,
|
||||||
|
pub cached_at: String,
|
||||||
|
pub timestamp: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub etag: Option<String>,
|
||||||
|
pub items: Vec<PublicCatalogueItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PublicCatalogueResponse {
|
||||||
|
pub items: Vec<PublicCatalogueItem>,
|
||||||
|
pub cached_at: String,
|
||||||
|
pub is_offline: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub etag: Option<String>,
|
||||||
|
pub total_count: usize,
|
||||||
|
pub recommended_count: usize,
|
||||||
|
#[serde(default)]
|
||||||
|
pub categories: Vec<CategoryInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helper: Normalization of Slugs & URLs
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub fn normalize_repo_slug(url_or_slug: &str) -> String {
|
||||||
|
let mut s = url_or_slug.trim();
|
||||||
|
if let Some(pos) = s.find("://") {
|
||||||
|
s = &s[pos + 3..];
|
||||||
|
}
|
||||||
|
if let Some(pos) = s.find('@') {
|
||||||
|
if let Some(colon) = s[pos..].find(':') {
|
||||||
|
s = &s[pos + colon + 1..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(stripped) = s.strip_prefix("github.com/") {
|
||||||
|
s = stripped;
|
||||||
|
}
|
||||||
|
// Remove query params or fragments
|
||||||
|
if let Some(pos) = s.find('?') {
|
||||||
|
s = &s[..pos];
|
||||||
|
}
|
||||||
|
if let Some(pos) = s.find('#') {
|
||||||
|
s = &s[..pos];
|
||||||
|
}
|
||||||
|
// Remove tree/branches if present (e.g. repo/tree/branch/sub)
|
||||||
|
let parts: Vec<&str> = s.split('/').filter(|p| !p.is_empty()).collect();
|
||||||
|
if parts.len() >= 2 {
|
||||||
|
let owner = parts[0].to_ascii_lowercase();
|
||||||
|
let mut repo = parts[1].to_ascii_lowercase();
|
||||||
|
if repo.ends_with(".git") {
|
||||||
|
repo.truncate(repo.len() - 4);
|
||||||
|
}
|
||||||
|
format!("{owner}/{repo}")
|
||||||
|
} else {
|
||||||
|
s.trim_end_matches(".git").to_ascii_lowercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_coa_overlay(optional_overlay_path: Option<&Path>) -> CoaOverlayDocument {
|
||||||
|
let mut doc: CoaOverlayDocument = serde_json::from_str(EMBEDDED_OVERLAY_JSON)
|
||||||
|
.unwrap_or_else(|_| CoaOverlayDocument {
|
||||||
|
version: 1,
|
||||||
|
description: None,
|
||||||
|
rules: Vec::new(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Some(path) = optional_overlay_path {
|
||||||
|
if path.is_file() {
|
||||||
|
if let Ok(content) = fs::read_to_string(path) {
|
||||||
|
if let Ok(external) = serde_json::from_str::<CoaOverlayDocument>(&content) {
|
||||||
|
for ext_rule in external.rules {
|
||||||
|
if let Some(existing) = doc
|
||||||
|
.rules
|
||||||
|
.iter_mut()
|
||||||
|
.find(|r| normalize_repo_slug(&r.repo_slug) == normalize_repo_slug(&ext_rule.repo_slug))
|
||||||
|
{
|
||||||
|
*existing = ext_rule;
|
||||||
|
} else {
|
||||||
|
doc.rules.push(ext_rule);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
doc
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if a repository is explicitly blocked by CoA policy.
|
||||||
|
/// Returns `Some(reason)` if blocked, otherwise `None`.
|
||||||
|
pub fn is_blocked_repo(url_or_slug: &str) -> Option<String> {
|
||||||
|
let target = normalize_repo_slug(url_or_slug);
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
for rule in overlay.rules {
|
||||||
|
if rule.status == CoaCompatibilityStatus::Blocked && normalize_repo_slug(&rule.repo_slug) == target {
|
||||||
|
return Some(rule.reason.unwrap_or_else(|| "Module blocked by CoA stability/security policy.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Normalization & Deduplication Logic
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub fn normalize_catalogue(
|
||||||
|
raw: &OfficialCatalogueRaw,
|
||||||
|
overlay: &CoaOverlayDocument,
|
||||||
|
) -> Vec<PublicCatalogueItem> {
|
||||||
|
let mut normalized = Vec::new();
|
||||||
|
let mut seen_ids = HashSet::new();
|
||||||
|
let mut seen_slugs = HashSet::new();
|
||||||
|
|
||||||
|
// 1. Map overlay rules by slug for O(1) lookup
|
||||||
|
let mut overlay_map: BTreeMap<String, &CoaOverlayRule> = BTreeMap::new();
|
||||||
|
for rule in &overlay.rules {
|
||||||
|
overlay_map.insert(normalize_repo_slug(&rule.repo_slug), rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Extract repos from the category "azerothcore-module"
|
||||||
|
let mut repos = Vec::new();
|
||||||
|
for (_, topics) in &raw.organizations {
|
||||||
|
for (topic_name, list) in topics {
|
||||||
|
if topic_name == "azerothcore-module" {
|
||||||
|
repos.extend(list.iter());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If "azerothcore-module" was empty or structure differs, collect all modules
|
||||||
|
if repos.is_empty() {
|
||||||
|
for (_, topics) in &raw.organizations {
|
||||||
|
for (_, list) in topics {
|
||||||
|
repos.extend(list.iter());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Process and deduplicate
|
||||||
|
for repo in repos {
|
||||||
|
let slug = normalize_repo_slug(&repo.full_name);
|
||||||
|
|
||||||
|
if repo.id != 0 && !seen_ids.insert(repo.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !seen_slugs.insert(slug.clone()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let owner = repo
|
||||||
|
.owner
|
||||||
|
.as_ref()
|
||||||
|
.map(|o| o.login.clone())
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
slug.split('/').next().unwrap_or("unknown").to_string()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Determine CoA status from overlay or default to Unverified
|
||||||
|
let (coa_status, coa_source, reason, is_rec) = if let Some(rule) = overlay_map.get(&slug) {
|
||||||
|
(
|
||||||
|
rule.status,
|
||||||
|
"Overlay".to_string(),
|
||||||
|
rule.reason.clone(),
|
||||||
|
rule.is_recommended || rule.status == CoaCompatibilityStatus::Recommended,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
CoaCompatibilityStatus::Unverified,
|
||||||
|
"AutoPublic".to_string(),
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let license = repo.license.as_ref().and_then(|l| l.spdx_id.clone());
|
||||||
|
|
||||||
|
normalized.push(PublicCatalogueItem {
|
||||||
|
id: repo.id,
|
||||||
|
name: repo.name.clone(),
|
||||||
|
full_name: repo.full_name.clone(),
|
||||||
|
owner,
|
||||||
|
html_url: repo.html_url.clone(),
|
||||||
|
description: repo.description.clone().unwrap_or_default(),
|
||||||
|
stars: repo.stargazers_count,
|
||||||
|
forks: repo.forks_count,
|
||||||
|
default_branch: repo.default_branch.clone(),
|
||||||
|
pushed_at: repo.pushed_at.clone(),
|
||||||
|
updated_at: repo.updated_at.clone(),
|
||||||
|
license,
|
||||||
|
topics: repo.topics.clone(),
|
||||||
|
coa_status,
|
||||||
|
coa_status_source: coa_source,
|
||||||
|
conflict_reason: reason,
|
||||||
|
is_coa_recommended: is_rec,
|
||||||
|
category: String::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overlay rules for repositories the public catalogue does not list are not turned into entries: the
|
||||||
|
// catalogue shows only what azerothcore.org lists (CoA's own modules are in the Manager's curated list).
|
||||||
|
|
||||||
|
// 4. Sort:
|
||||||
|
// Group A (Recommended/Verified) first, then by Stars desc, then by pushed_at desc
|
||||||
|
normalized.sort_by(|a, b| {
|
||||||
|
// Priority 1: Recommended modules first
|
||||||
|
match (a.is_coa_recommended, b.is_coa_recommended) {
|
||||||
|
(true, false) => return std::cmp::Ordering::Less,
|
||||||
|
(false, true) => return std::cmp::Ordering::Greater,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
// Priority 2: Status order (Verified before Unverified, Blocked at end)
|
||||||
|
if a.coa_status != b.coa_status {
|
||||||
|
return a.coa_status.cmp(&b.coa_status);
|
||||||
|
}
|
||||||
|
// Priority 3: Stars descending
|
||||||
|
if b.stars != a.stars {
|
||||||
|
return b.stars.cmp(&a.stars);
|
||||||
|
}
|
||||||
|
// Priority 4: pushed_at descending
|
||||||
|
let pa = a.pushed_at.as_deref().unwrap_or("");
|
||||||
|
let pb = b.pushed_at.as_deref().unwrap_or("");
|
||||||
|
if pb != pa {
|
||||||
|
return pb.cmp(pa);
|
||||||
|
}
|
||||||
|
// Deterministic tie-breaker
|
||||||
|
a.full_name.cmp(&b.full_name)
|
||||||
|
});
|
||||||
|
|
||||||
|
normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Network Fetcher & Cache Manager
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub fn fetch_or_load_catalogue(
|
||||||
|
cache_dir: &Path,
|
||||||
|
force_refresh: bool,
|
||||||
|
) -> Result<PublicCatalogueResponse> {
|
||||||
|
let _guard = CATALOGUE_LOCK.lock().map_err(|_| {
|
||||||
|
Error::Invalid("Failed to acquire catalogue cache lock.".into())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
fs::create_dir_all(cache_dir)?;
|
||||||
|
let cache_file = cache_dir.join("catalogue_cache.json");
|
||||||
|
let etag_file = cache_dir.join("catalogue_etag.txt");
|
||||||
|
let overlay_path = cache_dir.join("coa-modules-overlay.json");
|
||||||
|
let overlay = load_coa_overlay(Some(&overlay_path));
|
||||||
|
|
||||||
|
let now_ts = Utc::now().timestamp();
|
||||||
|
|
||||||
|
// 1. Check if disk cache exists and is fresh
|
||||||
|
if !force_refresh && cache_file.is_file() {
|
||||||
|
if let Ok(content) = fs::read_to_string(&cache_file) {
|
||||||
|
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
||||||
|
let age = now_ts - cached.timestamp;
|
||||||
|
if age < DEFAULT_CACHE_TTL_SECS && !cached.items.is_empty() {
|
||||||
|
return Ok(respond(cached.items, &overlay, cached.cached_at, false, cached.etag));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Perform Network Fetch with ETag support
|
||||||
|
let stored_etag = fs::read_to_string(&etag_file).ok().map(|s| s.trim().to_string());
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
|
||||||
|
.timeout(Duration::from_secs(READ_TIMEOUT_SECS))
|
||||||
|
.redirect(reqwest::redirect::Policy::limited(5))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| Error::Invalid(format!("HTTP client initialization failed: {}", e)))?;
|
||||||
|
|
||||||
|
let mut request = client.get(OFFICIAL_CATALOGUE_URL)
|
||||||
|
.header(reqwest::header::USER_AGENT, "CSM-Modules-Preview/0.7.1");
|
||||||
|
|
||||||
|
if let Some(ref etag) = stored_etag {
|
||||||
|
if !force_refresh && cache_file.is_file() {
|
||||||
|
request = request.header(reqwest::header::IF_NONE_MATCH, etag.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let fetch_result = request.send();
|
||||||
|
|
||||||
|
match fetch_result {
|
||||||
|
Ok(response) => {
|
||||||
|
let status = response.status();
|
||||||
|
|
||||||
|
// 2.1 Handle 304 Not Modified
|
||||||
|
if status == reqwest::StatusCode::NOT_MODIFIED {
|
||||||
|
if cache_file.is_file() {
|
||||||
|
if let Ok(content) = fs::read_to_string(&cache_file) {
|
||||||
|
if let Ok(mut cached) = serde_json::from_str::<CachedDocument>(&content) {
|
||||||
|
cached.timestamp = now_ts;
|
||||||
|
cached.cached_at = Utc::now().to_rfc3339();
|
||||||
|
let _ = fsx::atomic_write_json(&cache_file, &cached);
|
||||||
|
return Ok(respond(cached.items, &overlay, cached.cached_at, false, cached.etag));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If 304 received but cache file was missing or corrupt, re-fetch without etag
|
||||||
|
return fetch_or_load_catalogue(cache_dir, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.2 Handle 200 OK
|
||||||
|
if status.is_success() {
|
||||||
|
let new_etag = response
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::ETAG)
|
||||||
|
.and_then(|h| h.to_str().ok())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
let text = response.text().map_err(|e| {
|
||||||
|
Error::Invalid(format!("Failed to read catalogue response body: {}", e))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let raw: OfficialCatalogueRaw = serde_json::from_str(&text).map_err(|e| {
|
||||||
|
Error::Invalid(format!("Failed to parse AzerothCore official catalogue JSON: {}", e))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let items = normalize_catalogue(&raw, &overlay);
|
||||||
|
let now_str = Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
let cached_doc = CachedDocument {
|
||||||
|
schema_version: 1,
|
||||||
|
cached_at: now_str.clone(),
|
||||||
|
timestamp: now_ts,
|
||||||
|
etag: new_etag.clone(),
|
||||||
|
items: items.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Persist cache and etag atomically
|
||||||
|
let _ = fsx::atomic_write_json(&cache_file, &cached_doc);
|
||||||
|
if let Some(ref tag) = new_etag {
|
||||||
|
let _ = fs::write(&etag_file, tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(respond(items, &overlay, now_str, false, new_etag));
|
||||||
|
}
|
||||||
|
|
||||||
|
// If non-200 and non-304 HTTP status, fallback to existing cache if available
|
||||||
|
try_offline_fallback(&cache_file, stored_etag, &overlay)
|
||||||
|
}
|
||||||
|
Err(_net_err) => {
|
||||||
|
// Network unreachable, DNS timeout, connection reset -> offline fallback
|
||||||
|
try_offline_fallback(&cache_file, stored_etag, &overlay)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_offline_fallback(
|
||||||
|
cache_file: &Path,
|
||||||
|
stored_etag: Option<String>,
|
||||||
|
overlay: &CoaOverlayDocument,
|
||||||
|
) -> Result<PublicCatalogueResponse> {
|
||||||
|
if cache_file.is_file() {
|
||||||
|
if let Ok(content) = fs::read_to_string(cache_file) {
|
||||||
|
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
||||||
|
return Ok(respond(cached.items, overlay, cached.cached_at, true, cached.etag.or(stored_etag)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If completely offline and no cache file exists, build minimal catalog from overlay rules
|
||||||
|
let empty_raw = OfficialCatalogueRaw {
|
||||||
|
global_search: false,
|
||||||
|
organizations: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
let items = normalize_catalogue(&empty_raw, overlay);
|
||||||
|
Ok(respond(items, overlay, Utc::now().to_rfc3339(), true, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Unit & Integration Tests
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
fn sample_official_json() -> &'static str {
|
||||||
|
r#"{
|
||||||
|
"global_search": true,
|
||||||
|
"organizations": {
|
||||||
|
"azerothcore": {
|
||||||
|
"azerothcore-module": [
|
||||||
|
{
|
||||||
|
"id": 101,
|
||||||
|
"name": "mod-npc-buffer",
|
||||||
|
"full_name": "azerothcore/mod-npc-buffer",
|
||||||
|
"description": "NPC buffer master",
|
||||||
|
"stargazers_count": 55,
|
||||||
|
"default_branch": "master",
|
||||||
|
"html_url": "https://github.com/azerothcore/mod-npc-buffer",
|
||||||
|
"forks_count": 12,
|
||||||
|
"watchers_count": 55,
|
||||||
|
"pushed_at": "2026-10-10T12:00:00Z",
|
||||||
|
"updated_at": "2026-10-10T12:00:00Z",
|
||||||
|
"license": { "spdx_id": "AGPL-3.0" },
|
||||||
|
"topics": ["azerothcore-module", "utility"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 102,
|
||||||
|
"name": "mod-random-community",
|
||||||
|
"full_name": "author/mod-random-community",
|
||||||
|
"description": "A community module",
|
||||||
|
"stargazers_count": 120,
|
||||||
|
"default_branch": "main",
|
||||||
|
"html_url": "https://github.com/author/mod-random-community",
|
||||||
|
"forks_count": 5,
|
||||||
|
"watchers_count": 120,
|
||||||
|
"pushed_at": "2026-09-01T12:00:00Z",
|
||||||
|
"updated_at": "2026-09-01T12:00:00Z",
|
||||||
|
"license": null,
|
||||||
|
"topics": ["azerothcore-module"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 103,
|
||||||
|
"name": "mod-learn-spells",
|
||||||
|
"full_name": "azerothcore/mod-learn-spells",
|
||||||
|
"description": "Auto teach spells",
|
||||||
|
"stargazers_count": 48,
|
||||||
|
"default_branch": "master",
|
||||||
|
"html_url": "https://github.com/azerothcore/mod-learn-spells",
|
||||||
|
"forks_count": 8,
|
||||||
|
"watchers_count": 48,
|
||||||
|
"pushed_at": "2026-08-01T12:00:00Z",
|
||||||
|
"updated_at": "2026-08-01T12:00:00Z",
|
||||||
|
"license": { "spdx_id": "AGPL-3.0" },
|
||||||
|
"topics": ["azerothcore-module"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 104,
|
||||||
|
"name": "mod-ahbot",
|
||||||
|
"full_name": "azerothcore/mod-ahbot",
|
||||||
|
"description": "Upstream ahbot",
|
||||||
|
"stargazers_count": 80,
|
||||||
|
"default_branch": "master",
|
||||||
|
"html_url": "https://github.com/azerothcore/mod-ahbot",
|
||||||
|
"forks_count": 20,
|
||||||
|
"watchers_count": 80,
|
||||||
|
"pushed_at": "2026-07-01T12:00:00Z",
|
||||||
|
"updated_at": "2026-07-01T12:00:00Z",
|
||||||
|
"license": null,
|
||||||
|
"topics": ["azerothcore-module"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 101,
|
||||||
|
"name": "mod-npc-buffer-duplicate",
|
||||||
|
"full_name": "azerothcore/mod-npc-buffer",
|
||||||
|
"description": "Duplicate entry with same id and slug",
|
||||||
|
"stargazers_count": 55,
|
||||||
|
"default_branch": "master",
|
||||||
|
"html_url": "https://github.com/azerothcore/mod-npc-buffer",
|
||||||
|
"forks_count": 12,
|
||||||
|
"watchers_count": 55,
|
||||||
|
"pushed_at": "2026-10-10T12:00:00Z",
|
||||||
|
"updated_at": "2026-10-10T12:00:00Z",
|
||||||
|
"license": { "spdx_id": "AGPL-3.0" },
|
||||||
|
"topics": ["azerothcore-module"]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"azerothcore-lua": [
|
||||||
|
{
|
||||||
|
"id": 201,
|
||||||
|
"name": "pure-lua-script",
|
||||||
|
"full_name": "some/pure-lua-script",
|
||||||
|
"stargazers_count": 10,
|
||||||
|
"default_branch": "main",
|
||||||
|
"html_url": "https://github.com/some/pure-lua-script"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"#
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_slug_normalization() {
|
||||||
|
assert_eq!(normalize_repo_slug("https://github.com/azerothcore/mod-npc-buffer.git"), "azerothcore/mod-npc-buffer");
|
||||||
|
assert_eq!(normalize_repo_slug("https://github.com/AzerothCore/Mod-NPC-Buffer/"), "azerothcore/mod-npc-buffer");
|
||||||
|
assert_eq!(normalize_repo_slug("git@github.com:Corfirean/mod-coa-playerbots.git"), "corfirean/mod-coa-playerbots");
|
||||||
|
assert_eq!(normalize_repo_slug("author/repo"), "author/repo");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_overlay_loading_and_blocked_detection() {
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
assert!(!overlay.rules.is_empty(), "Embedded overlay must contain rules");
|
||||||
|
|
||||||
|
// Verify mod-ahbot is blocked
|
||||||
|
assert!(is_blocked_repo("https://github.com/azerothcore/mod-ahbot").is_some());
|
||||||
|
assert!(is_blocked_repo("azerothcore/mod-ahbot").is_some());
|
||||||
|
|
||||||
|
// Verify clean repo is not blocked
|
||||||
|
assert!(is_blocked_repo("https://github.com/azerothcore/mod-npc-buffer").is_none());
|
||||||
|
assert!(is_blocked_repo("random-author/clean-module").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_official_json_parsing_and_normalization() {
|
||||||
|
let raw: OfficialCatalogueRaw = serde_json::from_str(sample_official_json()).expect("Must parse sample JSON");
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
let items = normalize_catalogue(&raw, &overlay);
|
||||||
|
|
||||||
|
// Deduplication: id 101 was duplicated, should only appear once
|
||||||
|
let buffer_count = items.iter().filter(|i| i.full_name == "azerothcore/mod-npc-buffer").count();
|
||||||
|
assert_eq!(buffer_count, 1, "Duplicate repo with ID 101 must be deduplicated");
|
||||||
|
|
||||||
|
// Check statuses assigned via overlay
|
||||||
|
let buffer = items.iter().find(|i| i.full_name == "azerothcore/mod-npc-buffer").expect("mod-npc-buffer must exist");
|
||||||
|
assert_eq!(buffer.coa_status, CoaCompatibilityStatus::Verified);
|
||||||
|
assert!(buffer.is_coa_recommended);
|
||||||
|
|
||||||
|
let learn_spells = items.iter().find(|i| i.full_name == "azerothcore/mod-learn-spells").expect("mod-learn-spells must exist");
|
||||||
|
assert_eq!(learn_spells.coa_status, CoaCompatibilityStatus::Incompatible);
|
||||||
|
assert!(!learn_spells.is_coa_recommended);
|
||||||
|
assert!(learn_spells.conflict_reason.is_some());
|
||||||
|
|
||||||
|
let ahbot = items.iter().find(|i| i.full_name == "azerothcore/mod-ahbot").expect("mod-ahbot must exist");
|
||||||
|
assert_eq!(ahbot.coa_status, CoaCompatibilityStatus::Blocked);
|
||||||
|
|
||||||
|
let community = items.iter().find(|i| i.full_name == "author/mod-random-community").expect("community module must exist");
|
||||||
|
assert_eq!(community.coa_status, CoaCompatibilityStatus::Unverified);
|
||||||
|
assert_eq!(community.coa_status_source, "AutoPublic");
|
||||||
|
assert!(!community.is_coa_recommended);
|
||||||
|
|
||||||
|
// Check priority sorting: Recommended modules must come first
|
||||||
|
let first_non_rec_idx = items.iter().position(|i| !i.is_coa_recommended).unwrap_or(items.len());
|
||||||
|
for (idx, item) in items.iter().enumerate() {
|
||||||
|
if idx < first_non_rec_idx {
|
||||||
|
assert!(item.is_coa_recommended, "Items before boundary must be recommended");
|
||||||
|
} else {
|
||||||
|
assert!(!item.is_coa_recommended, "Items after boundary must not be recommended");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_disk_caching_and_offline_fallback() {
|
||||||
|
let d = tempdir().expect("tempdir");
|
||||||
|
let cache_dir = d.path();
|
||||||
|
|
||||||
|
// 1. Manually write a cached document
|
||||||
|
let items = vec![
|
||||||
|
PublicCatalogueItem {
|
||||||
|
id: 999,
|
||||||
|
name: "cached-mod".into(),
|
||||||
|
full_name: "test/cached-mod".into(),
|
||||||
|
owner: "test".into(),
|
||||||
|
html_url: "https://github.com/test/cached-mod".into(),
|
||||||
|
description: "Test description".into(),
|
||||||
|
stars: 42,
|
||||||
|
forks: 2,
|
||||||
|
default_branch: "master".into(),
|
||||||
|
pushed_at: Some("2026-10-01T00:00:00Z".into()),
|
||||||
|
updated_at: Some("2026-10-01T00:00:00Z".into()),
|
||||||
|
license: Some("MIT".into()),
|
||||||
|
topics: vec!["azerothcore-module".into()],
|
||||||
|
coa_status: CoaCompatibilityStatus::Unverified,
|
||||||
|
coa_status_source: "CacheTest".into(),
|
||||||
|
conflict_reason: None,
|
||||||
|
is_coa_recommended: false,
|
||||||
|
category: String::new(),
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
let cached_doc = CachedDocument {
|
||||||
|
schema_version: 1,
|
||||||
|
cached_at: Utc::now().to_rfc3339(),
|
||||||
|
timestamp: Utc::now().timestamp(),
|
||||||
|
etag: Some("\"sample-etag\"".into()),
|
||||||
|
items: items.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let cache_file = cache_dir.join("catalogue_cache.json");
|
||||||
|
fsx::atomic_write_json(&cache_file, &cached_doc).expect("write cache");
|
||||||
|
|
||||||
|
// 2. Read without force refresh -> should return cached doc instantly without network
|
||||||
|
let resp = fetch_or_load_catalogue(cache_dir, false).expect("load from cache");
|
||||||
|
assert_eq!(resp.total_count, 1);
|
||||||
|
assert_eq!(resp.items[0].name, "cached-mod");
|
||||||
|
assert!(!resp.is_offline);
|
||||||
|
|
||||||
|
// 3. Corrupt the cache file -> test resilience
|
||||||
|
fs::write(&cache_file, b"NOT_A_VALID_JSON").expect("write corrupt cache");
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
let fallback_resp = try_offline_fallback(&cache_file, None, &overlay).expect("fallback must succeed");
|
||||||
|
assert!(fallback_resp.is_offline);
|
||||||
|
// nothing is made up from overlay rules when there is no catalogue to show
|
||||||
|
assert!(fallback_resp.items.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item(full_name: &str, name: &str, description: &str, topics: &[&str]) -> PublicCatalogueItem {
|
||||||
|
PublicCatalogueItem {
|
||||||
|
id: 1,
|
||||||
|
name: name.into(),
|
||||||
|
full_name: full_name.into(),
|
||||||
|
owner: full_name.split('/').next().unwrap().into(),
|
||||||
|
html_url: format!("https://github.com/{full_name}"),
|
||||||
|
description: description.into(),
|
||||||
|
stars: 0,
|
||||||
|
forks: 0,
|
||||||
|
default_branch: "master".into(),
|
||||||
|
pushed_at: None,
|
||||||
|
updated_at: None,
|
||||||
|
license: None,
|
||||||
|
topics: topics.iter().map(|t| t.to_string()).collect(),
|
||||||
|
coa_status: CoaCompatibilityStatus::Verified,
|
||||||
|
coa_status_source: "Overlay".into(),
|
||||||
|
conflict_reason: Some("stale".into()),
|
||||||
|
is_coa_recommended: true,
|
||||||
|
category: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn statuses_come_from_the_current_overlay_not_the_cache_and_made_up_entries_are_dropped() {
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
let cached = vec![
|
||||||
|
item("azerothcore/mod-duel-reset", "mod-duel-reset", "Duel reset module", &["azerothcore-module"]),
|
||||||
|
item("azerothcore/mod-cfbg", "mod-cfbg", "Cross-faction battlegrounds", &["azerothcore-module", "coa-verified"]),
|
||||||
|
];
|
||||||
|
let out = finalize(cached, &overlay);
|
||||||
|
assert_eq!(out.len(), 1, "the made-up mod-cfbg entry is dropped");
|
||||||
|
assert_eq!(out[0].coa_status, CoaCompatibilityStatus::Unverified);
|
||||||
|
assert!(out[0].conflict_reason.is_none() && !out[0].is_coa_recommended);
|
||||||
|
assert_eq!(out[0].category, "pvp");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modules_get_a_category_from_the_reviewed_list_or_keywords() {
|
||||||
|
// reviewed list (the owner's file)
|
||||||
|
assert_eq!(categorize("DustinHendrickson/mod-ollama-chat", "mod-ollama-chat", "", &[]), "bots");
|
||||||
|
// keywords: whole words, not parts of other words
|
||||||
|
assert_eq!(categorize("x/mod-arena-points", "mod-arena-points", "Gives arena points", &[]), "pvp");
|
||||||
|
assert_eq!(categorize("x/mod-guild-chat", "mod-guild-chat", "", &[]), "social");
|
||||||
|
assert_eq!(categorize("x/mod-maintain", "mod-maintain", "Maintains things", &[]), "other");
|
||||||
|
assert_eq!(categorize("x/mod-nothing", "mod-nothing", "", &["azerothcore-module".to_string(), "wotlk".to_string()]), "other");
|
||||||
|
assert!(categories().iter().any(|c| c.code == "other"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,14 +21,19 @@ pub struct Envelope {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
|
pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
|
||||||
|
verify_with(bytes, channel, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pointer must carry its own channel key's signature, never the other one.
|
||||||
|
fn verify_with(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
|
||||||
let envelope: Envelope =
|
let envelope: Envelope =
|
||||||
serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||||
crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?;
|
crate::signing::verify_exact(envelope.payload.as_bytes(), &envelope.signature, key)?;
|
||||||
let pointer: Pointer = serde_json::from_str(&envelope.payload)
|
let pointer: Pointer = serde_json::from_str(&envelope.payload)
|
||||||
.map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
.map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||||
if pointer.schema != 1
|
if pointer.schema != 1
|
||||||
|| pointer.channel != channel
|
|| pointer.channel != channel
|
||||||
|| pointer.release_tag != format!("server-{}", pointer.version)
|
|| pointer.release_tag != release_tag(channel, &pointer.version)
|
||||||
|| pointer.version.is_empty()
|
|| pointer.version.is_empty()
|
||||||
|| !pointer
|
|| !pointer
|
||||||
.version
|
.version
|
||||||
@@ -42,20 +47,60 @@ pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
|
|||||||
Ok(pointer)
|
Ok(pointer)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resolve(channel: &str) -> Result<Source> {
|
/// The release a channel's packages are published under: `server-<v>`, or `preview-server-<v>` for the
|
||||||
if channel != "stable" && channel != "edge" {
|
/// Modules Preview (pre-releases that never become the repository's latest release).
|
||||||
return Err(Error::InvalidManifest("Unknown release channel".into()));
|
pub fn release_tag(channel: &str, version: &str) -> String {
|
||||||
|
if channel == "preview" {
|
||||||
|
format!("preview-server-{version}")
|
||||||
|
} else {
|
||||||
|
format!("server-{version}")
|
||||||
}
|
}
|
||||||
let source =
|
}
|
||||||
Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
|
|
||||||
|
/// Where a channel's pointer lives and which key signs it. The preview channel has its own branch and
|
||||||
|
/// key, so publishing it can never move a stable or edge pointer.
|
||||||
|
fn channel_home(channel: &str) -> Result<(&'static str, &'static str)> {
|
||||||
|
match channel {
|
||||||
|
"stable" | "edge" => Ok(("channels", crate::signing::EMBEDDED_PUBLIC_KEY)),
|
||||||
|
"preview" => Ok(("preview-channels", crate::signing::PREVIEW_PUBLIC_KEY)),
|
||||||
|
_ => Err(Error::InvalidManifest("Unknown release channel".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve(channel: &str) -> Result<Source> {
|
||||||
|
let (branch, key) = channel_home(channel)?;
|
||||||
|
let source = Source::Url(format!("https://raw.githubusercontent.com/Corfirean/coa-server-build/{branch}"));
|
||||||
let bytes = fetch_small(&source, &format!("{channel}.json"))?;
|
let bytes = fetch_small(&source, &format!("{channel}.json"))?;
|
||||||
let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
|
let pointer = verify_with(&bytes, channel, key)?;
|
||||||
Ok(Source::Url(format!(
|
Ok(Source::Url(format!(
|
||||||
"https://github.com/Corfirean/coa-server-build/releases/download/{}",
|
"https://github.com/Corfirean/coa-server-build/releases/download/{}",
|
||||||
pointer.release_tag
|
pointer.release_tag
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The stable release used when the stable pointer has not been published yet.
|
||||||
|
pub const STABLE_FALLBACK_URL: &str =
|
||||||
|
"https://github.com/Corfirean/coa-server-build/releases/download/stable";
|
||||||
|
|
||||||
|
/// Stable updates and installation images: the signed stable pointer, else the fixed stable release.
|
||||||
|
pub fn stable_source() -> Result<Source> {
|
||||||
|
match resolve("stable") {
|
||||||
|
Ok(source) => Ok(source),
|
||||||
|
Err(Error::PackageNotPublished(_)) => Ok(Source::Url(STABLE_FALLBACK_URL.into())),
|
||||||
|
Err(error) => Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the Modules Preview Manager looks for server updates when none is chosen: its own signed channel,
|
||||||
|
/// or the stable channel until a preview exists (a stable server is where every preview server starts).
|
||||||
|
pub fn preview_update_source() -> Result<Source> {
|
||||||
|
match resolve("preview") {
|
||||||
|
Ok(source) => Ok(source),
|
||||||
|
Err(Error::PackageNotPublished(_)) => stable_source(),
|
||||||
|
Err(error) => Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
|
pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
|
||||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
use ed25519_dalek::{Signer, SigningKey};
|
use ed25519_dalek::{Signer, SigningKey};
|
||||||
@@ -75,7 +120,7 @@ pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
|
|||||||
verify(
|
verify(
|
||||||
&bytes,
|
&bytes,
|
||||||
&pointer.channel,
|
&pointer.channel,
|
||||||
crate::signing::EMBEDDED_PUBLIC_KEY,
|
channel_home(&pointer.channel)?.1,
|
||||||
)?;
|
)?;
|
||||||
Ok(bytes)
|
Ok(bytes)
|
||||||
}
|
}
|
||||||
@@ -115,4 +160,41 @@ mod tests {
|
|||||||
let (bytes, key) = signed(&p);
|
let (bytes, key) = signed(&p);
|
||||||
assert!(verify(&bytes, "stable", &key).is_err());
|
assert!(verify(&bytes, "stable", &key).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preview_pointers_name_preview_releases_and_live_apart_from_stable() {
|
||||||
|
let p = Pointer {
|
||||||
|
schema: 1,
|
||||||
|
channel: "preview".into(),
|
||||||
|
version: "0.261105.1".into(),
|
||||||
|
release_tag: "preview-server-0.261105.1".into(),
|
||||||
|
snapshot: "b".repeat(64),
|
||||||
|
};
|
||||||
|
let (bytes, key) = signed(&p);
|
||||||
|
assert_eq!(verify(&bytes, "preview", &key).unwrap().release_tag, "preview-server-0.261105.1");
|
||||||
|
// A preview pointer is not a stable one, and a stable-style tag is not a preview release.
|
||||||
|
assert!(verify(&bytes, "stable", &key).is_err());
|
||||||
|
let stable_tag = Pointer { release_tag: "server-0.261105.1".into(), ..p };
|
||||||
|
let (bytes, key) = signed(&stable_tag);
|
||||||
|
assert!(verify(&bytes, "preview", &key).is_err());
|
||||||
|
assert_eq!(channel_home("preview").unwrap().0, "preview-channels");
|
||||||
|
assert_eq!(channel_home("stable").unwrap().0, "channels");
|
||||||
|
assert!(channel_home("nightly").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_channel_pointer_needs_its_own_key() {
|
||||||
|
// A pointer signed by some other key (here: not the embedded stable key) fails under the stable key
|
||||||
|
// even though the app also trusts the preview key for packages.
|
||||||
|
let p = Pointer {
|
||||||
|
schema: 1,
|
||||||
|
channel: "stable".into(),
|
||||||
|
version: "0.261105.2".into(),
|
||||||
|
release_tag: "server-0.261105.2".into(),
|
||||||
|
snapshot: "c".repeat(64),
|
||||||
|
};
|
||||||
|
let (bytes, _) = signed(&p);
|
||||||
|
assert!(verify_with(&bytes, "stable", crate::signing::EMBEDDED_PUBLIC_KEY).is_err());
|
||||||
|
assert!(verify_with(&bytes, "preview", crate::signing::PREVIEW_PUBLIC_KEY).is_err());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,8 @@ use crate::fsx;
|
|||||||
pub use crate::glue_config;
|
pub use crate::glue_config;
|
||||||
|
|
||||||
pub const ADDON_NAME: &str = "CoABotUI";
|
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 {
|
pub fn is_running(client: &Path) -> bool {
|
||||||
if crate::platform::flavor() == crate::platform::Flavor::Docker {
|
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> {
|
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(
|
fn sync_realm_when_closed(
|
||||||
client: &Path,
|
client: &Path,
|
||||||
meta: &Path,
|
meta: &Path,
|
||||||
mode: crate::realms::Mode,
|
realm: &str,
|
||||||
running: bool,
|
running: bool,
|
||||||
) -> Result<bool> {
|
) -> Result<bool> {
|
||||||
if running {
|
if running {
|
||||||
@@ -89,11 +100,6 @@ fn sync_realm_when_closed(
|
|||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
|
||||||
Err(e) => return Err(e.into()),
|
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);
|
let new = realm_config(&old, realm);
|
||||||
if new == old {
|
if new == old {
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
@@ -409,6 +415,38 @@ pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
|
|||||||
Ok(())
|
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.
|
/// Start the game client. The caller is responsible for making sure the server is ready first.
|
||||||
pub fn launch(client: &Path) -> Result<u32> {
|
pub fn launch(client: &Path) -> Result<u32> {
|
||||||
let exe =
|
let exe =
|
||||||
@@ -607,6 +645,23 @@ pub fn recover_all_realmlist_overrides(meta_roots: &[PathBuf]) -> usize {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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)]
|
#[cfg(windows)]
|
||||||
#[test]
|
#[test]
|
||||||
@@ -677,10 +732,10 @@ mod tests {
|
|||||||
let meta = d.path().join("meta");
|
let meta = d.path().join("meta");
|
||||||
let original = b"SET realmName \"Wildcard\"\n";
|
let original = b"SET realmName \"Wildcard\"\n";
|
||||||
fs::write(c.join("WTF/Config.wtf"), original).unwrap();
|
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_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
|
||||||
assert!(!backup_dir(&meta).exists());
|
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!(
|
assert_eq!(
|
||||||
fs::read(c.join("WTF/Config.wtf")).unwrap(),
|
fs::read(c.join("WTF/Config.wtf")).unwrap(),
|
||||||
b"SET realmName \"Conquest of Azeroth\"\n"
|
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,
|
bytes_per_sec: 0,
|
||||||
file: Some(f.path.clone()),
|
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 path = fsx::safe_join(client, &f.path)?;
|
||||||
let meta = match fs::metadata(&path) {
|
let meta = match fs::metadata(&path) {
|
||||||
Ok(meta) if meta.is_file() => meta,
|
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();
|
let mut todo = Vec::new();
|
||||||
for item in &a.plan.items {
|
for item in &a.plan.items {
|
||||||
|
if crate::client_graphics::disabled(a.client, &item.path)? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if item.kind == Kind::Modified && a.keep_modified {
|
if item.kind == Kind::Modified && a.keep_modified {
|
||||||
let path = fsx::safe_join(a.client, &item.path)?;
|
let path = fsx::safe_join(a.client, &item.path)?;
|
||||||
let meta = fs::metadata(&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]
|
#[test]
|
||||||
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
|
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
|
||||||
let d = tempfile::tempdir().unwrap();
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -0,0 +1,473 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"source": "azerothcore_catalogue_categorized_2026-11-07.xlsx (owner), modules with high or medium confidence",
|
||||||
|
"categories": [
|
||||||
|
{
|
||||||
|
"code": "bots",
|
||||||
|
"ru": "Боты и искусственный интеллект",
|
||||||
|
"en": "Bots and AI",
|
||||||
|
"keywords": [
|
||||||
|
"playerbots",
|
||||||
|
"bots",
|
||||||
|
"npcbot",
|
||||||
|
"llm",
|
||||||
|
"ollama",
|
||||||
|
"ai",
|
||||||
|
"автономные спутники"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "pve",
|
||||||
|
"ru": "PvE, подземелья и рейды",
|
||||||
|
"en": "PvE, dungeons and raids",
|
||||||
|
"keywords": [
|
||||||
|
"pve",
|
||||||
|
"dungeon",
|
||||||
|
"raid",
|
||||||
|
"boss",
|
||||||
|
"mythic+",
|
||||||
|
"scaling",
|
||||||
|
"rdf",
|
||||||
|
"инстансы"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "pvp",
|
||||||
|
"ru": "PvP, арены и поля боя",
|
||||||
|
"en": "PvP, arenas and battlegrounds",
|
||||||
|
"keywords": [
|
||||||
|
"pvp",
|
||||||
|
"arena",
|
||||||
|
"battleground",
|
||||||
|
"bg",
|
||||||
|
"duel",
|
||||||
|
"ffa",
|
||||||
|
"фракции"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "hardcore",
|
||||||
|
"ru": "Hardcore и режимы сложности",
|
||||||
|
"en": "Hardcore and difficulty",
|
||||||
|
"keywords": [
|
||||||
|
"hardcore",
|
||||||
|
"ironman",
|
||||||
|
"permadeath",
|
||||||
|
"high risk",
|
||||||
|
"difficulty"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "progression",
|
||||||
|
"ru": "Прокачка и прогрессия",
|
||||||
|
"en": "Leveling and progression",
|
||||||
|
"keywords": [
|
||||||
|
"xp",
|
||||||
|
"level",
|
||||||
|
"rates",
|
||||||
|
"leveling",
|
||||||
|
"rewards",
|
||||||
|
"prestige",
|
||||||
|
"progression",
|
||||||
|
"experience",
|
||||||
|
"reputation",
|
||||||
|
"rested"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "classes",
|
||||||
|
"ru": "Классы, расы и способности",
|
||||||
|
"en": "Classes, races and abilities",
|
||||||
|
"keywords": [
|
||||||
|
"race",
|
||||||
|
"class",
|
||||||
|
"talent",
|
||||||
|
"spells",
|
||||||
|
"specialization",
|
||||||
|
"pets"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "cosmetics",
|
||||||
|
"ru": "Косметика и трансмог",
|
||||||
|
"en": "Cosmetics and transmog",
|
||||||
|
"keywords": [
|
||||||
|
"transmog",
|
||||||
|
"appearance",
|
||||||
|
"morph",
|
||||||
|
"visual",
|
||||||
|
"vanity",
|
||||||
|
"cosmetics"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "items",
|
||||||
|
"ru": "Лут, предметы и экипировка",
|
||||||
|
"en": "Loot, items and gear",
|
||||||
|
"keywords": [
|
||||||
|
"loot",
|
||||||
|
"item",
|
||||||
|
"gear",
|
||||||
|
"enchant",
|
||||||
|
"reforging",
|
||||||
|
"bank",
|
||||||
|
"inventory",
|
||||||
|
"items",
|
||||||
|
"reagent"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "economy",
|
||||||
|
"ru": "Торговля, экономика и профессии",
|
||||||
|
"en": "Trade, economy and professions",
|
||||||
|
"keywords": [
|
||||||
|
"auction",
|
||||||
|
"market",
|
||||||
|
"vendor",
|
||||||
|
"trade",
|
||||||
|
"gold",
|
||||||
|
"shop",
|
||||||
|
"profession",
|
||||||
|
"ahbot",
|
||||||
|
"auction house",
|
||||||
|
"gather",
|
||||||
|
"herbs",
|
||||||
|
"mining",
|
||||||
|
"fishing",
|
||||||
|
"crafting"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "account",
|
||||||
|
"ru": "Аккаунты и персонажи",
|
||||||
|
"en": "Accounts and characters",
|
||||||
|
"keywords": [
|
||||||
|
"account",
|
||||||
|
"character",
|
||||||
|
"mounts",
|
||||||
|
"collection",
|
||||||
|
"migration",
|
||||||
|
"recruit",
|
||||||
|
"login",
|
||||||
|
"alts"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "social",
|
||||||
|
"ru": "Гильдии, чат и социальные",
|
||||||
|
"en": "Guilds, chat and social",
|
||||||
|
"keywords": [
|
||||||
|
"guild",
|
||||||
|
"chat",
|
||||||
|
"messages",
|
||||||
|
"announcements",
|
||||||
|
"friends",
|
||||||
|
"mail"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "npc",
|
||||||
|
"ru": "NPC и игровые сервисы",
|
||||||
|
"en": "NPCs and services",
|
||||||
|
"keywords": [
|
||||||
|
"npc",
|
||||||
|
"buffer",
|
||||||
|
"trainer",
|
||||||
|
"enchanter",
|
||||||
|
"services",
|
||||||
|
"assistant",
|
||||||
|
"vendor npc",
|
||||||
|
"gossip"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "world",
|
||||||
|
"ru": "Мир, зоны и перемещение",
|
||||||
|
"en": "World, zones and travel",
|
||||||
|
"keywords": [
|
||||||
|
"world",
|
||||||
|
"zone",
|
||||||
|
"spawn",
|
||||||
|
"teleport",
|
||||||
|
"portal",
|
||||||
|
"travel",
|
||||||
|
"respawn"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "events",
|
||||||
|
"ru": "События и мини-игры",
|
||||||
|
"en": "Events and mini-games",
|
||||||
|
"keywords": [
|
||||||
|
"events",
|
||||||
|
"holidays",
|
||||||
|
"quests",
|
||||||
|
"trivia",
|
||||||
|
"minigames",
|
||||||
|
"treasure"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "server",
|
||||||
|
"ru": "Сервер, хостинг и автоматизация",
|
||||||
|
"en": "Server and automation",
|
||||||
|
"keywords": [
|
||||||
|
"server",
|
||||||
|
"deployment",
|
||||||
|
"backup",
|
||||||
|
"cache",
|
||||||
|
"relay",
|
||||||
|
"restart",
|
||||||
|
"monitoring"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "admin",
|
||||||
|
"ru": "Администрирование и безопасность",
|
||||||
|
"en": "Administration and security",
|
||||||
|
"keywords": [
|
||||||
|
"gm",
|
||||||
|
"admin",
|
||||||
|
"moderation",
|
||||||
|
"logs",
|
||||||
|
"security",
|
||||||
|
"bans",
|
||||||
|
"abuse"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "web",
|
||||||
|
"ru": "Сайты, API и интеграции",
|
||||||
|
"en": "Websites, API and integrations",
|
||||||
|
"keywords": [
|
||||||
|
"api",
|
||||||
|
"cms",
|
||||||
|
"website",
|
||||||
|
"discord",
|
||||||
|
"telegram",
|
||||||
|
"web",
|
||||||
|
"metrics"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "dev",
|
||||||
|
"ru": "Разработка, SQL и инструменты",
|
||||||
|
"en": "Development, SQL and tools",
|
||||||
|
"keywords": [
|
||||||
|
"editor",
|
||||||
|
"db",
|
||||||
|
"sql",
|
||||||
|
"lua",
|
||||||
|
"eluna",
|
||||||
|
"ide",
|
||||||
|
"tooling",
|
||||||
|
"sdk"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "client",
|
||||||
|
"ru": "Клиент, патчи и интерфейс",
|
||||||
|
"en": "Client, patches and UI",
|
||||||
|
"keywords": [
|
||||||
|
"client",
|
||||||
|
"patch",
|
||||||
|
"addon",
|
||||||
|
"ui",
|
||||||
|
"launcher",
|
||||||
|
"controller",
|
||||||
|
"mpq"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "other",
|
||||||
|
"ru": "Прочее",
|
||||||
|
"en": "Other",
|
||||||
|
"keywords": [
|
||||||
|
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"repos": {
|
||||||
|
"liyunfan1223/mod-playerbots": "bots",
|
||||||
|
"dustinhendrickson/mod-ollama-chat": "bots",
|
||||||
|
"dustinhendrickson/mod-player-bot-level-brackets": "bots",
|
||||||
|
"dustinhendrickson/mod-ollama-bot-buddy": "bots",
|
||||||
|
"azerothcore/mod-autobalance": "pve",
|
||||||
|
"zhengpeiru21/mod-challenge-modes": "pve",
|
||||||
|
"anchydev/dungeonrespawn": "pve",
|
||||||
|
"azerothcore/mod-rdf-expansion": "pve",
|
||||||
|
"silviu20092/mod-mythic-plus": "pve",
|
||||||
|
"avarishd/mod-brawlers-guild": "pve",
|
||||||
|
"sogladev/mod-vanilla-naxxramas": "pve",
|
||||||
|
"pangolp/mod-cfpve": "pve",
|
||||||
|
"bewarellamas/mod-dungeonmaster": "pve",
|
||||||
|
"araxiaonline/mod-mythic-plus": "pve",
|
||||||
|
"sogladev/mod-reset-raid-cooldowns": "pve",
|
||||||
|
"hallgaeuer/mod-quickbalance": "pve",
|
||||||
|
"valsan-azerty-boi/mod-ony-naxx-logout-teleport": "pve",
|
||||||
|
"stealthyape/raidteleporter": "pve",
|
||||||
|
"zesman21/mod-nordf": "pve",
|
||||||
|
"helias/mod-bg-slaveryvalley": "pvp",
|
||||||
|
"azerothcore/mod-duel-reset": "pvp",
|
||||||
|
"gitdalisar/mod-faction-free": "pvp",
|
||||||
|
"azerothcore/mod-pvp-titles": "pvp",
|
||||||
|
"helias/mod-bg-twinpeaks": "pvp",
|
||||||
|
"helias/mod-bg-battle-for-gilneas": "pvp",
|
||||||
|
"talamortis/mod-pvpscript": "pvp",
|
||||||
|
"gozzim/mod-npc-spectator": "pvp",
|
||||||
|
"azerothcore/mod-bg-reward": "pvp",
|
||||||
|
"helias/mod-arena-tigerspeak": "pvp",
|
||||||
|
"helias/mod-arena-tolviron": "pvp",
|
||||||
|
"tbcstar/mod-high-risk-system": "pvp",
|
||||||
|
"azerothcore/mod-pvp-zones": "pvp",
|
||||||
|
"azerothcore/mod-bg-item-reward": "pvp",
|
||||||
|
"azerothcore/mod-desertion-warnings": "pvp",
|
||||||
|
"azerothcore/mod-low-level-rbg": "pvp",
|
||||||
|
"youpeoples/ultimate-full-loot-pvp": "pvp",
|
||||||
|
"azerothcore/mod-pvpstats-announcer": "pvp",
|
||||||
|
"anchydev/ffafix": "pvp",
|
||||||
|
"azerothcore/mod-low-level-arena": "pvp",
|
||||||
|
"trembon/mod-peacekeeper": "pvp",
|
||||||
|
"anchydev/bgqueuechecker": "pvp",
|
||||||
|
"anchydev/hardmode": "hardcore",
|
||||||
|
"kjack9/mod-dead-means-dead": "hardcore",
|
||||||
|
"conan1996-2/mod-hard-modes": "hardcore",
|
||||||
|
"jorge990125/mod-hardcore-makgora": "hardcore",
|
||||||
|
"stuntmonkey4u/mod-trial-of-finality": "hardcore",
|
||||||
|
"zindokar/mod-hardcore": "hardcore",
|
||||||
|
"zhengpeiru21/mod-individual-progression": "progression",
|
||||||
|
"azerothcore/mod-congrats-on-level": "progression",
|
||||||
|
"noisiver/mod-weekendbonus": "progression",
|
||||||
|
"youpeoples/prestige-and-draft-mode": "progression",
|
||||||
|
"anchydev/attriboost": "progression",
|
||||||
|
"azerothcore/mod-fireworks-on-level": "progression",
|
||||||
|
"anchydev/extendedxp": "progression",
|
||||||
|
"anchydev/prestigious": "progression",
|
||||||
|
"noisiver/mod-appreciation": "progression",
|
||||||
|
"betayi/mod_spec_reward": "progression",
|
||||||
|
"brian8544/setxpbar": "progression",
|
||||||
|
"nhobodyimportant/prestige": "progression",
|
||||||
|
"azerothcore/mod-alpha-rewards": "progression",
|
||||||
|
"michaeldelago/mod-quest-count-level": "progression",
|
||||||
|
"regrad/update-mob-level-to-player-and-random-item-stats": "progression",
|
||||||
|
"azerothcore/mod-chromie-xp": "progression",
|
||||||
|
"kadan-gx/mod-login-rewards": "progression",
|
||||||
|
"talamortis/mod-individual-xp": "progression",
|
||||||
|
"talamortis/reward-system": "progression",
|
||||||
|
"brian8544/mod-setxpbar": "progression",
|
||||||
|
"fischerlol/mod-level-15-boost": "progression",
|
||||||
|
"notepadguyofficial/mod-level-rewards": "progression",
|
||||||
|
"thearktect/mod-weekend-xp": "progression",
|
||||||
|
"heyitsbench/mod-arac": "classes",
|
||||||
|
"heyitsbench/mod-worgoblin": "classes",
|
||||||
|
"azerothcore/mod-npc-beastmaster": "classes",
|
||||||
|
"zhengpeiru21/mod-leech": "classes",
|
||||||
|
"azerothcore/mod-racial-trait-swap": "classes",
|
||||||
|
"noisiver/mod-learnspells": "classes",
|
||||||
|
"silviu20092/mod-warlock-pet-rename": "classes",
|
||||||
|
"vhiperdev/mod-spellregulator": "classes",
|
||||||
|
"xiii-hearts/mod-npc-subclass": "classes",
|
||||||
|
"gozzim/mod-starting-pet": "classes",
|
||||||
|
"bewarellamas/mod-profspecs": "classes",
|
||||||
|
"sogladev/mod-demonic-pact-classic": "classes",
|
||||||
|
"brian8544/mod-talentbutton": "classes",
|
||||||
|
"lenzork/mod-petequip": "classes",
|
||||||
|
"azerothcore/mod-transmog": "cosmetics",
|
||||||
|
"azerothcore/mod-weapon-visual": "cosmetics",
|
||||||
|
"azerothcore/mod-morphsummon": "cosmetics",
|
||||||
|
"azerothcore/mod-costumes": "cosmetics",
|
||||||
|
"azerothcore/mod-npc-morph": "cosmetics",
|
||||||
|
"azerothcore/mod-aoe-loot": "items",
|
||||||
|
"azerothcore/mod-npc-enchanter": "items",
|
||||||
|
"anchydev/statbooster": "items",
|
||||||
|
"zhengpeiru21/mod-reagent-bank": "items",
|
||||||
|
"silviu20092/mod-item-upgrade": "items",
|
||||||
|
"silviu20092/mod-reforging": "items",
|
||||||
|
"terrabyte-tbwps/mod-aoe-loot": "items",
|
||||||
|
"silviu20092/mod-improved-bank": "items",
|
||||||
|
"pangolp/mod-quest-loot-party": "items",
|
||||||
|
"anchydev/recycleditems": "items",
|
||||||
|
"anchydev/statboosterreroller": "items",
|
||||||
|
"hallgaeuer/mod-dynamic-loot-rates": "items",
|
||||||
|
"seaferer/aoe-loot---merge": "items",
|
||||||
|
"protonull/mod-starter-wands": "items",
|
||||||
|
"talamortis/mod-itemlevel": "items",
|
||||||
|
"noisiver/mod-junk-to-gold": "economy",
|
||||||
|
"youpeoples/black-market-auction-house": "economy",
|
||||||
|
"wowhellgarve-holydeew/mod-multi-vendor": "economy",
|
||||||
|
"azerothcore/mod-money-for-kills": "economy",
|
||||||
|
"azerothcore/mod-npc-gambler": "economy",
|
||||||
|
"elmsroth/mod-trade-items-filter": "economy",
|
||||||
|
"talamortis/mod_reward_shop": "economy",
|
||||||
|
"silviu20092/mod-sell-items": "economy",
|
||||||
|
"tereneckla/mod-profession-experience": "economy",
|
||||||
|
"jorge990125/mod-black-market": "economy",
|
||||||
|
"heyitsbench/mod-ptr-template": "account",
|
||||||
|
"pangolp/mod-recruit-friend": "account",
|
||||||
|
"azerothcore/mod-npc-all-mounts": "account",
|
||||||
|
"gozzim/mod-firstlogin-aio": "account",
|
||||||
|
"talamortis/mod-premium": "account",
|
||||||
|
"zerkenn/mod-character-services": "account",
|
||||||
|
"lucafolloni/mod-account-vanity-pets": "account",
|
||||||
|
"noisiver/mod-accountbound": "account",
|
||||||
|
"pangolp/mod-mounts-on-account": "account",
|
||||||
|
"microbica/mod-share-mounts": "account",
|
||||||
|
"gozzim/mod-globalchat": "social",
|
||||||
|
"azerothcore/mod-guild-zone-system": "social",
|
||||||
|
"azerothcore/mod-starter-guild": "social",
|
||||||
|
"anchydev/itembroadcastguildchat": "social",
|
||||||
|
"azerothcore/mod-chat-transmitter": "social",
|
||||||
|
"azerothcore/mod-global-chat": "social",
|
||||||
|
"noisiver/mod-guildfunds": "social",
|
||||||
|
"jorge990125/mod-streams": "social",
|
||||||
|
"noisiver/mod-assistant": "npc",
|
||||||
|
"azerothcore/mod-npc-services": "npc",
|
||||||
|
"azerothcore/mod-npc-buffer": "npc",
|
||||||
|
"pangolp/mod-npc-promotion": "npc",
|
||||||
|
"azerothcore/mod-npc-codebox": "npc",
|
||||||
|
"azerothcore/mod-buff-command": "npc",
|
||||||
|
"jorge990125/mod-bienvenida": "npc",
|
||||||
|
"dunjeon/mod-timeistime": "world",
|
||||||
|
"bytesgalore/mod-no-hearthstone-cooldown": "world",
|
||||||
|
"justin-kaufmann/mod-changeablespawnrates": "world",
|
||||||
|
"hallgaeuer/mod-quick-respawn": "world",
|
||||||
|
"justin-kaufmann/mod-noclip": "world",
|
||||||
|
"eldoba/mod-dynamic-resurrections-": "world",
|
||||||
|
"elmegaard/mod-auto-resurrect": "world",
|
||||||
|
"noisiver/mod-spawnpoints": "world",
|
||||||
|
"tralenor/mod-objscale": "world",
|
||||||
|
"silviu20092/mod-flightmaster-whistle": "world",
|
||||||
|
"sogladev/mod-ghost-speed": "world",
|
||||||
|
"talamortis/playerteleport": "world",
|
||||||
|
"vhiperdev/mod-no-farming": "world",
|
||||||
|
"noisiver/mod-activatezones": "world",
|
||||||
|
"zyggy123/treasure-chest-system": "events",
|
||||||
|
"azerothcore/mod-tic-tac-toe": "events",
|
||||||
|
"pangolp/mod-quest-status": "events",
|
||||||
|
"azerothcore/mod-war-effort": "events",
|
||||||
|
"youpeoples/quizmaster": "events",
|
||||||
|
"azerothcore/mod-cta-switch": "events",
|
||||||
|
"azerothcore/mod-dmf-switch": "events",
|
||||||
|
"azerothcore/mod-server-auto-shutdown": "server",
|
||||||
|
"anchydev/recache": "server",
|
||||||
|
"azerothcore/mod-queue-list-cache": "server",
|
||||||
|
"maluramichael/mod-influxdb": "server",
|
||||||
|
"sogladev/mod-increment-cache-version": "server",
|
||||||
|
"anchydev/aci": "server",
|
||||||
|
"azerothcore/mod-ip-tracker": "admin",
|
||||||
|
"tralenor/mod-gomove": "admin",
|
||||||
|
"talamortis/mod-whologged": "admin",
|
||||||
|
"talamortis/mod_character_tools": "admin",
|
||||||
|
"azerothcore/mod-notify-muted": "admin",
|
||||||
|
"mellianstudios/mod-encounter-logs": "admin",
|
||||||
|
"miithrandiir/mod_sponsorship": "web",
|
||||||
|
"exitare/mod-discord-webhook": "web",
|
||||||
|
"abutbul/mod-game-state-api": "web",
|
||||||
|
"thearktect/mod-discord-announce": "web",
|
||||||
|
"azerothcore/skeleton-module": "dev",
|
||||||
|
"azerothcore/eluna-ts": "dev",
|
||||||
|
"azerothcore/mod-premium-lib": "dev",
|
||||||
|
"anchydev/breakingnewsoverride": "client",
|
||||||
|
"gitdalisar/addon-faction-free-unit-popup": "client"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"description": "Curated CoA compatibility and recommendation overlay for AzerothCore modules",
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"repo_slug": "corfirean/mod-coa-playerbots",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Official companion bots for groups, dungeons and guild in Conquest of Azeroth."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "corfirean/mod-coa-content-scaling",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Official dynamic dungeon and raid scaling system with solo modes."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "zyth45/mod-playerbots",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "SQUID's Playerbots with full autonomous AI. Mutually exclusive with CoA Companions."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "corfirean/azerothcore-wotlk-coa",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Official Conquest of Azeroth modular core features."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-npc-buffer",
|
||||||
|
"status": "Verified",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "NPC buff master offering spells, sickness removal, and player restoration. Verified dynamic DLL on CoA Plugin SDK."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-congrats-on-level",
|
||||||
|
"status": "Verified",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Level-up celebration animations, fireworks and announcements. Verified dynamic DLL on CoA Plugin SDK."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-npc-enchanter",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Official NPC equipment enchanting module."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-reward-played-time",
|
||||||
|
"status": "Verified",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Periodic rewards and tokens granted based on active playtime. Verified dynamic DLL on CoA Plugin SDK."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-solocraft",
|
||||||
|
"status": "RequiresAdapter",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Dynamically boosts player stats in group content. Verified DLL build; requires calibration with CoA Content Scaling."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-cfbg",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Already built into the CoA core (cross-faction battlegrounds); a separate DLL would load it a second time."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "helias/mod-bg-battle-for-gilneas",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Needs the server's DBC files replaced (including Spell.dbc, which CoA ships its own of), a client patch and a modified wow.exe; written for AzerothCore 2019."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "helias/mod-bg-twinpeaks",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Needs the server's DBC files replaced (CoA ships its own), a client patch and a modified wow.exe."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "helias/mod-bg-slaveryvalley",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Needs the server's DBC files replaced (CoA ships its own) and a client patch."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-learn-spells",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Directly conflicts with CoA classless progression & spell draft: automatically grants standard class spells, breaking player builds."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-autobalance",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Direct gameplay authority collision with mod-coa-content-scaling: both systems attempt to dynamically scale creature health and damage."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "zhengpeiru21/mod-individual-progression",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Conflicts with CoA progression curve, dungeon level brackets, and content scaling gating."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-arac",
|
||||||
|
"status": "Incompatible",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Incompatible with CoA custom races DBC table (Esteria, etc.) and expanded race limits."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-ahbot",
|
||||||
|
"status": "Blocked",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Upstream repository has missing script loader entrypoint (Addmod_ahbotScripts) causing compilation and linking failures. Use official mod-ah-bot-plus instead."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-eluna",
|
||||||
|
"status": "RequiresAdapter",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Requires external LuaJIT runtime and custom CoA spell system exports."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-transmog",
|
||||||
|
"status": "RequiresAdapter",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Redundant: CoA already provides a built-in wardrobe and transmog system configured in coa.conf."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "mod-playerbots/mod-playerbots",
|
||||||
|
"status": "Blocked",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Конфликт с ядром CoA: используйте SQUID's Playerbots (Zyth45/mod-playerbots) или CoA Companions, специально адаптированные под CoA."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "azerothcore/mod-playerbots",
|
||||||
|
"status": "Blocked",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Конфликт с ядром CoA: используйте SQUID's Playerbots (Zyth45/mod-playerbots) или CoA Companions, специально адаптированные под CoA."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "zyth45/mod-dungeon-clear",
|
||||||
|
"status": "Recommended",
|
||||||
|
"is_recommended": true,
|
||||||
|
"reason": "Модуль тактик прохождения подземелий для SQUID's Playerbots (Zyth45). Требует активного модуля SQUID bots."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "jrad7/mod-dungeon-clear",
|
||||||
|
"status": "Blocked",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Конфликт с ядром CoA: используйте Zyth45/mod-dungeon-clear, адаптированный под SQUID's Playerbots в CoA."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"repo_slug": "nathanhandley/mod-ah-bot-plus",
|
||||||
|
"status": "Blocked",
|
||||||
|
"is_recommended": false,
|
||||||
|
"reason": "Конфликт с ядром CoA: в ядро уже встроен официальный модуль Auction House Bot."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -214,11 +214,13 @@ fn run(
|
|||||||
struct StreamWorker {
|
struct StreamWorker {
|
||||||
tx: Sender<TunnelMsg>,
|
tx: Sender<TunnelMsg>,
|
||||||
reset_on_drop: bool,
|
reset_on_drop: bool,
|
||||||
|
shutdown: Arc<TcpStream>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for StreamWorker {
|
impl Drop for StreamWorker {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.reset_on_drop {
|
if self.reset_on_drop {
|
||||||
|
let _ = self.shutdown.shutdown(std::net::Shutdown::Both);
|
||||||
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
|
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -388,6 +390,8 @@ fn session(
|
|||||||
};
|
};
|
||||||
match TcpStream::connect(("127.0.0.1", local_port)) {
|
match TcpStream::connect(("127.0.0.1", local_port)) {
|
||||||
Ok(tcp) => {
|
Ok(tcp) => {
|
||||||
|
let tcp = Arc::new(tcp);
|
||||||
|
let shutdown = tcp.clone();
|
||||||
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
|
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
|
||||||
let ws_tx = ws_out_tx.clone();
|
let ws_tx = ws_out_tx.clone();
|
||||||
|
|
||||||
@@ -398,6 +402,7 @@ fn session(
|
|||||||
StreamWorker {
|
StreamWorker {
|
||||||
tx: stream_tx,
|
tx: stream_tx,
|
||||||
reset_on_drop: true,
|
reset_on_drop: true,
|
||||||
|
shutdown,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -456,19 +461,20 @@ fn session(
|
|||||||
|
|
||||||
fn spawn_local_tcp_bridge(
|
fn spawn_local_tcp_bridge(
|
||||||
stream_id: u32,
|
stream_id: u32,
|
||||||
mut tcp: TcpStream,
|
tcp: Arc<TcpStream>,
|
||||||
from_tunnel: Receiver<TunnelMsg>,
|
from_tunnel: Receiver<TunnelMsg>,
|
||||||
to_tunnel: Sender<TunnelMsg>,
|
to_tunnel: Sender<TunnelMsg>,
|
||||||
) {
|
) {
|
||||||
let _ = tcp.set_nonblocking(false);
|
let _ = tcp.set_nonblocking(false);
|
||||||
let _ = tcp.set_nodelay(true);
|
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();
|
let to_tunnel_read = to_tunnel.clone();
|
||||||
|
|
||||||
// Local TCP read -> to tunnel
|
// Local TCP read -> to tunnel
|
||||||
std::thread::Builder::new()
|
std::thread::Builder::new()
|
||||||
.name(format!("relay-stream-{stream_id}-read"))
|
.name(format!("relay-stream-{stream_id}-read"))
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
|
let mut tcp_read = tcp_read.as_ref();
|
||||||
let mut buf = [0u8; 16384];
|
let mut buf = [0u8; 16384];
|
||||||
loop {
|
loop {
|
||||||
match tcp_read.read(&mut buf) {
|
match tcp_read.read(&mut buf) {
|
||||||
@@ -498,11 +504,12 @@ fn spawn_local_tcp_bridge(
|
|||||||
std::thread::Builder::new()
|
std::thread::Builder::new()
|
||||||
.name(format!("relay-stream-{stream_id}-write"))
|
.name(format!("relay-stream-{stream_id}-write"))
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
|
let mut tcp_write = tcp.as_ref();
|
||||||
while let Ok(msg) = from_tunnel.recv() {
|
while let Ok(msg) = from_tunnel.recv() {
|
||||||
match msg {
|
match msg {
|
||||||
TunnelMsg::Data { chunk, .. } => {
|
TunnelMsg::Data { chunk, .. } => {
|
||||||
if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&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;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -608,22 +615,71 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 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();
|
let (mut peer, _) = listener.accept().unwrap();
|
||||||
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let (out, _) = channel();
|
let (out, replies) = channel();
|
||||||
spawn_local_tcp_bridge(7, tcp, rx, out);
|
spawn_local_tcp_bridge(8, tcp, rx, out);
|
||||||
drop(StreamWorker {
|
let worker = StreamWorker {
|
||||||
tx,
|
tx,
|
||||||
reset_on_drop: true,
|
reset_on_drop: true,
|
||||||
});
|
shutdown,
|
||||||
match peer.read(&mut [0u8; 1]) {
|
};
|
||||||
Ok(0) => {},
|
worker
|
||||||
Err(error) if matches!(error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => {},
|
.tx
|
||||||
other => panic!("The abandoned relay stream must close, got {other:?}"),
|
.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.
|
/// Lists recent crash reports from `Core/Crashes`, sorted newest first.
|
||||||
pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
|
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();
|
let mut files: Vec<(PathBuf, SystemTime)> = Vec::new();
|
||||||
if let Ok(entries) = fs::read_dir(&dir) {
|
for world_root in roots {
|
||||||
for entry in entries.flatten() {
|
let entries = match fs::read_dir(world_root.join("Core/Crashes")) {
|
||||||
let path = entry.path();
|
Ok(entries) => Some(entries),
|
||||||
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||||
let mtime = entry
|
Err(e) => return Err(e.into()),
|
||||||
.metadata()
|
};
|
||||||
.and_then(|m| m.modified())
|
if let Some(entries) = entries {
|
||||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
for entry in entries.flatten() {
|
||||||
files.push((path, mtime));
|
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();
|
let mut items = Vec::new();
|
||||||
for (path, mtime) in files {
|
for (path, mtime) in files {
|
||||||
if let Ok(content) = fs::read_to_string(&path) {
|
if let Ok(bytes) = fs::read(&path) {
|
||||||
let item = parse_crash_content(&path, mtime, &content);
|
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);
|
items.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,6 +249,49 @@ fn explain(
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn parses_assertion_report() {
|
fn parses_assertion_report() {
|
||||||
let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static)
|
let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static)
|
||||||
|
|||||||
+1003
-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"
|
||||||
|
}
|
||||||
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user