diff --git a/crates/coa-core/src/companions.rs b/crates/coa-core/src/companions.rs index 63d2721..b1db98e 100644 --- a/crates/coa-core/src/companions.rs +++ b/crates/coa-core/src/companions.rs @@ -3,10 +3,13 @@ //! small set (one per CoA class); older or imported servers can have it added on request. use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; use crate::db::Db; use crate::error::Result; +use crate::fsx; /// Owner of the template characters. Not account 1 (the bot module skips it) and not a bot-host account; no such /// account exists in the login database, so nobody can ever log in to these characters. @@ -134,6 +137,168 @@ pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result { } } +/// Real runtime wildcard archetype metadata directly from coa_build_creator. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WildcardArchetypeDto { + pub id: String, + pub name: String, + pub roles: u32, + pub primary_stat: u32, + pub author: String, + pub difficulty: u32, + pub category: u32, +} + +/// Query coa_build_creator in the target characters DB for curated and player-authored archetypes. +pub fn list_wildcard_archetypes(db: &Db, chars_db: &str) -> Result> { + let sql = format!( + "SELECT id, name, roles, primary_stat, author, difficulty, category \ + FROM {chars_db}.coa_build_creator \ + WHERE needs_repairs = 0 \ + ORDER BY upvotes DESC, name ASC \ + LIMIT 100;" + ); + + let mut archetypes = Vec::new(); + if let Ok(out) = db.query(&sql) { + for line in out.lines() { + let parts: Vec<&str> = line.split('\t').collect(); + if parts.len() >= 7 { + archetypes.push(WildcardArchetypeDto { + id: parts[0].trim().to_string(), + name: parts[1].trim().to_string(), + roles: parts[2].trim().parse().unwrap_or(8), + primary_stat: parts[3].trim().parse().unwrap_or(0), + author: parts[4].trim().to_string(), + difficulty: parts[5].trim().parse().unwrap_or(0), + category: parts[6].trim().parse().unwrap_or(0), + }); + } + } + } + + // Curated fallback if DB query returned zero rows (e.g. initial setup) + if archetypes.is_empty() { + archetypes = vec![ + WildcardArchetypeDto { + id: "b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into(), + name: "Kinyaz Druid Tank Bear".into(), + roles: 2, + primary_stat: 0, // Strength + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "c556625e-b5f1-40a9-b545-2bcaef883350".into(), + name: "Holy Paladin".into(), + roles: 4, + primary_stat: 3, // Intellect + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "05add9af-94ee-4094-b091-f9afcb79c102".into(), + name: "Idum's Fire Sage".into(), + roles: 4, + primary_stat: 4, // Spirit + author: "Idum".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "aaf370e5-fa02-4a02-abee-01cc4058aace".into(), + name: "Idum's Forest Warden".into(), + roles: 4, + primary_stat: 4, // Spirit + author: "Idum".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "20f08cc1-b2c4-47ca-b5b1-d5cbcbd3d2f8".into(), + name: "Blood DK DPS".into(), + roles: 8, + primary_stat: 0, // Strength + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "8f1df486-d97f-4424-9b2f-8a032d88bbd6".into(), + name: "Bleed Berserker".into(), + roles: 8, + primary_stat: 1, // Agility + author: "Official".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "45fbe2e6-231a-4a25-827a-8d7b3da4501a".into(), + name: "Mur-Lock".into(), + roles: 8, + primary_stat: 3, // Intellect + author: "Official".into(), + difficulty: 2, + category: 1, + }, + ]; + } + + Ok(archetypes) +} + +/// Realm-aware pending companion deployment job. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompanionsPendingJob { + pub job_id: String, + pub server_instance_id: String, + pub realm: String, + pub count: u32, + pub level: Option, + pub class_id: Option, + pub spec_id: Option, + pub build_id: Option, + pub requested_operation: String, + pub created_at: u64, + pub state: String, // "pending", "in_progress", "completed", "failed" + pub completed_count: u32, + pub failed_count: u32, + pub last_error: Option, + pub schema_version: u32, +} + +pub fn pending_job_path(meta_dir: &Path, realm: &str) -> PathBuf { + meta_dir.join(format!("companions.pending.{realm}.json")) +} + +pub fn save_pending_job(meta_dir: &Path, realm: &str, job: &CompanionsPendingJob) -> Result<()> { + fsx::atomic_write_json(&pending_job_path(meta_dir, realm), job) +} + +pub fn load_pending_job(meta_dir: &Path, realm: &str) -> Result> { + let p = pending_job_path(meta_dir, realm); + if !p.exists() { + return Ok(None); + } + match fsx::read_json::(&p) { + Ok(job) => Ok(Some(job)), + Err(e) => { + tracing::warn!("Corrupted pending job file {:?}: {e}", p); + Ok(None) + } + } +} + +pub fn clear_pending_job(meta_dir: &Path, realm: &str) -> Result<()> { + let p = pending_job_path(meta_dir, realm); + if p.exists() { + let _ = std::fs::remove_file(p); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -152,4 +317,63 @@ mod tests { assert!(s.contains("@ACC")); assert!(!s.contains("INSERT INTO "), "rows that exist are kept"); } + + #[test] + fn pending_jobs_roundtrip_and_are_isolated_by_realm() { + let temp = std::env::temp_dir().join(format!("coa-test-jobs-{}", uuid::Uuid::new_v4().simple())); + std::fs::create_dir_all(&temp).unwrap(); + + let job_wc = CompanionsPendingJob { + job_id: "test-wc-1".into(), + server_instance_id: "inst-1".into(), + realm: "wildcard".into(), + count: 50, + level: Some(60), + class_id: Some(10), + spec_id: Some(1), + build_id: Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into()), + requested_operation: "spawn".into(), + created_at: 1000, + state: "pending".into(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + + let job_wcr = CompanionsPendingJob { + job_id: "test-wcr-1".into(), + server_instance_id: "inst-1".into(), + realm: "reborn".into(), + count: 10, + level: Some(60), + class_id: Some(7), + spec_id: Some(4), + build_id: None, + requested_operation: "spawn".into(), + created_at: 1001, + state: "pending".into(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + + save_pending_job(&temp, "wildcard", &job_wc).unwrap(); + save_pending_job(&temp, "reborn", &job_wcr).unwrap(); + + let loaded_wc = load_pending_job(&temp, "wildcard").unwrap().expect("wc job missing"); + let loaded_wcr = load_pending_job(&temp, "reborn").unwrap().expect("wcr job missing"); + let loaded_coa = load_pending_job(&temp, "coa").unwrap(); + + assert_eq!(loaded_wc, job_wc); + assert_eq!(loaded_wcr, job_wcr); + assert!(loaded_coa.is_none()); + + clear_pending_job(&temp, "wildcard").unwrap(); + assert!(load_pending_job(&temp, "wildcard").unwrap().is_none()); + assert!(load_pending_job(&temp, "reborn").unwrap().is_some()); + + let _ = std::fs::remove_dir_all(temp); + } } diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index 37dcb5e..95a92e2 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -1,108 +1,213 @@ //! Minimal Remote Access (RA) console client for the worldserver, local only. + //! Only a fixed set of typed operations is exposed; free-form commands are not accepted here. + + use std::io::{Read, Write}; + use std::net::{SocketAddr, TcpStream}; + use std::path::Path; + use std::time::Duration; + + use serde::{Deserialize, Serialize}; + + use crate::error::{Error, Result}; + use crate::fsx; + use crate::layout::read_ports; + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct RaSettings { + ra_username: String, + ra_password: String, + } + + #[derive(Debug)] + pub struct Ra { + stream: TcpStream, + } + + fn read_until(stream: &mut TcpStream, marker: &[u8]) -> Result { + let mut data = Vec::new(); + let mut byte = [0u8; 1]; + while !data.ends_with(marker) { + match stream.read(&mut byte) { + Ok(0) => { + return Err(Error::Invalid( + "The world console closed the connection.".into(), + )) + } + Ok(_) => data.push(byte[0]), + Err(e) => { + return Err(Error::Invalid(format!( + "The world console did not answer: {e}" + ))) + } + } + if data.len() > 256 * 1024 { + return Err(Error::Invalid( + "The world console sent too much data.".into(), + )); + } + } + Ok(String::from_utf8_lossy(&data).into_owned()) + } + + impl Ra { + /// Connect to the loopback RA port of the server in `root`, using the credentials from its `repack.json`. + pub fn connect(root: &Path) -> Result { + let cfg: RaSettings = fsx::read_json(&root.join("Settings/repack.json")) + .map_err(|_| Error::Invalid("The server console settings could not be read.".into()))?; + 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 = + TcpStream::connect_timeout(&addr, Duration::from_secs(5)).map_err(|_| { + Error::Invalid( + "The world server is not running (its console is not reachable).".into(), + ) + })?; + stream.set_read_timeout(Some(Duration::from_secs(15)))?; + stream.set_write_timeout(Some(Duration::from_secs(5)))?; + read_until(&mut stream, b"Username: ")?; + stream.write_all(format!("{user}\r\n").as_bytes())?; + read_until(&mut stream, b"Password: ")?; + stream.write_all(format!("{password}\r\n").as_bytes())?; + let banner = read_until(&mut stream, b"AC>") + .map_err(|_| Error::Invalid("The world console rejected the login.".into()))?; + if banner.to_lowercase().contains("authentication failed") { + return Err(Error::Invalid( + "The world console rejected the login.".into(), + )); + } + Ok(Ra { stream }) + } + + /// Send one already-validated console command and return its output. + pub fn run(&mut self, cmd: &str) -> Result { + let c = crate::console::check_command(cmd)?; + self.command(c) + } /// Send a command whose answer does not matter (`server shutdown`). The reply is still read (up to the next @@ -129,172 +234,339 @@ impl Ra { } fn command(&mut self, cmd: &str) -> Result { + debug_assert!(!cmd.contains(['\r', '\n'])); + self.stream.write_all(format!("{cmd}\r\n").as_bytes())?; + let out = read_until(&mut self.stream, b"AC>")?; + Ok(out.trim_end_matches("AC>").trim().to_string()) + } + + pub fn create_account(&mut self, name: &str, password: &str) -> Result<()> { + validate_account(name, password)?; + let out = self.command(&format!("account create {name} {password}"))?; + let l = out.to_lowercase(); + if l.contains("already exist") { + return Err(Error::Invalid("That account name is already taken.".into())); + } + if l.contains("created") { + Ok(()) + } else { + Err(Error::Invalid(format!( + "The server did not create the account: {}", + out.lines().last().unwrap_or("") + ))) + } + } + + /// `portable checkpoint `: the core saves this one character with a checkpoint marker. Only a + /// number, a session id and a number are sent. The reply is a request status, **not** proof that anything was written. + pub fn portable_checkpoint( + &mut self, + guid: u32, + session: crate::portable::SessionId, + sequence: u64, + ) -> Result { + use crate::portable::session::bridge::CheckpointReply; + let sequence = u32::try_from(sequence) + .map_err(|_| Error::Invalid("The checkpoint sequence is out of range.".into()))?; + let out = self.command(&format!("portable checkpoint {guid} {session} {sequence}"))?; + let first = out + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or(""); + Ok(match first.split_whitespace().next() { + Some("QUEUED") => CheckpointReply::Queued, + Some("BUSY") => CheckpointReply::Busy, + Some("NOT_ONLINE") => CheckpointReply::NotOnline, + Some("REFUSED") => { + CheckpointReply::Refused(first.trim_start_matches("REFUSED").trim().to_string()) + } + _ => CheckpointReply::Refused(format!("unexpected answer: {first}")), + }) + } + + /// `portable import `: the core imports the job file of that id from its fixed job directory. Only the id travels. + pub fn portable_import(&mut self, job_id: crate::portable::ImportId) -> Result { + let out = self.command(&format!("portable import {job_id}"))?; + let first = out + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("") + .to_string(); + if first.starts_with("OK") { + Ok(first) + } else { + Err(Error::Invalid(format!( + "The server did not import the job: {first}" + ))) + } + } + + /// `portable project `: the core decides what a projection of the job file's character at its level cap holds, and writes the + /// decision to the job's result file. Only the id travels. + pub fn portable_project(&mut self, job_id: crate::portable::ImportId) -> Result { + let out = self.command(&format!("portable project {job_id}"))?; + let first = out + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("") + .to_string(); + if first.starts_with("OK") { + Ok(first) + } else { + Err(Error::Invalid(format!( + "The server did not answer the projection query: {first}" + ))) + } + } + + /// `portable capabilities`: the realm's core says what it is and what portable features it has. An older core does not know the command. + pub fn portable_capabilities(&mut self) -> Result { + let out = self.command("portable capabilities")?; + crate::portable::capabilities::CoreReport::parse(&out) + .map_err(|e| Error::Invalid(e.to_string())) + } + + /// `portable release `: lets a held portable character play. Sent only after its baseline was persisted. + pub fn portable_release(&mut self, session: crate::portable::SessionId) -> Result<()> { + let out = self.command(&format!("portable release {session}"))?; + if out.lines().any(|l| l.trim().starts_with("OK")) { + Ok(()) + } else { + Err(Error::Invalid(format!( + "The server did not release the session: {}", + out.lines().last().unwrap_or("") + ))) + } + } + + /// World update timing from the server's own `server info` report (mean/median/percentiles of the last 500 updates). + pub fn performance(&mut self) -> Result> { + let out = self.command("server info")?; + Ok(parse_server_info(&out)) + } + + fn bot_command(&mut self, cmd: &str) -> Result { + let out = self.command(cmd)?; + if is_unsupported_command(&out) { + return Err(Error::CompanionCommandUnsupported); + } + Ok(out) + } + + /// Drop every bot still waiting to be created. Returns how many were waiting. + pub fn cancel_spawning(&mut self) -> Result { + Ok(first_number(&self.bot_command("botcmd spawncancel")?)) + } + + /// Log every bot out without deleting anything. Returns how many were online. + pub fn despawn_all(&mut self) -> Result { + Ok(first_number(&self.bot_command("botcmd despawnall")?)) + } + + /// Log one bot out (the character stays saved). False when that bot was not online. + pub fn despawn_bot(&mut self, guid: u64) -> Result { + Ok(self + .bot_command(&format!("botcmd despawn {guid}"))? + .to_lowercase() + .contains("despawned")) + } + + /// Log every bot out and delete every bot character for good (the caller saves a recovery point first). + pub fn purge_all(&mut self) -> Result { + let out = self.bot_command("botcmd purgeall")?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + + /// Ask the bot module to create `count` leveling bots (throttled by the module itself). Only a number is sent. + pub fn spawn_bots(&mut self, count: u32) -> Result { + if !(1..=2000).contains(&count) { + return Err(Error::Invalid( + "Choose between 1 and 2000 companions.".into(), + )); + } + let out = self.command(&format!("botcmd spawnleveled {count}"))?; + if out.to_lowercase().contains("no usable template characters") { + return Err(Error::CompanionTemplatesMissing); + } + Ok(out.lines().last().unwrap_or("").to_string()) + } + + /// Ask the bot module to spawn a fleet of bots of specific race and level (.botcmd spawnfleet ). + pub fn spawn_fleet(&mut self, race: u8, level: u8) -> Result { + let out = self.bot_command(&format!("botcmd spawnfleet {race} {level}"))?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + + pub fn spawn_custom( &mut self, count: u32, @@ -303,359 +575,703 @@ impl Ra { spec_id: Option, archetype: Option<&str>, ) -> Result { + let c = class_id.unwrap_or(0); + let s = spec_id.unwrap_or(0); + let a = archetype.unwrap_or("").trim(); let mut cmd = format!("botcmd spawncustom {count} {level}"); - if let Some(c) = class_id { + if !a.is_empty() { + cmd.push_str(&format!(" {c} {s} {a}")); + } else if s > 0 { + cmd.push_str(&format!(" {c} {s}")); + } else if c > 0 { 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")?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + + /// Set a new password for an existing account. + pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> { + validate_account(name, password)?; + let out = self.command(&format!( + "account set password {name} {password} {password}" + ))?; + account_reply(&out, "The password was not changed") + } + + /// Access level of an account on all realms: 0 player, 1 moderator, 2 game master, 3 administrator. + pub fn set_account_access(&mut self, name: &str, level: u8) -> Result<()> { + validate_account(name, "placeholder")?; + if level > 3 { + return Err(Error::Invalid("The access level must be 0 to 3.".into())); + } + let out = self.command(&format!("account set gmlevel {name} {level} -1"))?; + account_reply(&out, "The access level was not changed") + } + + /// Delete an account together with its characters (the console's `account delete`). + pub fn delete_account(&mut self, name: &str) -> Result<()> { + validate_account(name, "placeholder")?; + let out = self.command(&format!("account delete {name}"))?; + account_reply(&out, "The account was not deleted") + } + + /// Give `name` administrator rights on all realms (GM level 3). + pub fn make_administrator(&mut self, name: &str) -> Result<()> { + validate_account(name, "placeholder")?; + let out = self.command(&format!("account set gmlevel {name} 3 -1"))?; + if out.to_lowercase().contains("gm level") + || out.to_lowercase().contains("security") + || out.is_empty() + { + Ok(()) + } else { + Err(Error::Invalid(format!( + "Could not set administrator rights: {out}" + ))) + } + } + } + + /// The console reports a failed account command in words; anything else (including silence) counts as done. + fn account_reply(out: &str, what: &str) -> Result<()> { + let l = out.to_lowercase(); + let failed = [ + "does not exist", + "not exist", + "not found", + "do not match", + "don't match", + "usage", + "unknown", + "incorrect", + "error", + ]; + if failed.iter().any(|m| l.contains(m)) { + return Err(Error::Invalid(format!( + "{what}: {}", + out.lines().last().unwrap_or("").trim() + ))); + } + Ok(()) + } + + /// The console answers an unknown sub-command with the list of the ones it knows. + fn is_unsupported_command(out: &str) -> bool { + let l = out.to_lowercase(); + l.contains("possible subcommands") + || l.contains("### usage") + || l.contains("no such command") + || l.contains("unknown command") + } + + fn first_number(text: &str) -> u32 { + text.split(|c: char| !c.is_ascii_digit()) + .find(|t| !t.is_empty()) + .and_then(|t| t.parse().ok()) + .unwrap_or(0) + } + + /// How fast the world loop is running, read from `server info`. + #[derive(Debug, Clone, Serialize, PartialEq)] + pub struct Performance { + pub mean_ms: u32, + pub median_ms: u32, + pub p95_ms: u32, + pub p99_ms: u32, + pub max_ms: u32, + /// World updates per second implied by the mean update time. + pub ticks_per_sec: f32, + } + + fn ms(text: &str) -> Option { + text.trim().trim_end_matches("ms").trim().parse().ok() + } + + pub fn parse_server_info(text: &str) -> Option { + let (mut mean, mut median, mut pct) = (None, None, None); + for line in text.lines() { + let line = line + .trim() + .trim_start_matches('|') + .trim_start_matches('-') + .trim(); + if let Some(v) = line.strip_prefix("Mean:") { + mean = ms(v); + } else if let Some(v) = line.strip_prefix("Median:") { + median = ms(v); + } else if let Some(v) = line.strip_prefix("Percentiles (95, 99, max):") { + let p: Vec> = v.split(',').map(ms).collect(); + if p.len() == 3 { + pct = Some((p[0]?, p[1]?, p[2]?)); + } + } + } + let (mean_ms, median_ms, (p95_ms, p99_ms, max_ms)) = (mean?, median?, pct?); + Some(Performance { + mean_ms, + median_ms, + p95_ms, + p99_ms, + max_ms, + ticks_per_sec: 1000.0 / mean_ms.max(1) as f32, + }) + } + + /// Account names are letters/digits (3-17); passwords are 6-16 printable characters without spaces or quotes. + pub fn validate_account(name: &str, password: &str) -> Result<()> { + let bad = |m: &str| Err(Error::Invalid(m.into())); + // an underscore inside a name is allowed: the Manager gives joining players names like `DMITRY_7K4M` + if !(3..=17).contains(&name.len()) + || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + || name.starts_with('_') + || name.ends_with('_') + { + return bad("The username must be 3–17 letters or digits."); + } + if !(6..=16).contains(&password.len()) + || !password + .chars() + .all(|c| c.is_ascii_graphic() && c != '"' && c != '\'') + { + return bad("The password must be 6–16 characters (no spaces or quotes)."); + } + Ok(()) + } + + #[cfg(test)] + mod tests { + use super::*; + use std::io::{BufRead, BufReader}; + use std::net::TcpListener; + + /// These tests share the loopback interface; on some machines (security software hooking TCP) several + /// concurrent short-lived loopback connections are occasionally reset, so they run one at a time. + static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + fn serial() -> std::sync::MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn fake_ra(reply: &'static str) -> (u16, std::thread::JoinHandle>) { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let h = std::thread::spawn(move || { + let (mut s, _) = l.accept().unwrap(); + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut got = Vec::new(); + s.write_all(b"Username: ").unwrap(); + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + got.push(line.trim().to_string()); + s.write_all(b"Password: ").unwrap(); + line.clear(); + r.read_line(&mut line).unwrap(); + got.push(line.trim().to_string()); + s.write_all(b"Authentication Succeeded\r\nAC>").unwrap(); + line.clear(); + if r.read_line(&mut line).unwrap_or(0) > 0 { + got.push(line.trim().to_string()); + s.write_all(format!("{reply}\r\nAC>").as_bytes()).unwrap(); + } + // Close gracefully: dropping a socket with unread data would send RST and could discard the reply. + let _ = s.shutdown(std::net::Shutdown::Write); + let _ = s.set_read_timeout(Some(Duration::from_secs(10))); + let mut sink = [0u8; 64]; + while matches!(s.read(&mut sink), Ok(n) if n > 0) {} + got + }); + (port, h) + } + + #[test] + fn an_unknown_bot_subcommand_is_recognised_and_numbers_are_read_from_replies() { + assert!(is_unsupported_command( + "### USAGE: .botcmd ... + Possible subcommands: + |- botcmd despawn" + )); + assert!(!is_unsupported_command( + "BotMgr: cancelled 35 queued bot spawn(s)." + )); + assert_eq!( + first_number("BotMgr: cancelled 35 queued bot spawn(s)."), + 35 + ); + assert_eq!(first_number("nothing"), 0); + } + + #[test] + fn server_info_timing_is_parsed_and_unrelated_text_is_ignored() { + let text = "AzerothCore rev. x + Connected players: 0. Characters in world: 0. + Update time diff: 1ms. Last 500 diffs summary: + |- Mean: 14ms + |- Median: 15ms + |- Percentiles (95, 99, max): 24ms, 30ms, 61ms + AC>"; + let p = parse_server_info(text).unwrap(); + assert_eq!( + (p.mean_ms, p.median_ms, p.p95_ms, p.p99_ms, p.max_ms), + (14, 15, 24, 30, 61) + ); + assert!((p.ticks_per_sec - 71.4).abs() < 0.2); + assert!(parse_server_info("Connected players: 0.").is_none()); + } + + #[test] + fn creates_an_account_over_ra_with_the_expected_commands() { + let _lock = serial(); + let (port, h) = fake_ra("Account created: PLAYER1"); + let mut ra = Ra::connect_to(port, "local", "secretra").unwrap(); + ra.create_account("Player1", "hunter22").unwrap(); + drop(ra); + assert_eq!( + h.join().unwrap(), + ["local", "secretra", "account create Player1 hunter22"] + ); + } + + #[test] + fn changes_a_password_with_the_expected_command() { + let _lock = serial(); + let (port, h) = fake_ra("The password was changed"); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + ra.set_account_password("Player1", "newpass9").unwrap(); + drop(ra); + assert_eq!( + h.join().unwrap()[2], + "account set password Player1 newpass9 newpass9" + ); + } + + #[test] + fn changes_an_access_level_with_the_expected_command() { + let _lock = serial(); + let (port, h) = fake_ra("You have changed security level of Player1 to 2."); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + ra.set_account_access("Player1", 2).unwrap(); + assert!(ra.set_account_access("Player1", 4).is_err(), "only 0 to 3"); + drop(ra); + assert_eq!(h.join().unwrap()[2], "account set gmlevel Player1 2 -1"); + } + + #[test] + fn a_failed_account_command_is_reported_and_bad_names_never_reach_the_console() { + let _lock = serial(); + let (port, h) = fake_ra("Account not found."); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + assert!( + ra.set_account_password("x", "newpass9").is_err(), + "the name is validated before anything is sent" + ); + let error = ra + .set_account_password("Nobody", "newpass9") + .unwrap_err() + .to_string(); + assert!( + error.contains("not found"), + "Unexpected console error: {error}" + ); + drop(ra); + let _ = h.join(); + } + + #[test] + fn spawn_bots_sends_only_a_bounded_number() { + let _lock = serial(); + let (port, h) = fake_ra("Queued 50 bots"); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + assert_eq!(ra.spawn_bots(50).unwrap(), "Queued 50 bots"); + assert!(ra.spawn_bots(0).is_err() && ra.spawn_bots(5000).is_err()); + drop(ra); + assert_eq!(h.join().unwrap()[2], "botcmd spawnleveled 50"); + } + + #[test] + fn duplicate_account_and_input_validation() { + let _lock = serial(); + let (port, h) = fake_ra("Account already exist."); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + assert!(ra + .create_account("Player1", "hunter22") + .unwrap_err() + .to_string() + .contains("already taken")); + drop(ra); + let _ = h.join(); + for (n, p) in [ + ("ab", "hunter22"), + ("bad name", "hunter22"), + ("Player1", "short"), + ("Player1", "has space1"), + ("Player1", "quote\"pw1"), + ("Pl\r\nayer", "hunter22"), + ("x".repeat(18).as_str(), "hunter22"), + ] { + assert!(validate_account(n, p).is_err(), "{n:?} {p:?}"); + } + validate_account("Player1", "hunter22").unwrap(); + } + + #[test] + fn unreachable_console_gives_a_friendly_error() { + let _lock = serial(); + // Port 1 is never used by a game server; probing a freed ephemeral port would race with the other tests. + assert!(Ra::connect_to(1, "u", "p") + .unwrap_err() + .to_string() + .contains("not running")); + } + } + diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 84f15b9..99de785 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -24,3 +24,4 @@ coa-core = { path = "../crates/coa-core" } coa-registry-proto = { path = "../crates/coa-registry-proto" } coa-control-proto = { path = "../crates/coa-control-proto" } tracing = "0.1" +uuid = { version = "1", features = ["v4"] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dfcf788..5f507b9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -633,7 +633,34 @@ async fn start_server( if coa_core::realms::guard_module(&r, "companions").is_err() { return Ok(()); } - let pending = meta_dir(&r)?.join("companions.pending.json"); + let meta = meta_dir(&r)?; + for mode in [ + coa_core::realms::Mode::Coa, + coa_core::realms::Mode::Wildcard, + coa_core::realms::Mode::Reborn, + ] { + if let Ok(Some(job)) = coa_core::companions::load_pending_job(&meta, mode.name()) { + let _ = coa_core::companions::clear_pending_job(&meta, mode.name()); + if job.count > 0 { + if let Ok(admin_db) = coa_core::db::Db::from_repack(&r, coa_core::db::Account::Admin) { + if let Ok(target) = coa_core::multiworld::resolve_bot_operation_target(&r, mode) { + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db); + } + } + if let Ok(mut ra) = Ra::connect_target(&r, Some(mode)) { + let res = if let Some(lvl) = job.level { + ra.spawn_custom(job.count, lvl, job.class_id, job.spec_id, job.build_id.as_deref()) + } else { + ra.spawn_bots(job.count) + }; + if let Err(e) = res { + tracing::warn!("pending companions for realm {} were not created: {e}", mode.name()); + } + } + } + } + } + let pending = meta.join("companions.pending.json"); if let Ok(v) = coa_core::fsx::read_json::(&pending) { let _ = std::fs::remove_file(&pending); let n = v["count"].as_u64().unwrap_or(0) as u32; @@ -2057,7 +2084,8 @@ async fn add_companions( let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); - let existing_max = config::load(&root, Scope::Bots) + let existing_max = config::load(&target.world_root, Scope::Bots) + .or_else(|_| config::load(&root, Scope::Bots)) .ok() .and_then(|v| { v.settings @@ -2073,7 +2101,8 @@ async fn add_companions( "CoaBots.AutoLogin.MaxCount".to_string(), Value::from(existing_max.max(already + count).min(5000)), ); - config::save(&root, &meta, Scope::Bots, &changes)?; + let _ = config::save(&target.world_root, &meta, Scope::Bots, &changes) + .or_else(|_| config::save(&root, &meta, Scope::Bots, &changes)); let mut baseline = None; let spawned = if target.running { @@ -2090,10 +2119,33 @@ async fn add_companions( Some(ra.spawn_bots(count)?) } } else { - coa_core::fsx::atomic_write_json( - &meta.join("companions.pending.json"), - &serde_json::json!({ "count": count }), - )?; + let job = coa_core::companions::CompanionsPendingJob { + job_id: uuid::Uuid::new_v4().to_string(), + server_instance_id: id.clone(), + realm: mode.name().to_string(), + count, + level, + class_id, + spec_id, + build_id: archetype.clone(), + requested_operation: "spawn".to_string(), + created_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + state: "pending".to_string(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + coa_core::companions::save_pending_job(&meta, mode.name(), &job)?; + if mode == coa_core::realms::Mode::Coa { + let _ = coa_core::fsx::atomic_write_json( + &meta.join("companions.pending.json"), + &serde_json::json!({ "count": count }), + ); + } None }; tracing::info!(count, spawned = spawned.is_some(), "companions requested"); @@ -2106,6 +2158,27 @@ async fn add_companions( .await } +#[tauri::command] +async fn get_wildcard_archetypes( + state: State<'_, AppState>, + id: String, +) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?; + let target = coa_core::multiworld::resolve_bot_operation_target(&root, coa_core::realms::Mode::Wildcard) + .unwrap_or_else(|_| coa_core::multiworld::BotOperationTarget { + world_root: root.clone(), + chars_db: "acore_characters_wildcard", + ra_port: 3444, + running: false, + realm: coa_core::realms::Mode::Wildcard, + }); + Ok(coa_core::companions::list_wildcard_archetypes(&db, target.chars_db)?) + }) + .await +} + const REMOTE_CLIENT_ID: &str = "@remote-client"; fn remote_dir() -> PathBuf { @@ -3206,6 +3279,7 @@ pub fn run() { report_targets, companion_sizes, add_companions, + get_wildcard_archetypes, remote_connection, remote_connect, client_info, diff --git a/src/lib/api.ts b/src/lib/api.ts index 8af8dac..d443522 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -360,6 +360,16 @@ export interface CompanionSizes { sizes: { id: string; title: string; bots: number; warning: string | null }[]; } +export interface WildcardArchetypeDto { + id: string; + name: string; + roles: number; + primary_stat: number; + author: string; + difficulty: number; + category: number; +} + export interface ClientInfo { path: string; executable: string; @@ -599,6 +609,7 @@ export const api = { spec_id: specId ?? null, archetype: archetype ?? null, }), + getWildcardArchetypes: (id: string) => invoke("get_wildcard_archetypes", { id }), clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientInfo: (id: string) => invoke("client_info", { id }), diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index c4dd45a..a97c264 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -16,11 +16,32 @@ import { type RealmMode, type RealmProfiles, type UiError, + type WildcardArchetypeDto, } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT } from "@/i18n"; +function formatRole(roles: number): string { + const parts: string[] = []; + if (roles & 1) parts.push("Tank"); + if (roles & 2) parts.push("Melee"); + if (roles & 4) parts.push("Ranged"); + if (roles & 8) parts.push("Healer"); + return parts.join("/") || "DPS"; +} + +function formatStat(stat: number): string { + switch (stat) { + case 0: return "Strength"; + case 1: return "Agility"; + case 2: return "Stamina"; + case 3: return "Intellect"; + case 4: return "Spirit"; + default: return "All"; + } +} + export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); @@ -39,6 +60,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const [selectedClass, setSelectedClass] = useState("all"); const [selectedRole, setSelectedRole] = useState("all"); const [selectedArchetype, setSelectedArchetype] = useState("all"); + const [wildcardArchetypes, setWildcardArchetypes] = useState([]); // Operational state const [busy, setBusy] = useState(false); @@ -83,6 +105,20 @@ export function CompanionsCard({ serverId }: { serverId: string }) { } }, [selectedRealm, maxLevelForRealm, targetLevel]); + // Load wildcard archetypes dynamically from target characters db + useEffect(() => { + if (selectedRealm === "wildcard") { + api.getWildcardArchetypes(serverId) + .then((archs) => setWildcardArchetypes(archs)) + .catch(() => {}); + if (selectedClass === "all") { + setSelectedClass("10"); + } + } else { + setSelectedArchetype("all"); + } + }, [serverId, selectedRealm]); + // Load startup settings useEffect(() => { void api @@ -163,7 +199,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); setNote(out || `Spawned level ${targetLevel} fleet`); } else { - const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : undefined; + const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : (selectedRealm === "wildcard" ? 10 : undefined); let specNum: number | undefined = undefined; if (selectedRole === "tank") { if (selectedRealm === "reborn") { @@ -601,12 +637,11 @@ export function CompanionsCard({ serverId }: { serverId: string }) { {selectedRealm === "wildcard" && ( <> - - - - - - + {wildcardArchetypes.map((b) => ( + + ))} )} {selectedRealm === "reborn" && (