From e4edb7cbdd0ca2f783bc0fb1121a76b816c5b857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Sat, 7 Nov 2026 10:19:13 +0500 Subject: [PATCH] feat(manager): multi-realm character database routing, RA dispatch & extended bot manager UI --- crates/coa-core/src/multiworld.rs | 52 ++++++++++++++++ crates/coa-core/src/ra.rs | 41 ++++++++++++ src-tauri/src/lib.rs | 100 ++++++++++++------------------ src/lib/api.ts | 32 +++++++--- src/screens/CompanionsCard.tsx | 70 ++++++++++++++------- 5 files changed, 203 insertions(+), 92 deletions(-) diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index f7bb17c..7e42d2c 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -97,6 +97,58 @@ pub fn world_root(main: &Path, mode: Mode) -> PathBuf { .map_or_else(|| main.to_path_buf(), |t| tree_root(main, t)) } +#[derive(Debug, Clone)] +pub struct BotOperationTarget { + pub world_root: PathBuf, + pub chars_db: &'static str, + pub ra_port: u16, + pub running: bool, + pub realm: Mode, +} + +pub fn resolve_bot_operation_target(main: &Path, realm: Mode) -> Result { + let state = realms::state(main)?; + let chars_db = realm.schema("characters")?; + + if realm == state.active { + let ports = crate::layout::read_ports(main); + let ra_port = ports.ra; + let status = process::observe(main, &ports); + let running = status.world.state != ServiceState::Stopped; + return Ok(BotOperationTarget { + world_root: main.to_path_buf(), + chars_db, + ra_port, + running, + realm, + }); + } + + let tree = Tree::ALL + .into_iter() + .find(|t| t.enabled(&state) && t.mode(state.active) == realm) + .ok_or_else(|| Error::Invalid(format!("Realm {} is not enabled in multiworld configuration.", realm.label())))?; + + let root = tree_root(main, tree); + if !root.exists() { + return Err(Error::Invalid(format!("Multiworld directory for {} does not exist: {}", realm.label(), root.display()))); + } + + let ports = crate::layout::read_ports(&root); + let (_, default_ra) = tree.ports(&state); + let ra_port = if ports.ra != 0 { ports.ra } else { default_ra.unwrap_or(3444) }; + let status = process::observe(&root, &ports); + let running = status.world.state != ServiceState::Stopped; + + Ok(BotOperationTarget { + world_root: root, + chars_db, + ra_port, + running, + realm, + }) +} + /// Any of the extra worlds is running or still stopping. pub fn is_running(main: &Path) -> bool { Tree::ALL.into_iter().any(|t| tree_running(main, t)) diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index c63a52e..37dcb5e 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -58,6 +58,23 @@ impl Ra { Self::connect_to(read_ports(root).ra, &cfg.ra_username, &cfg.ra_password) } + /// Connect to the loopback RA port of the target realm world server. + pub fn connect_target(main: &Path, realm: Option) -> Result { + let mode = realm.unwrap_or_else(|| { + crate::realms::view(main).map(|v| v.active).unwrap_or_default() + }); + let target = crate::multiworld::resolve_bot_operation_target(main, mode)?; + if !target.running { + return Err(Error::Invalid(format!( + "Realm {} worldserver is stopped; cannot execute online bot operation.", + target.realm.label() + ))); + } + let cfg: RaSettings = fsx::read_json(&main.join("Settings/repack.json")) + .map_err(|_| Error::Invalid("The server console settings could not be read.".into()))?; + Self::connect_to(target.ra_port, &cfg.ra_username, &cfg.ra_password) + } + pub fn connect_to(port: u16, user: &str, password: &str) -> Result { let addr: SocketAddr = ([127, 0, 0, 1], port).into(); let mut stream = @@ -278,6 +295,30 @@ impl Ra { Ok(out.lines().last().unwrap_or("").to_string()) } + pub fn spawn_custom( + &mut self, + count: u32, + level: u8, + class_id: Option, + spec_id: Option, + archetype: Option<&str>, + ) -> Result { + let mut cmd = format!("botcmd spawncustom {count} {level}"); + if let Some(c) = class_id { + cmd.push_str(&format!(" {c}")); + if let Some(s) = spec_id { + cmd.push_str(&format!(" {s}")); + if let Some(a) = archetype { + if !a.is_empty() { + cmd.push_str(&format!(" {a}")); + } + } + } + } + let out = self.bot_command(&cmd)?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + /// Bring all offline bots online gradually (.botcmd loginall). pub fn login_all(&mut self) -> Result { let out = self.bot_command("botcmd loginall")?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fb6f2f0..dfcf788 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1849,11 +1849,12 @@ async fn get_population( async fn companions_login_all( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, realm)?; ra.login_all() }) .await @@ -1865,11 +1866,12 @@ async fn companions_spawn_fleet( id: String, race: u8, level: u8, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, realm)?; ra.spawn_fleet(race, level) }) .await @@ -1885,11 +1887,12 @@ struct CompanionAction { async fn companions_stop_spawning( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; blocking(move || { Ok(CompanionAction { - count: Ra::connect(&root)?.cancel_spawning()?, + count: Ra::connect_target(&root, realm)?.cancel_spawning()?, }) }) .await @@ -1899,12 +1902,12 @@ async fn companions_stop_spawning( async fn companions_take_offline( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; - // Anything still waiting to be created must not come back right after. + let mut ra = Ra::connect_target(&root, realm)?; let _ = ra.cancel_spawning(); Ok(CompanionAction { count: ra.despawn_all()?, @@ -1913,13 +1916,12 @@ async fn companions_take_offline( .await } -/// Log `count` randomly chosen online companions out to lower the load. Uses the per-bot command that every server -/// build has, so it works on older builds too. #[tauri::command] async fn companions_despawn_some( state: State<'_, AppState>, id: String, count: u32, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; @@ -1927,13 +1929,18 @@ async fn companions_despawn_some( if !(1..=5000).contains(&count) { return Err(Error::Invalid("Choose a number between 1 and 5000.".into())); } + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let prefix = coa_core::population::bot_account_prefix(&root).to_uppercase(); let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::App)?; let rows = db.query(&format!( - "SELECT c.guid FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};" + "SELECT c.guid FROM {}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};", + target.chars_db ))?; let guids: Vec = rows.lines().filter_map(|l| l.trim().parse().ok()).collect(); - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, Some(mode))?; let mut done = 0; for g in guids { if ra.despawn_bot(g).unwrap_or(false) { @@ -1945,31 +1952,35 @@ async fn companions_despawn_some( .await } -/// Delete every companion for good. A recovery point of the characters and accounts is saved first. #[tauri::command] async fn companions_delete_all( app: AppHandle, state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let meta = meta_dir(&root)?; backup::create( &root, &meta, Kind::Quick, Trigger::BeforeDangerousChange, - Some("before deleting all companions".into()), + Some(format!("before deleting all {} companions", target.realm.label())), &|step| { let _ = app.emit("backup-progress", step); }, )?; - let before = coa_core::population::query(&root) + let before = coa_core::population::query_for_realm(&root, mode) .map(|p| p.bots_total) .unwrap_or(0); - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, Some(mode))?; let _ = ra.cancel_spawning(); ra.purge_all()?; Ok(CompanionAction { count: before }) @@ -2026,6 +2037,10 @@ async fn add_companions( id: String, count: u32, realm: Option, + level: Option, + class_id: Option, + spec_id: Option, + archetype: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; @@ -2038,15 +2053,10 @@ async fn add_companions( let mode = realm.unwrap_or_else(|| { coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() }); - let chars_db = match mode { - coa_core::realms::Mode::Coa => "acore_characters", - coa_core::realms::Mode::Wildcard => "acore_characters_wildcard", - coa_core::realms::Mode::Reborn => "acore_characters_reborn", - }; + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); - // Every companion, old and new, should come back at the next start, so the start-up limit only ever grows here. let existing_max = config::load(&root, Scope::Bots) .ok() .and_then(|v| { @@ -2064,56 +2074,22 @@ async fn add_companions( Value::from(existing_max.max(already + count).min(5000)), ); config::save(&root, &meta, Scope::Bots, &changes)?; - let o = coa_core::process::observe(&root, &layout::read_ports(&root)); - // Large batches while the server is stopped: create them in the database right now, fully equipped (CoA schema only). - if o.world.state == coa_core::process::ServiceState::Stopped - && o.auth.state == coa_core::process::ServiceState::Stopped - && count >= coa_core::companions::OFFLINE_MIN - && mode == coa_core::realms::Mode::Coa - && coa_core::companions::offline_factory(&root).is_some() - { - let started_db = o.mysql.state != coa_core::process::ServiceState::Running; - if started_db { - let out = driver::run(&root, Verb::StartMysql)?; - if !out.ok { - return Err(Error::Invalid("The database could not be started.".into())); - } - } - let made = (|| -> Result<()> { - coa_core::companions::ensure_templates_for_schema( - &coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?, - chars_db, - )?; - coa_core::companions::offline_create( - &root, - &meta.join("logs").join("companions-offline.log"), - count, - )?; - Ok(()) - })(); - if started_db { - let _ = driver::run(&root, Verb::StopAll); - } - made?; - tracing::info!(count, "companions created offline"); - return Ok(CompanionsResult { - spawned: None, - created: Some(count), - baseline: None, - }); - } + let mut baseline = None; - let spawned = if o.world.state == coa_core::process::ServiceState::Running { - // Older servers have no template characters to copy bots from: add them first. + let spawned = if target.running { if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) { - let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db); + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db); } baseline = coa_core::population::query_for_realm(&root, mode) .ok() .map(|p| p.bots_total); - Some(Ra::connect(&root)?.spawn_bots(count)?) + let mut ra = Ra::connect_target(&root, Some(mode))?; + if let Some(lvl) = level { + Some(ra.spawn_custom(count, lvl, class_id, spec_id, archetype.as_deref())?) + } else { + Some(ra.spawn_bots(count)?) + } } else { - // The server is stopped: creating bots needs it running, so remember the request and do it after the next start. coa_core::fsx::atomic_write_json( &meta.join("companions.pending.json"), &serde_json::json!({ "count": count }), diff --git a/src/lib/api.ts b/src/lib/api.ts index 4ac05c1..8af8dac 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -572,17 +572,33 @@ export const api = { rollbackUpdate: (id: string, txn: string) => invoke("rollback_update", { id, txn }), retryUpdateValidation: (id: string, txn: string) => invoke("retry_update_validation", { id, txn }), population: (id: string, realm?: RealmMode) => invoke("get_population", { id, realm: realm ?? null }), - stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }), - takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }), - despawnSome: (id: string, count: number) => invoke<{ count: number }>("companions_despawn_some", { id, count }), - deleteAllCompanions: (id: string) => invoke<{ count: number }>("companions_delete_all", { id }), - loginAllCompanions: (id: string) => invoke("companions_login_all", { id }), - spawnBotFleet: (id: string, race: number, level: number) => invoke("companions_spawn_fleet", { id, race, level }), + stopSpawning: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_stop_spawning", { id, realm: realm ?? null }), + takeOffline: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_take_offline", { id, realm: realm ?? null }), + despawnSome: (id: string, count: number, realm?: RealmMode) => invoke<{ count: number }>("companions_despawn_some", { id, count, realm: realm ?? null }), + deleteAllCompanions: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_delete_all", { id, realm: realm ?? null }), + loginAllCompanions: (id: string, realm?: RealmMode) => invoke("companions_login_all", { id, realm: realm ?? null }), + spawnBotFleet: (id: string, race: number, level: number, realm?: RealmMode) => invoke("companions_spawn_fleet", { id, race, level, realm: realm ?? null }), openLink: (url: string) => invoke("open_link", { url }), performance: (id: string) => invoke("get_performance", { id }), companionSizes: () => invoke("companion_sizes"), - addCompanions: (id: string, count: number, realm?: RealmMode) => - invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count, realm: realm ?? null }), + addCompanions: ( + id: string, + count: number, + realm?: RealmMode, + level?: number, + classId?: number, + specId?: number, + archetype?: string + ) => + invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { + id, + count, + realm: realm ?? null, + level: level ?? null, + class_id: classId ?? null, + spec_id: specId ?? null, + archetype: archetype ?? null, + }), clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientInfo: (id: string) => invoke("client_info", { id }), diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index 3ca88ac..c4dd45a 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -55,8 +55,9 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const activeServerRealm = profiles?.active ?? "coa"; const isViewingActiveRealm = selectedRealm === activeServerRealm; + const isRealmOperational = isViewingActiveRealm || running; - const maxLevelForRealm = selectedRealm === "reborn" ? 60 : 80; + const maxLevelForRealm = 60; // Load realm profiles const loadProfiles = async () => { @@ -158,12 +159,27 @@ export function CompanionsCard({ serverId }: { serverId: string }) { setNote(null); try { if (spawnMode === "fleet") { - // Fleet spawn: race 1 (Human) or 2 (Orc) const race = 1; - const out = await api.spawnBotFleet(serverId, race, targetLevel); + const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); setNote(out || `Spawned level ${targetLevel} fleet`); } else { - const r = await api.addCompanions(serverId, count, selectedRealm); + const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : undefined; + let specNum: number | undefined = undefined; + if (selectedRole === "tank") { + if (selectedRealm === "reborn") { + specNum = (classNum === 7 || classNum === 9 || classNum === 11) ? 4 : (classNum === 2 ? 2 : classNum === 1 ? 3 : 1); + } else if (selectedRealm === "wildcard") { + specNum = 1; + } + } else if (selectedRole === "healer") { + if (selectedRealm === "reborn") { + specNum = (classNum === 2 || classNum === 5) ? 1 : (classNum === 7 || classNum === 11 ? 3 : 1); + } else if (selectedRealm === "wildcard") { + specNum = 2; + } + } + const archStr = selectedArchetype !== "all" ? selectedArchetype : undefined; + const r = await api.addCompanions(serverId, count, selectedRealm, targetLevel, classNum, specNum, archStr); if (r.spawned && r.baseline !== null) { setJob({ baseline: r.baseline, target: count, since: Date.now() }); } @@ -186,7 +202,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { // Bring offline bots online const handleLoginAll = () => act(async () => { - const out = await api.loginAllCompanions(serverId); + const out = await api.loginAllCompanions(serverId, selectedRealm); await fetchPopulation(); return out || "All available offline bots queued for login."; }); @@ -194,7 +210,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { // Stop queued creations const stopCreating = () => act(async () => { - const r = await api.stopSpawning(serverId); + const r = await api.stopSpawning(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.stopped", { n: r.count }); @@ -204,7 +220,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const takeOffline = () => { if (!window.confirm(t("comp.offlineConfirm"))) return; void act(async () => { - const r = await api.takeOffline(serverId); + const r = await api.takeOffline(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.offlineDone2", { n: r.count }); @@ -216,7 +232,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000; const despawnSome = () => act(async () => { - const r = await api.despawnSome(serverId, dn); + const r = await api.despawnSome(serverId, dn, selectedRealm); await fetchPopulation(); return t("comp.despawnSomeDone", { n: r.count }); }); @@ -225,7 +241,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const deleteAll = () => { if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return; void act(async () => { - await api.deleteAllCompanions(serverId); + await api.deleteAllCompanions(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.deleteDone"); @@ -514,17 +530,27 @@ export function CompanionsCard({ serverId }: { serverId: string }) { {selectedRealm === "coa" && ( <> - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + )} {selectedRealm === "wildcard" && ( @@ -605,7 +631,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {