Files
coa-server-manager/crates/coa-core/src/realms.rs
T
ДмитрийandClaude Opus 5.5 8353b791fb The Manager no longer edits Scripts/manage.py
Repacks ship no .bat files, and the Manager starts servers with
coa-core::launcher, so the realm-profile patch it wrote into manage.py
served no one. It is no longer applied (realm creation, realm switching and
start).

Recognising the edits older Managers made (realm patch, bridge import fix)
moves into legacy_launcher, so updates and file checks still treat such a
file as unmodified. Nothing there writes a file.

manage.py itself stays complete in the repack: Managers up to 0.9.10 run it
through their bridge and patch its text, so it cannot become a thin wrapper
until those Managers are no longer supported.

Verified: coa-core unit tests; examples/manager_launcher_e2e on a disposable
repack (manage.py unchanged after a start with a realm profile).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:07:41 +05:00

1116 lines
40 KiB
Rust

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::config::parser::ConfFile;
use crate::db::{Account, Db};
use crate::error::{Error, Result};
use crate::{fsx, layout, process};
const STATE: &str = "Settings/realm-profile.json";
const JOURNAL: &str = "Settings/realm-switch.json";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
#[default]
Coa,
Wildcard,
Reborn,
}
impl Mode {
pub fn name(self) -> &'static str {
match self {
Self::Coa => "coa",
Self::Wildcard => "wildcard",
Self::Reborn => "reborn",
}
}
pub fn realm_id(self) -> u32 {
match self {
Self::Coa => 1,
Self::Wildcard => 2,
Self::Reborn => 3,
}
}
pub fn label(self) -> &'static str {
match self {
Self::Coa => "Conquest of Azeroth",
Self::Wildcard => "Wildcard",
Self::Reborn => "Warcraft Reborn",
}
}
pub fn schema(self, kind: &str) -> Result<&'static str> {
match (self, kind) {
(_, "auth") => Ok("acore_auth"),
(Self::Coa, "characters") => Ok("acore_characters"),
(Self::Coa, "world") => Ok("acore_world"),
(Self::Wildcard, "characters") => Ok("acore_characters_wildcard"),
(Self::Wildcard, "world") => Ok("acore_world_wildcard"),
(Self::Reborn, "characters") => Ok("acore_characters_reborn"),
(Self::Reborn, "world") => Ok("acore_world_reborn"),
_ => Err(Error::Invalid("Unknown realm database.".into())),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RealmState {
pub active: Mode,
pub wildcard_created: bool,
#[serde(default)]
pub reborn_created: bool,
/// Wildcard starts together with Conquest of Azeroth (the second of the two when Wildcard is the primary realm).
#[serde(default)]
pub simultaneous: bool,
#[serde(default)]
pub secondary_world_port: Option<u16>,
#[serde(default)]
pub secondary_ra_port: Option<u16>,
/// Warcraft Reborn starts together with Conquest of Azeroth, which is then the primary realm.
#[serde(default)]
pub with_reborn: bool,
#[serde(default)]
pub reborn_world_port: Option<u16>,
#[serde(default)]
pub reborn_ra_port: Option<u16>,
}
impl RealmState {
/// World ports of the realms that run next to the primary one (the ones that are switched on).
pub fn extra_world_ports(&self) -> Vec<u16> {
[
self.secondary_world_port.filter(|_| self.simultaneous),
self.reborn_world_port.filter(|_| self.with_reborn),
]
.into_iter()
.flatten()
.collect()
}
/// Realms that run as a world of their own next to the primary one.
pub fn extra_modes(&self) -> Vec<Mode> {
let mut modes = Vec::new();
if self.simultaneous {
modes.push(if self.active == Mode::Coa {
Mode::Wildcard
} else {
Mode::Coa
});
}
if self.with_reborn {
modes.push(Mode::Reborn);
}
modes
}
pub fn created(&self, mode: Mode) -> bool {
match mode {
Mode::Coa => true,
Mode::Wildcard => self.wildcard_created,
Mode::Reborn => self.reborn_created,
}
}
pub fn modes(&self) -> Vec<Mode> {
let mut modes = vec![self.active];
modes.extend(
[Mode::Coa, Mode::Wildcard, Mode::Reborn]
.into_iter()
.filter(|m| *m != self.active && self.created(*m)),
);
modes
}
}
#[derive(Debug, Serialize)]
pub struct View {
pub active: Mode,
pub wildcard_created: bool,
pub reborn_created: bool,
pub reborn_supported: bool,
pub supported: bool,
pub recovery_pending: bool,
pub simultaneous: bool,
pub secondary_world_port: Option<u16>,
pub secondary_running: bool,
pub with_reborn: bool,
pub reborn_world_port: Option<u16>,
pub reborn_running: bool,
}
pub fn state(root: &Path) -> Result<RealmState> {
if !root.join(STATE).exists() {
return Ok(RealmState::default());
}
fsx::read_json(&root.join(STATE))
}
/// The world server executable of this folder: `worldserver.exe` in a repack, `worldserver` in a Docker server.
fn world_binary(root: &Path) -> std::path::PathBuf {
let exe = root.join("Core/worldserver.exe");
if exe.exists() {
exe
} else {
root.join("Core/worldserver")
}
}
pub fn view(root: &Path) -> Result<View> {
let s = state(root)?;
// Inspect the binary itself; templates or an old log cannot prove installed support.
let binary = fs::read(world_binary(root))?;
let reborn_supported = binary
.windows(b"Warcraft Reborn class spells are unavailable".len())
.any(|w| w == b"Warcraft Reborn class spells are unavailable");
let supported = binary
.windows(b"Wildcard synergy settings".len())
.any(|w| w == b"Wildcard synergy settings");
Ok(View {
active: s.active,
wildcard_created: s.wildcard_created,
reborn_created: s.reborn_created,
reborn_supported,
supported,
recovery_pending: root.join(JOURNAL).exists(),
simultaneous: s.simultaneous,
secondary_world_port: s.secondary_world_port,
secondary_running: crate::multiworld::tree_running(root, crate::multiworld::Tree::Second),
with_reborn: s.with_reborn,
reborn_world_port: s.reborn_world_port,
reborn_running: crate::multiworld::tree_running(root, crate::multiworld::Tree::Reborn),
})
}
pub fn guard_module(root: &Path, id: &str) -> Result<()> {
if state(root)?.active != Mode::Coa && matches!(id, "companions" | "playerbots") {
return Err(Error::Invalid("Bot class mechanics have not been validated for this realm. This module is unavailable on this realm.".into()));
}
Ok(())
}
type Files = BTreeMap<String, Vec<u8>>;
fn configs(root: &Path) -> Result<Files> {
let mut files = Files::new();
for rel in crate::backup::config_files(root) {
if rel.starts_with("Core/configs/") && rel.ends_with(".conf")
|| rel.starts_with("Settings/") && rel.ends_with(".template")
{
files.insert(rel.clone(), fs::read(fsx::safe_join(root, &rel)?)?);
}
}
Ok(files)
}
fn snapshot(root: &Path, mode: Mode) -> std::path::PathBuf {
root.join(format!("Settings/realm-profiles/{}.json", mode.name()))
}
fn write_configs(root: &Path, files: &Files) -> Result<()> {
for rel in configs(root)?.keys() {
if !files.contains_key(rel) {
fs::remove_file(fsx::safe_join(root, rel)?)?;
}
}
for (rel, bytes) in files {
if !(rel.starts_with("Core/configs/") && rel.ends_with(".conf")
|| rel.starts_with("Settings/") && rel.ends_with(".template"))
{
return Err(Error::Invalid("Invalid realm configuration path.".into()));
}
fsx::atomic_write(
&fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?,
bytes,
)?;
}
Ok(())
}
fn set(files: &mut Files, path: &str, key: &str, value: &str) -> Result<()> {
let mut conf = ConfFile::parse_bytes(
files
.entry(path.into())
.or_insert_with(|| b"[worldserver]\n".to_vec()),
)?;
conf.set(key, value, &[]);
files.insert(path.into(), conf.to_text().into_bytes());
Ok(())
}
fn wildcard_configs(mut files: Files) -> Result<Files> {
for (key, value) in [
("CoA.ClassModel", "\"hero\""),
("CoA.GameModeMask", "64"),
("CoA.MapClass10ToWarrior", "0"),
("CoA.RealmType", "\"live seasonal\""),
(
"CoA.ClientBooleanConfigs",
"\"CONFIG_LEGACY_CHARACTER_ADVANCEMENT_ENABLED=0\"",
),
] {
set(&mut files, "Core/configs/modules/coa.conf", key, value)?;
}
set(
&mut files,
"Core/configs/modules/mod-coa-challenges.conf",
"CoAChallenges.GameModes.Realm",
"WildCard",
)?;
set(
&mut files,
"Core/configs/modules/mod-coa-challenges.conf",
"CoAChallenges.GameModes.Enable",
"1",
)?;
for (key, value) in [
("ChancePercent", "65"),
("LinkWeight", "3"),
("RelatedWeight", "2"),
("SpecTagWeight", "2"),
("SchoolTagWeight", "1"),
("TooltipWeight", "3"),
("TalentsNeedTarget", "1"),
("LogRolls", "1"),
] {
set(
&mut files,
"Core/configs/modules/wildcard.conf",
&format!("Wildcard.Synergy.{key}"),
value,
)?;
}
for path in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
if files.contains_key(path) {
for (key, value) in [
("RealmID", "2"),
("AlwaysMaxSkillForLevel", "1"),
("PlayerStart.CustomSpells", "1"),
] {
set(&mut files, path, key, value)?;
}
}
}
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
set(
&mut files,
"Core/configs/modules/mod_coa_playerbots.conf",
key,
value,
)?;
}
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files)
}
fn reborn_configs(mut files: Files) -> Result<Files> {
for (key, value) in [
("CoA.ClassModel", "\"wcr\""),
("CoA.GameModeMask", "0"),
("CoA.MapClass10ToWarrior", "0"),
("CoA.RealmType", "\"live\""),
("CoA.ClientBooleanConfigs", "\"\""),
] {
set(&mut files, "Core/configs/modules/coa.conf", key, value)?;
}
set(
&mut files,
"Core/configs/modules/mod-coa-challenges.conf",
"CoAChallenges.GameModes.Realm",
"\"\"",
)?;
for path in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
if files.contains_key(path) {
set(&mut files, path, "RealmID", "3")?;
}
}
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
set(
&mut files,
"Core/configs/modules/mod_coa_playerbots.conf",
key,
value,
)?;
}
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files)
}
#[derive(Serialize, Deserialize)]
struct Journal {
before: RealmState,
files: Files,
}
fn require_world_stopped(root: &Path) -> Result<()> {
let observed = process::observe(root, &layout::read_ports(root));
if observed.world.state != process::ServiceState::Stopped
|| observed.auth.state != process::ServiceState::Stopped
|| crate::multiworld::is_running(root)
{
return Err(Error::Invalid(
"Stop the server before switching realms. Your characters will be saved.".into(),
));
}
Ok(())
}
pub fn recover(root: &Path) -> Result<()> {
if !root.join(JOURNAL).exists() {
return Ok(());
}
require_world_stopped(root)?;
let journal: Journal = fsx::read_json(&root.join(JOURNAL))?;
write_configs(root, &journal.files)?;
fsx::atomic_write_json(&root.join(STATE), &journal.before)?;
fs::remove_file(root.join(JOURNAL))?;
Ok(())
}
fn create_databases(root: &Path, mode: Mode) -> Result<()> {
crate::backup::with_database(root, |_| {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
if db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.realmlist WHERE id={};",
mode.realm_id()
))? != "0"
{
return Err(Error::Invalid(format!(
"Realm ID {} is already in use. Its settings were left intact.",
mode.realm_id()
)));
}
for kind in ["world", "characters"] {
let source = Mode::Coa.schema(kind)?;
let dest = mode.schema(kind)?;
if db.schema_exists(dest)? {
return Err(Error::Invalid(format!("Database {dest} already exists. It was left intact; inspect it before creating a realm.")));
}
if db.extra_objects(source)? != 0 {
return Err(Error::Invalid(
"Realm creation does not support databases with routines, triggers or views."
.into(),
));
}
}
for (kind, tables) in crate::schema_check::WILDCARD_TABLES
.iter()
.filter(|_| mode == Mode::Wildcard)
{
let schema = crate::db::schema_of(kind)?;
let present = db.tables(schema)?;
let missing: Vec<_> = tables
.iter()
.filter(|table| !present.iter().any(|p| p == **table))
.copied()
.collect();
if !missing.is_empty() {
tracing::error!(root = %root.display(), database = schema, missing_tables = ?missing, "Wildcard realm creation blocked by missing database tables");
return Err(Error::Invalid(format!("Cannot create Wildcard: {schema} is missing tables: {}. Run Check files and database and include its report when requesting support.", missing.join(", "))));
}
}
let cache = root.join("Settings/realm-profiles/staging");
fs::create_dir_all(&cache)?;
fsx::require_space(
&cache,
db.schema_bytes("acore_world")?.saturating_mul(2) + 512 * 1024 * 1024,
)?;
let dump = cache.join("world.sql.zst");
db.dump_to("acore_world", &dump)?;
let stage_world = format!("coa_realm_world_{}", uuid::Uuid::new_v4().simple());
let stage_chars = format!("coa_realm_chars_{}", uuid::Uuid::new_v4().simple());
db.query(&format!("CREATE DATABASE `{stage_world}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE DATABASE `{stage_chars}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"))?;
db.import_from(&stage_world, &dump)?;
db.clone_structure("acore_characters", &stage_chars, &cache)?;
for table in [
"active_arena_season",
"addons",
"updates",
"updates_include",
"warden_action",
] {
db.query(&format!(
"INSERT INTO `{stage_chars}`.`{table}` SELECT * FROM acore_characters.`{table}`;"
))?;
}
// The newly empty realm inherits schema migration history, never the owner's characters or cards.
if db
.tables("acore_world")?
.iter()
.any(|t| t == "coa_manager_migrations")
{
db.query(&format!("CREATE TABLE IF NOT EXISTS `{stage_world}`.coa_manager_migrations LIKE acore_world.coa_manager_migrations;"))?;
}
let world = mode.schema("world")?;
let characters = mode.schema("characters")?;
db.query(&format!("CREATE DATABASE `{world}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE DATABASE `{characters}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"))?;
let mut renames = Vec::new();
for (stage, dest) in [(&stage_world, world), (&stage_chars, characters)] {
for table in db.tables(stage)? {
if !crate::db::valid_identifier(&table) {
return Err(Error::Invalid("Unsupported table name.".into()));
}
renames.push(format!("`{stage}`.`{table}` TO `{dest}`.`{table}`"));
}
}
db.query(&format!("RENAME TABLE {};", renames.join(", ")))?;
for host in db
.query("SELECT host FROM mysql.user WHERE user='acore';")?
.lines()
{
let host = hex::encode(host.as_bytes());
// Host names are trusted database data, but still quote them through a hex SQL literal.
db.query(&format!("SET @host=CONVERT(UNHEX('{host}') USING utf8mb4); SET @grant=CONCAT('GRANT ALL ON {world}.* TO ', QUOTE('acore'), '@', QUOTE(@host)); PREPARE realm_grant FROM @grant; EXECUTE realm_grant; DEALLOCATE PREPARE realm_grant; SET @grant=CONCAT('GRANT ALL ON {characters}.* TO ', QUOTE('acore'), '@', QUOTE(@host)); PREPARE realm_grant FROM @grant; EXECUTE realm_grant; DEALLOCATE PREPARE realm_grant;"))?;
}
db.query(&format!(
"DROP DATABASE `{stage_world}`; DROP DATABASE `{stage_chars}`;"
))?;
fs::remove_file(&dump)?;
Ok(())
})
}
/// Create the saved settings and the databases of a realm that was never set up. `before` is the current
/// configuration, the base of a new realm while Conquest of Azeroth is the active one.
fn create_realm(root: &Path, s: &mut RealmState, mode: Mode, before: &Files) -> Result<()> {
if s.created(mode) {
return Ok(());
}
let base = if s.active == Mode::Coa {
before.clone()
} else {
fsx::read_json(&snapshot(root, Mode::Coa))?
};
let files = match mode {
Mode::Wildcard => wildcard_configs(base)?,
Mode::Reborn => reborn_configs(base)?,
Mode::Coa => unreachable!(),
};
fsx::atomic_write_json(&snapshot(root, mode), &files)?;
create_databases(root, mode)?;
match mode {
Mode::Wildcard => s.wildcard_created = true,
Mode::Reborn => s.reborn_created = true,
Mode::Coa => {}
}
fsx::atomic_write_json(&root.join(STATE), s)?;
Ok(())
}
/// Set a realm up without making it the active one, so it can start next to the active realm.
pub fn ensure_created(root: &Path, mode: Mode) -> Result<()> {
let meta = crate::registry::metadata_dir_for(root)?;
let _update_lock = crate::update::operation_lock(&meta)?;
crate::update::ensure_recovered(&meta)?;
require_world_stopped(root)?;
recover(root)?;
let mut s = state(root)?;
let supported = view(root)?;
if mode == Mode::Wildcard && !supported.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
}
if mode == Mode::Reborn && !supported.reborn_supported {
return Err(Error::Invalid(
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
let before = configs(root)?;
create_realm(root, &mut s, mode, &before)
}
pub fn select(root: &Path, mode: Mode) -> Result<View> {
let meta = crate::registry::metadata_dir_for(root)?;
let _update_lock = crate::update::operation_lock(&meta)?;
crate::update::ensure_recovered(&meta)?;
require_world_stopped(root)?;
recover(root)?;
let mut s = state(root)?;
if mode == s.active {
return view(root);
}
if mode == Mode::Wildcard && !view(root)?.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
}
if mode == Mode::Reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid(
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
if (s.simultaneous || s.with_reborn) && mode != s.active {
return Err(Error::Invalid(
"Disable the realms that start together before switching realms.".into(),
));
}
let before = configs(root)?;
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
create_realm(root, &mut s, mode, &before)?;
let target: Files = fsx::read_json(&snapshot(root, mode))?;
// The launcher and batch files share this lock; recheck after the potentially long database copy.
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))?;
if !fs4::fs_std::FileExt::try_lock_exclusive(&lock)? {
return Err(Error::Invalid(
"Another start/stop action is in progress.".into(),
));
}
require_world_stopped(root)?;
let original = state(root)?;
fsx::atomic_write_json(
&root.join(JOURNAL),
&Journal {
before: original,
files: before,
},
)?;
let result = (|| {
write_configs(root, &target)?;
s.active = mode;
fsx::atomic_write_json(&root.join(STATE), &s)?;
Ok(())
})();
if let Err(e) = result {
drop(lock);
recover(root)?;
return Err(e);
}
fs::remove_file(root.join(JOURNAL))?;
view(root)
}
/// The character-creation model the world server advertises for a realm. Every realm has its own database and its own
/// entry on Overview, so it advertises exactly one model: a list such as `"coa wcr"` would let players create
/// Warcraft Reborn characters in the Conquest of Azeroth realm.
fn class_model_for(mode: Mode) -> &'static str {
match mode {
Mode::Coa => "coa",
Mode::Wildcard => "hero",
Mode::Reborn => "wcr",
}
}
/// The client builds its character-creation screen from `CoA.ClassModel`, so a realm whose setting lacks its own
/// model would show the wrong screen (a Conquest of Azeroth realm set to `"hero"` has no classes). The realm chosen in
/// the Manager wins: any other setting is replaced by the realm's own model.
/// A missing key means the server default, `"coa"`; a missing file is left to the server.
fn align_class_model(root: &Path, mode: Mode) -> Result<()> {
let path = root.join("Core/configs/modules/coa.conf");
let Ok(bytes) = fs::read(&path) else {
return Ok(());
};
let mut conf = ConfFile::parse_bytes(&bytes)?;
let current = conf
.get("CoA.ClassModel")
.map(crate::config::parser::unquote)
.unwrap_or("coa")
.to_string();
let wanted = class_model_for(mode);
if current.split_whitespace().eq([wanted]) {
return Ok(());
}
conf.set("CoA.ClassModel", &format!("\"{wanted}\""), &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
tracing::warn!(realm = mode.name(), from = %current, to = wanted, "CoA.ClassModel did not fit the selected realm and was corrected");
Ok(())
}
pub fn before_start(root: &Path) -> Result<()> {
recover(root)?;
let s = state(root)?;
align_class_model(root, s.active)?;
if !root.join(STATE).exists() {
return Ok(());
}
if s.simultaneous && !view(root)?.supported {
return Err(Error::Invalid(
"The installed server build does not support simultaneous Wildcard startup.".into(),
));
}
if (s.simultaneous || s.with_reborn) && s.active == Mode::Reborn {
return Err(Error::Invalid(
"Realms that start together need Conquest of Azeroth or Wildcard as the main realm.".into(),
));
}
if s.with_reborn && s.active != Mode::Coa {
return Err(Error::Invalid(
"Warcraft Reborn can start together with Conquest of Azeroth only. Select Conquest of Azeroth first.".into(),
));
}
if s.with_reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid(
"The installed server build does not support Warcraft Reborn.".into(),
));
}
if s.simultaneous || s.with_reborn {
fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?;
}
if s.active == Mode::Reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid(
"The installed server build does not support Warcraft Reborn.".into(),
));
}
if s.active != Mode::Coa {
if s.active == Mode::Wildcard && !view(root)?.supported {
return Err(Error::Invalid(
"The installed server build does not support Wildcard.".into(),
));
}
let path = root.join("Core/configs/modules/mod_coa_playerbots.conf");
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
conf.set("CoaBots.Enable", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
let path = root.join("Core/configs/modules/playerbots.conf");
let bytes = if path.exists() {
fs::read(&path)?
} else {
b"[worldserver]\n".to_vec()
};
let mut conf = ConfFile::parse_bytes(&bytes)?;
conf.set("AiPlayerbot.Enabled", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
}
Ok(())
}
pub fn setup_realmlist(root: &Path) -> Result<()> {
let s = state(root)?;
if !root.join(STATE).exists() {
return Ok(());
}
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let port = layout::read_ports(root).world;
for mode in s.modes().into_iter().filter(|m| *m != Mode::Coa) {
let id = mode.realm_id();
let name = mode.label();
db.query(&format!("INSERT INTO acore_auth.realmlist (id,name,address,localAddress,localSubnetMask,port,icon,flag,timezone,gamebuild) SELECT {id},'{name}',address,localAddress,localSubnetMask,{port},icon,2,timezone,gamebuild FROM acore_auth.realmlist WHERE id=1 ON DUPLICATE KEY UPDATE port={port};"))?;
}
let ids = s
.modes()
.iter()
.map(|m| m.realm_id().to_string())
.collect::<Vec<_>>()
.join(",");
db.query(&format!(
"UPDATE acore_auth.realmlist SET flag=2 WHERE id IN ({ids}) AND id<>{};",
s.active.realm_id()
))?;
if s.simultaneous {
let second = s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm port is missing.".into()))?;
let (coa, wildcard) = if s.active == Mode::Coa {
(port, second)
} else {
(second, port)
};
db.query(&format!("UPDATE acore_auth.realmlist SET port=CASE id WHEN 1 THEN {coa} ELSE {wildcard} END,flag=0 WHERE id IN (1,2);"))?;
}
if s.with_reborn {
let reborn = s
.reborn_world_port
.ok_or_else(|| Error::Invalid("Warcraft Reborn realm port is missing.".into()))?;
db.query(&format!(
"UPDATE acore_auth.realmlist SET port={reborn},flag=0 WHERE id={};",
Mode::Reborn.realm_id()
))?;
}
Ok(())
}
pub fn world_port_for_mode(root: &Path, mode: Mode) -> Result<u16> {
let ports = crate::layout::read_ports(root);
let s = state(root)?;
if mode == s.active {
return Ok(ports.world);
}
if mode == Mode::Reborn && s.with_reborn && s.active == Mode::Coa {
return s
.reborn_world_port
.ok_or_else(|| Error::Invalid("Warcraft Reborn realm port is missing.".into()));
}
if s.simultaneous && matches!((s.active, mode), (Mode::Coa, Mode::Wildcard) | (Mode::Wildcard, Mode::Coa)) {
return s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm port is missing.".into()));
}
Err(Error::Invalid(format!(
"Realm mode {mode:?} is not active (active: {:?}) and simultaneous mode is disabled.",
s.active
)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_states_and_all_created_realms_are_enumerated_once() {
let legacy: RealmState =
serde_json::from_str(r#"{"active":"wildcard","wildcard_created":true}"#).unwrap();
assert!(!legacy.reborn_created);
assert_eq!(legacy.modes(), [Mode::Wildcard, Mode::Coa]);
let all = RealmState {
active: Mode::Reborn,
wildcard_created: true,
reborn_created: true,
..Default::default()
};
assert_eq!(all.modes(), [Mode::Reborn, Mode::Coa, Mode::Wildcard]);
assert_eq!(serde_json::to_string(&Mode::Reborn).unwrap(), "\"reborn\"");
assert_eq!(Mode::Reborn.realm_id(), 3);
assert_eq!(Mode::Reborn.schema("auth").unwrap(), "acore_auth");
}
#[test]
fn reborn_has_its_own_settings_and_restores_the_coa_profile() {
let t = tempfile::tempdir().unwrap();
let mut coa = Files::new();
coa.insert(
"Core/configs/modules/coa.conf".into(),
b"[worldserver]\nCoA.ClassModel = coa\nCoA.GameModeMask = 0\n".to_vec(),
);
coa.insert(
"Settings/worldserver.conf.template".into(),
b"[worldserver]\nRealmID = 1\n".to_vec(),
);
coa.insert(
"Core/configs/modules/playerbots.conf".into(),
b"[worldserver]\nAiPlayerbot.Enabled = 1\n".to_vec(),
);
let reborn = reborn_configs(coa.clone()).unwrap();
let conf = ConfFile::parse_bytes(&reborn["Core/configs/modules/coa.conf"]).unwrap();
assert_eq!(conf.get("CoA.ClassModel"), Some("\"wcr\""));
assert_eq!(conf.get("CoA.GameModeMask"), Some("0"));
assert_eq!(
ConfFile::parse_bytes(&reborn["Settings/worldserver.conf.template"])
.unwrap()
.get("RealmID"),
Some("3")
);
assert_eq!(
ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"])
.unwrap()
.get("AiPlayerbot.Enabled"),
Some("0")
);
write_configs(t.path(), &reborn).unwrap();
write_configs(t.path(), &coa).unwrap();
assert_eq!(configs(t.path()).unwrap(), coa);
fsx::atomic_write_json(
&t.path().join(STATE),
&RealmState {
active: Mode::Reborn,
reborn_created: true,
..Default::default()
},
)
.unwrap();
assert!(guard_module(t.path(), "companions").is_err());
assert!(guard_module(t.path(), "playerbots").is_err());
assert!(guard_module(t.path(), "content-scaling").is_ok());
}
fn write_class_model(root: &Path, text: &str) {
fsx::atomic_write(&root.join("Core/configs/modules/coa.conf"), text.as_bytes()).unwrap();
}
fn class_model(root: &Path) -> String {
let bytes = fs::read(root.join("Core/configs/modules/coa.conf")).unwrap();
ConfFile::parse_bytes(&bytes)
.unwrap()
.get("CoA.ClassModel")
.unwrap_or_default()
.to_string()
}
#[test]
fn a_class_model_that_does_not_fit_the_realm_is_replaced_by_the_realms_own() {
let t = tempfile::tempdir().unwrap();
// No file: left to the server. No key: the server default "coa" applies, which fits Conquest of Azeroth.
align_class_model(t.path(), Mode::Coa).unwrap();
assert!(!t.path().join("Core/configs/modules/coa.conf").exists());
write_class_model(t.path(), "[worldserver]
# CoA.ClassModel = \"hero\"
");
align_class_model(t.path(), Mode::Coa).unwrap();
assert_eq!(class_model(t.path()), "");
write_class_model(t.path(), "# note
CoA.ClassModel = \"hero\"
CoA.GameModeMask = 0
");
align_class_model(t.path(), Mode::Coa).unwrap();
assert_eq!(
fs::read_to_string(t.path().join("Core/configs/modules/coa.conf")).unwrap(),
"# note
CoA.ClassModel = \"coa\"
CoA.GameModeMask = 0
"
);
align_class_model(t.path(), Mode::Wildcard).unwrap();
assert_eq!(class_model(t.path()), "\"hero\"");
align_class_model(t.path(), Mode::Reborn).unwrap();
assert_eq!(class_model(t.path()), "\"wcr\"");
// A missing key does not fit a realm other than Conquest of Azeroth.
write_class_model(t.path(), "[worldserver]
");
align_class_model(t.path(), Mode::Wildcard).unwrap();
assert_eq!(class_model(t.path()), "\"hero\"");
}
#[test]
fn a_class_model_list_is_narrowed_to_the_realms_own_model() {
let t = tempfile::tempdir().unwrap();
// The shipped default serves two models; the realm chosen in the Manager keeps only its own.
for (mode, want) in [(Mode::Coa, "\"coa\""), (Mode::Reborn, "\"wcr\"")] {
write_class_model(t.path(), "CoA.ClassModel = \"coa wcr\"
");
align_class_model(t.path(), mode).unwrap();
assert_eq!(class_model(t.path()), want);
}
// A setting that is already exactly right is not rewritten, quoted or not.
for (text, mode) in [
("CoA.ClassModel = \"coa\"
", Mode::Coa),
("CoA.ClassModel = hero
", Mode::Wildcard),
] {
write_class_model(t.path(), text);
align_class_model(t.path(), mode).unwrap();
assert_eq!(
fs::read_to_string(t.path().join("Core/configs/modules/coa.conf")).unwrap(),
text
);
}
}
#[test]
fn before_start_aligns_the_class_model_with_the_active_realm() {
let t = tempfile::tempdir().unwrap();
write_class_model(t.path(), "CoA.ClassModel = \"hero\"
");
before_start(t.path()).unwrap();
assert_eq!(class_model(t.path()), "\"coa\"");
}
#[test]
fn extra_realms_follow_the_two_switches_and_old_states_still_load() {
let old: RealmState = serde_json::from_str(
r#"{"active":"coa","wildcard_created":true,"simultaneous":true,"secondary_world_port":8086}"#,
)
.unwrap();
assert!(!old.with_reborn && old.reborn_world_port.is_none());
assert_eq!(old.extra_modes(), [Mode::Wildcard]);
let mut s = RealmState::default();
assert!(s.extra_modes().is_empty());
s.with_reborn = true;
assert_eq!(s.extra_modes(), [Mode::Reborn]);
s.simultaneous = true;
assert_eq!(s.extra_modes(), [Mode::Wildcard, Mode::Reborn]);
s.secondary_world_port = Some(8086);
s.reborn_world_port = Some(8087);
assert_eq!(s.extra_world_ports(), [8086, 8087]);
s.with_reborn = false;
assert_eq!(s.extra_world_ports(), [8086]);
s.with_reborn = true;
// Wildcard as the main realm still pairs with Conquest of Azeroth.
s.active = Mode::Wildcard;
s.with_reborn = false;
assert_eq!(s.extra_modes(), [Mode::Coa]);
}
#[test]
fn each_running_realm_has_its_own_world_port() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write(&t.path().join("Settings/repack.json"), br#"{"worldPort": 8085}"#).unwrap();
let write = |json: &str| fsx::atomic_write(&t.path().join(STATE), json.as_bytes()).unwrap();
write(r#"{"active":"coa","wildcard_created":true,"reborn_created":true,"simultaneous":true,"secondary_world_port":8086,"with_reborn":true,"reborn_world_port":8087}"#);
assert_eq!(world_port_for_mode(t.path(), Mode::Coa).unwrap(), 8085);
assert_eq!(world_port_for_mode(t.path(), Mode::Wildcard).unwrap(), 8086);
assert_eq!(world_port_for_mode(t.path(), Mode::Reborn).unwrap(), 8087);
// Only Reborn next to Conquest of Azeroth: Wildcard is not running anywhere.
write(r#"{"active":"coa","wildcard_created":true,"reborn_created":true,"with_reborn":true,"reborn_world_port":8087}"#);
assert_eq!(world_port_for_mode(t.path(), Mode::Reborn).unwrap(), 8087);
assert!(world_port_for_mode(t.path(), Mode::Wildcard).is_err());
// Reborn only pairs with Conquest of Azeroth as the main realm.
write(r#"{"active":"wildcard","wildcard_created":true,"reborn_created":true,"with_reborn":true,"reborn_world_port":8087}"#);
assert!(world_port_for_mode(t.path(), Mode::Reborn).is_err());
}
#[test]
fn reborn_support_requires_the_new_code_in_the_installed_binary() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write(
&t.path().join("Core/worldserver.exe"),
b"Wildcard synergy settings",
)
.unwrap();
assert!(!view(t.path()).unwrap().reborn_supported);
fsx::atomic_write(
&t.path().join("Core/worldserver.exe"),
b"Warcraft Reborn class spells are unavailable",
)
.unwrap();
let v = view(t.path()).unwrap();
assert!(v.reborn_supported);
assert!(!v.supported);
}
#[test]
fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() {
let d = tempfile::tempdir().unwrap();
fs::create_dir_all(d.path().join("Core")).unwrap();
fs::create_dir_all(d.path().join("Settings")).unwrap();
fs::write(
d.path().join("Settings/docker.json"),
br#"{"project":"t1"}"#,
)
.unwrap();
fs::write(
d.path().join("Core/worldserver"),
b"ELF...Wildcard synergy settings...",
)
.unwrap();
assert!(
view(d.path()).unwrap().supported,
"worldserver without .exe is read too"
);
fs::write(d.path().join("Core/worldserver"), b"ELF...an older build").unwrap();
assert!(!view(d.path()).unwrap().supported);
// The repack's executable still wins when both exist, so a repack is read as before.
fs::write(
d.path().join("Core/worldserver.exe"),
b"MZ...Wildcard synergy settings",
)
.unwrap();
assert!(view(d.path()).unwrap().supported);
}
#[test]
fn fresh_wildcard_disables_bots_and_preserves_scaling() {
let mut f = Files::new();
f.insert(
"Core/configs/modules/mod-coa-content-scaling.conf".into(),
b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(),
);
f.insert(
"Settings/worldserver.conf.template".into(),
b"[worldserver]\nRealmID = 1\n".to_vec(),
);
let w = wildcard_configs(f.clone()).unwrap();
assert_eq!(
w["Core/configs/modules/mod-coa-content-scaling.conf"],
f["Core/configs/modules/mod-coa-content-scaling.conf"]
);
let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap();
assert_eq!(c.get("CoaBots.Enable"), Some("0"));
assert_eq!(
ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"])
.unwrap()
.get("RealmID"),
Some("2")
);
}
#[test]
fn corrupt_state_is_not_silently_treated_as_coa() {
let t = tempfile::tempdir().unwrap();
fs::create_dir(t.path().join("Settings")).unwrap();
fs::write(t.path().join(STATE), "broken").unwrap();
assert!(state(t.path()).is_err());
}
#[test]
fn recovery_restores_original_settings() {
let t = tempfile::tempdir().unwrap();
let mut files = Files::new();
files.insert(
"Core/configs/modules/coa.conf".into(),
b"CoA.ClassModel = coa\n".to_vec(),
);
fsx::atomic_write_json(
&t.path().join(JOURNAL),
&Journal {
before: RealmState::default(),
files,
},
)
.unwrap();
recover(t.path()).unwrap();
assert_eq!(state(t.path()).unwrap().active, Mode::Coa);
assert_eq!(
fs::read_to_string(t.path().join("Core/configs/modules/coa.conf")).unwrap(),
"CoA.ClassModel = coa\n"
);
assert!(!t.path().join(JOURNAL).exists());
}
#[test]
fn reverting_to_coa_removes_wildcard_only_config_files() {
let t = tempfile::tempdir().unwrap();
let mut coa = Files::new();
coa.insert(
"Core/configs/modules/coa.conf".into(),
b"[worldserver]\nCoA.ClassModel = coa\n".to_vec(),
);
let wildcard = wildcard_configs(coa.clone()).unwrap();
write_configs(t.path(), &wildcard).unwrap();
write_configs(t.path(), &coa).unwrap();
assert!(!t
.path()
.join("Core/configs/modules/mod-coa-challenges.conf")
.exists());
assert_eq!(configs(t.path()).unwrap(), coa);
}
#[test]
fn wildcard_blocks_bot_settings_and_enable_calls() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write_json(
&t.path().join(STATE),
&RealmState {
active: Mode::Wildcard,
wildcard_created: true,
..Default::default()
},
)
.unwrap();
assert!(crate::modules::set_enabled(t.path(), t.path(), "companions", true).is_err());
assert!(crate::config::save(
t.path(),
t.path(),
crate::config::Scope::Bots,
&BTreeMap::new()
)
.is_err());
assert!(guard_module(t.path(), "content-scaling").is_ok());
}
}