mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 11:25:56 +00:00
Phase 3: config engine (line-preserving parser, schemas, validation, atomic save, snapshots, merge, presets) and Bots/Server settings UI
Verified: 28 real config files round-trip byte-identical; native UI edit changes exactly one line in template and generated conf; snapshot restore is byte-exact. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
19024a3162
commit
5b5255cca8
18 files changed
+3668
-3
No files matched your search
@@ -0,0 +1,49 @@
|
||||
//! Read-only sanity check of the config engine against a real server folder.
|
||||
use coa_core::config::{self, parser::ConfFile, Scope};
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let root = std::env::args().nth(1).expect("usage: config_check <server folder>");
|
||||
let root = Path::new(&root);
|
||||
|
||||
let mut files = 0;
|
||||
for dir in ["Core/configs", "Core/configs/modules", "Settings"] {
|
||||
let Ok(rd) = std::fs::read_dir(root.join(dir)) else { continue };
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
let name = p.file_name().unwrap().to_string_lossy().to_lowercase();
|
||||
if !p.is_file() || !(name.contains(".conf") || name.contains(".template")) {
|
||||
continue;
|
||||
}
|
||||
let bytes = std::fs::read(&p).unwrap();
|
||||
match ConfFile::parse_bytes(&bytes) {
|
||||
Ok(c) => {
|
||||
assert_eq!(c.to_text().as_bytes(), &bytes[..], "round-trip mismatch: {}", p.display());
|
||||
files += 1;
|
||||
}
|
||||
Err(e) => println!("skipped {}: {e}", p.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("round-trip identical for {files} files");
|
||||
|
||||
for scope in [Scope::Bots, Scope::Server] {
|
||||
match config::load(root, scope) {
|
||||
Ok(v) => {
|
||||
let present = v.settings.iter().filter(|s| s.present).count();
|
||||
let problems: Vec<_> = v.settings.iter().filter(|s| s.problem.is_some()).map(|s| (&s.meta.key, s.problem.clone().unwrap())).collect();
|
||||
let missing: Vec<_> = v.settings.iter().filter(|s| !s.present).map(|s| s.meta.key.as_str()).collect();
|
||||
let non_default = v.settings.iter().filter(|s| s.present && !s.is_default).count();
|
||||
println!(
|
||||
"{scope:?}: {} settings, {present} present, {non_default} non-default, {} unknown keys, drift {:?}\n problems {:?}\n missing {:?}",
|
||||
v.settings.len(), v.unknown_keys, v.drift_keys, problems, missing
|
||||
);
|
||||
for p in scope.presets() {
|
||||
let pv = config::preview_preset(root, scope, &p.id).unwrap();
|
||||
println!(" preset {:<14} would change {} settings", p.id, pv.changes.len());
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{scope:?}: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Non-destructive `.dist` merge: add keys a newer `.dist` introduced, never touch existing values,
|
||||
//! and only *report* keys the newer `.dist` no longer has.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use super::parser::ConfFile;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct MergePlan {
|
||||
pub added: Vec<String>,
|
||||
/// Present in the user's file but unknown to the `.dist` (possibly removed upstream, possibly a custom setting).
|
||||
pub not_in_dist: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn plan(conf: &ConfFile, dist: &ConfFile) -> MergePlan {
|
||||
let added = dist.entries().map(|(k, _)| k).filter(|k| !conf.contains(k)).map(str::to_string).collect::<Vec<_>>();
|
||||
let not_in_dist = conf.entries().map(|(k, _)| k).filter(|k| !dist.contains(k)).map(str::to_string).collect();
|
||||
MergePlan { added: dedup(added), not_in_dist: dedup(not_in_dist) }
|
||||
}
|
||||
|
||||
fn dedup(mut v: Vec<String>) -> Vec<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
v.retain(|k| seen.insert(k.clone()));
|
||||
v
|
||||
}
|
||||
|
||||
/// Apply the additive part of the plan to `conf`; returns what was added.
|
||||
pub fn apply(conf: &mut ConfFile, dist: &ConfFile) -> MergePlan {
|
||||
let plan = plan(conf, dist);
|
||||
for key in &plan.added {
|
||||
let value = dist.get(key).unwrap_or_default().to_string();
|
||||
let mut doc = dist.doc_for(key);
|
||||
doc.push("(added by CoA Server Manager from the updated .dist)".into());
|
||||
let refs: Vec<&str> = doc.iter().map(String::as_str).collect();
|
||||
conf.set(key, &value, &refs);
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adds_new_keys_with_docs_and_preserves_user_values_and_unknowns() {
|
||||
let mut conf = ConfFile::parse("[worldserver]\nA = 42\n# mine\nCustom.Key = 1\n");
|
||||
let dist = ConfFile::parse("[worldserver]\n# About A\nA = 1\n# About B\n# second line\nB = \"x\"\n");
|
||||
let before = conf.to_text();
|
||||
let p = apply(&mut conf, &dist);
|
||||
assert_eq!(p.added, ["B"]);
|
||||
assert_eq!(p.not_in_dist, ["Custom.Key"]);
|
||||
let out = conf.to_text();
|
||||
assert!(out.starts_with(&before), "existing content is untouched");
|
||||
assert!(out.contains("# About B\n# second line\n# (added by CoA Server Manager from the updated .dist)\nB = \"x\"\n"), "{out}");
|
||||
assert_eq!(conf.get("A"), Some("42"));
|
||||
assert_eq!(conf.get("Custom.Key"), Some("1"));
|
||||
// idempotent
|
||||
assert!(apply(&mut conf, &dist).added.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_upstream_keys_are_reported_not_deleted() {
|
||||
let mut conf = ConfFile::parse("Old.Key = 5\nKeep = 1\n");
|
||||
let dist = ConfFile::parse("Keep = 1\n");
|
||||
let p = apply(&mut conf, &dist);
|
||||
assert_eq!(p.not_in_dist, ["Old.Key"]);
|
||||
assert_eq!(conf.get("Old.Key"), Some("5"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
//! Safe configuration editing: schema-driven, line-preserving, validated, snapshotted and atomically written.
|
||||
|
||||
pub mod merge;
|
||||
pub mod parser;
|
||||
pub mod schema;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{Error, FieldError, Result};
|
||||
use crate::fsx;
|
||||
use parser::ConfFile;
|
||||
use schema::{values_equal, Category, Preset, PresetFile, Restart, Schema, Setting};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Scope {
|
||||
Bots,
|
||||
Server,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn schema(self) -> &'static Schema {
|
||||
static BOTS: OnceLock<Schema> = OnceLock::new();
|
||||
static SERVER: OnceLock<Schema> = OnceLock::new();
|
||||
match self {
|
||||
Scope::Bots => BOTS.get_or_init(|| Schema::parse(include_str!("../../../../schemas/bots.json")).expect("bots schema")),
|
||||
Scope::Server => SERVER.get_or_init(|| Schema::parse(include_str!("../../../../schemas/server.json")).expect("server schema")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn presets(self) -> &'static [Preset] {
|
||||
static BOTS: OnceLock<PresetFile> = OnceLock::new();
|
||||
static SERVER: OnceLock<PresetFile> = OnceLock::new();
|
||||
let f = match self {
|
||||
Scope::Bots => BOTS.get_or_init(|| serde_json::from_str(include_str!("../../../../schemas/presets/bots.json")).expect("bots presets")),
|
||||
Scope::Server => SERVER.get_or_init(|| serde_json::from_str(include_str!("../../../../schemas/presets/server.json")).expect("server presets")),
|
||||
};
|
||||
&f.presets
|
||||
}
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Scope::Bots => "bots",
|
||||
Scope::Server => "server",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Files that carry a scope's settings. `read` is what the next server start will use.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Targets {
|
||||
pub read: PathBuf,
|
||||
/// Every file a change must be written to (always includes `read`).
|
||||
pub writes: Vec<PathBuf>,
|
||||
/// The generated file the launcher rewrites from a template at each start, when applicable.
|
||||
pub generated: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub fn targets(root: &Path, scope: Scope) -> Result<Targets> {
|
||||
match scope {
|
||||
Scope::Bots => {
|
||||
let conf = root.join("Core/configs/modules/mod_coa_playerbots.conf");
|
||||
if !conf.is_file() {
|
||||
return Err(Error::Invalid("CoA Companions (bots) are not installed on this server.".into()));
|
||||
}
|
||||
Ok(Targets { read: conf.clone(), writes: vec![conf], generated: None })
|
||||
}
|
||||
Scope::Server => {
|
||||
let conf = root.join("Core/configs/worldserver.conf");
|
||||
let template = root.join("Settings/worldserver.conf.template");
|
||||
match (template.is_file(), conf.is_file()) {
|
||||
(true, true) => Ok(Targets { read: template.clone(), writes: vec![template, conf.clone()], generated: Some(conf) }),
|
||||
(true, false) => Ok(Targets { read: template.clone(), writes: vec![template], generated: None }),
|
||||
(false, true) => Ok(Targets { read: conf.clone(), writes: vec![conf], generated: None }),
|
||||
(false, false) => Err(Error::Invalid("worldserver.conf was not found.".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_conf(path: &Path) -> Result<ConfFile> {
|
||||
ConfFile::parse_bytes(&fs::read(path)?)
|
||||
}
|
||||
|
||||
fn has_placeholder(raw: &str) -> bool {
|
||||
let t = raw.trim().trim_matches('"');
|
||||
t.starts_with('@') && t.ends_with('@') && t.len() > 2
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SettingView {
|
||||
#[serde(flatten)]
|
||||
pub meta: Setting,
|
||||
pub value: Value,
|
||||
pub is_default: bool,
|
||||
/// The key exists in the configuration file (otherwise `value` is the built-in default).
|
||||
pub present: bool,
|
||||
/// The file holds a value that is not valid for this setting.
|
||||
pub problem: Option<String>,
|
||||
/// Manual edit of the generated file that the launcher will overwrite at next start.
|
||||
pub drift: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SettingsView {
|
||||
pub scope: Scope,
|
||||
pub categories: Vec<Category>,
|
||||
pub settings: Vec<SettingView>,
|
||||
/// Keys in the file the schema does not know (kept untouched).
|
||||
pub unknown_keys: usize,
|
||||
pub drift_keys: Vec<String>,
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
/// Keys whose value in the generated conf differs from the template (i.e. hand edits the launcher will reset).
|
||||
pub fn drift(root: &Path) -> Result<Vec<String>> {
|
||||
let t = targets(root, Scope::Server)?;
|
||||
let Some(generated) = &t.generated else { return Ok(Vec::new()) };
|
||||
let (template, conf) = (load_conf(&t.read)?, load_conf(generated)?);
|
||||
let mut keys = BTreeSet::new();
|
||||
for (k, v) in conf.entries() {
|
||||
match template.get(k) {
|
||||
Some(tv) if has_placeholder(tv) => {}
|
||||
Some(tv) if tv.trim() != v.trim() => {
|
||||
keys.insert(k.to_string());
|
||||
}
|
||||
None => {
|
||||
keys.insert(k.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(keys.into_iter().collect())
|
||||
}
|
||||
|
||||
pub fn load(root: &Path, scope: Scope) -> Result<SettingsView> {
|
||||
let schema = scope.schema();
|
||||
let t = targets(root, scope)?;
|
||||
let conf = load_conf(&t.read)?;
|
||||
let drift_keys = if scope == Scope::Server { drift(root).unwrap_or_default() } else { Vec::new() };
|
||||
let known: BTreeSet<&str> = schema.settings.iter().map(|s| s.key.as_str()).collect();
|
||||
let unknown_keys = conf.entries().filter(|(k, _)| !known.contains(k)).count();
|
||||
|
||||
let settings = schema
|
||||
.settings
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let raw = conf.get(&s.key);
|
||||
let (value, problem) = match raw {
|
||||
Some(r) => match s.from_raw(r) {
|
||||
Ok(v) => (v, None),
|
||||
Err(e) => (s.default.clone(), Some(e)),
|
||||
},
|
||||
None => (s.default.clone(), None),
|
||||
};
|
||||
SettingView {
|
||||
is_default: values_equal(&value, &s.default),
|
||||
present: raw.is_some(),
|
||||
problem,
|
||||
drift: drift_keys.iter().any(|k| *k == s.key),
|
||||
value,
|
||||
meta: s.clone(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(SettingsView {
|
||||
scope,
|
||||
categories: schema.categories.clone(),
|
||||
settings,
|
||||
unknown_keys,
|
||||
drift_keys,
|
||||
files: t.writes.iter().map(|p| p.to_string_lossy().into_owned()).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Pairs that must satisfy `min <= max` after a save.
|
||||
const ORDERED_PAIRS: [(&str, &str); 6] = [
|
||||
("CoaBots.Profile.IntentMinMs", "CoaBots.Profile.IntentMaxMs"),
|
||||
("CoaBots.WorldBrain.PlannerMinMs", "CoaBots.WorldBrain.PlannerMaxMs"),
|
||||
("CoaBots.WorldBrain.ScanMinMs", "CoaBots.WorldBrain.ScanMaxMs"),
|
||||
("CoaBots.WorldBrain.MountDistanceMin", "CoaBots.WorldBrain.MountDistanceMax"),
|
||||
("CoaBots.WorldBrain.PartyMinMinutes", "CoaBots.WorldBrain.PartyMaxMinutes"),
|
||||
("CoaBots.WorldBrain.QuestSuspendMs", "CoaBots.WorldBrain.QuestSuspendMaxMs"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Change {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
pub from: Option<Value>,
|
||||
pub to: Value,
|
||||
pub restart: Restart,
|
||||
pub dangerous: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SaveReport {
|
||||
pub changed: Vec<Change>,
|
||||
/// Strongest restart any changed setting needs, if any changed.
|
||||
pub restart: Option<Restart>,
|
||||
pub snapshot: Option<String>,
|
||||
}
|
||||
|
||||
fn effective(view: &SettingsView, changes: &BTreeMap<String, Value>, key: &str) -> Option<f64> {
|
||||
changes
|
||||
.get(key)
|
||||
.and_then(Value::as_f64)
|
||||
.or_else(|| view.settings.iter().find(|s| s.meta.key == key).and_then(|s| s.value.as_f64()))
|
||||
}
|
||||
|
||||
/// Validate `changes` against the schema without writing anything.
|
||||
pub fn validate(root: &Path, scope: Scope, changes: &BTreeMap<String, Value>) -> Result<BTreeMap<String, String>> {
|
||||
let schema = scope.schema();
|
||||
let mut errors = Vec::new();
|
||||
let mut raws = BTreeMap::new();
|
||||
for (key, value) in changes {
|
||||
match schema.get(key) {
|
||||
None => errors.push(FieldError { key: key.clone(), message: "is not a setting the Manager can change".into() }),
|
||||
Some(s) => match s.to_raw(value) {
|
||||
Ok(raw) => {
|
||||
raws.insert(key.clone(), raw);
|
||||
}
|
||||
Err(m) => errors.push(FieldError { key: key.clone(), message: m }),
|
||||
},
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
let view = load(root, scope)?;
|
||||
for (lo, hi) in ORDERED_PAIRS {
|
||||
if !(changes.contains_key(lo) || changes.contains_key(hi)) {
|
||||
continue;
|
||||
}
|
||||
if let (Some(a), Some(b)) = (effective(&view, changes, lo), effective(&view, changes, hi)) {
|
||||
if a > b {
|
||||
let key = if changes.contains_key(lo) { lo } else { hi };
|
||||
errors.push(FieldError { key: key.into(), message: format!("the minimum ({lo}) cannot be larger than the maximum ({hi})") });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(raws)
|
||||
} else {
|
||||
Err(Error::Validation(errors))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where snapshots of a scope's files are kept.
|
||||
fn snapshot_root(meta_dir: &Path) -> PathBuf {
|
||||
meta_dir.join("backups").join("config")
|
||||
}
|
||||
|
||||
const KEEP_SNAPSHOTS: usize = 40;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
|
||||
struct SnapshotFile {
|
||||
original: String,
|
||||
stored: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
|
||||
pub struct SnapshotInfo {
|
||||
pub id: String,
|
||||
pub scope: Scope,
|
||||
pub reason: String,
|
||||
pub created_at: String,
|
||||
files: Vec<SnapshotFile>,
|
||||
}
|
||||
|
||||
fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec<u8>)]) -> Result<String> {
|
||||
let id = format!("{}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"), scope.name());
|
||||
let dir = snapshot_root(meta_dir).join(&id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let mut entries = Vec::new();
|
||||
for (i, (path, bytes)) in files.iter().enumerate() {
|
||||
let stored = format!("{i}_{}", path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
|
||||
fsx::atomic_write(&dir.join(&stored), bytes)?;
|
||||
entries.push(SnapshotFile { original: path.to_string_lossy().into_owned(), stored });
|
||||
}
|
||||
let info = SnapshotInfo { id: id.clone(), scope, reason: reason.into(), created_at: chrono::Utc::now().to_rfc3339(), files: entries };
|
||||
fsx::atomic_write_json(&dir.join("snapshot.json"), &info)?;
|
||||
prune_snapshots(meta_dir);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn prune_snapshots(meta_dir: &Path) {
|
||||
let Ok(rd) = fs::read_dir(snapshot_root(meta_dir)) else { return };
|
||||
let mut dirs: Vec<_> = rd.filter_map(|e| e.ok()).filter(|e| e.path().join("snapshot.json").is_file()).map(|e| e.path()).collect();
|
||||
dirs.sort();
|
||||
while dirs.len() > KEEP_SNAPSHOTS {
|
||||
let _ = fs::remove_dir_all(dirs.remove(0));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_snapshots(meta_dir: &Path) -> Vec<SnapshotInfo> {
|
||||
let mut out: Vec<SnapshotInfo> = fs::read_dir(snapshot_root(meta_dir))
|
||||
.map(|rd| rd.filter_map(|e| e.ok()).filter_map(|e| fsx::read_json(&e.path().join("snapshot.json")).ok()).collect())
|
||||
.unwrap_or_default();
|
||||
out.sort_by(|a, b| b.id.cmp(&a.id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply validated `changes`. Nothing is written unless every change is valid; previous contents are snapshotted first.
|
||||
pub fn save(root: &Path, meta_dir: &Path, scope: Scope, changes: &BTreeMap<String, Value>) -> Result<SaveReport> {
|
||||
let raws = validate(root, scope, changes)?;
|
||||
let schema = scope.schema();
|
||||
let t = targets(root, scope)?;
|
||||
let current = load(root, scope)?;
|
||||
|
||||
let mut originals: Vec<(PathBuf, Vec<u8>)> = Vec::new();
|
||||
let mut confs: Vec<ConfFile> = Vec::new();
|
||||
for p in &t.writes {
|
||||
let bytes = fs::read(p)?;
|
||||
confs.push(ConfFile::parse_bytes(&bytes)?);
|
||||
originals.push((p.clone(), bytes));
|
||||
}
|
||||
|
||||
let mut changed = Vec::new();
|
||||
for (key, raw) in &raws {
|
||||
let setting = schema.get(key).expect("validated");
|
||||
let view = current.settings.iter().find(|s| s.meta.key == *key).expect("in schema");
|
||||
let same_everywhere = confs.iter().all(|c| c.get(key).map(str::trim) == Some(raw.as_str()));
|
||||
if same_everywhere {
|
||||
continue;
|
||||
}
|
||||
for c in &mut confs {
|
||||
c.set(key, raw, &["Added by CoA Server Manager"]);
|
||||
}
|
||||
changed.push(Change {
|
||||
key: key.clone(),
|
||||
title: setting.title.clone(),
|
||||
from: view.present.then(|| view.value.clone()),
|
||||
to: changes[key].clone(),
|
||||
restart: setting.restart_required,
|
||||
dangerous: setting.dangerous,
|
||||
});
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Ok(SaveReport { changed, restart: None, snapshot: None });
|
||||
}
|
||||
|
||||
// Verify what we are about to write before touching the disk.
|
||||
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
|
||||
for text in &texts {
|
||||
let reread = ConfFile::parse(text);
|
||||
for c in &changed {
|
||||
if reread.get(&c.key).map(str::trim) != Some(raws[&c.key].as_str()) {
|
||||
return Err(Error::Invalid(format!("internal check failed for {}", c.key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let reason = format!("before changing {} setting(s)", changed.len());
|
||||
let snapshot = take_snapshot(meta_dir, scope, &reason, &originals)?;
|
||||
|
||||
let mut written = 0;
|
||||
for (i, (path, _)) in originals.iter().enumerate() {
|
||||
if let Err(e) = fsx::atomic_write(path, texts[i].as_bytes()) {
|
||||
for (p, bytes) in originals.iter().take(written) {
|
||||
let _ = fsx::atomic_write(p, bytes);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
written += 1;
|
||||
}
|
||||
let restart = changed.iter().map(|c| c.restart).max();
|
||||
tracing::info!(scope = scope.name(), changed = changed.len(), %snapshot, "configuration saved");
|
||||
Ok(SaveReport { changed, restart, snapshot: Some(snapshot) })
|
||||
}
|
||||
|
||||
/// Put a snapshot's files back (after snapshotting the current state, so a restore is itself undoable).
|
||||
pub fn restore_snapshot(meta_dir: &Path, id: &str) -> Result<()> {
|
||||
if id.contains(['/', '\\']) || id.contains("..") {
|
||||
return Err(Error::PathRejected(id.into()));
|
||||
}
|
||||
let dir = snapshot_root(meta_dir).join(id);
|
||||
let info: SnapshotInfo = fsx::read_json(&dir.join("snapshot.json"))?;
|
||||
let mut current = Vec::new();
|
||||
for f in &info.files {
|
||||
let p = PathBuf::from(&f.original);
|
||||
if let Ok(bytes) = fs::read(&p) {
|
||||
current.push((p, bytes));
|
||||
}
|
||||
}
|
||||
take_snapshot(meta_dir, info.scope, "before restoring a snapshot", ¤t)?;
|
||||
for f in &info.files {
|
||||
fsx::atomic_write(Path::new(&f.original), &fs::read(dir.join(&f.stored))?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PresetChange {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
pub from: Value,
|
||||
pub to: Value,
|
||||
pub dangerous: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PresetPreview {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub changes: Vec<PresetChange>,
|
||||
}
|
||||
|
||||
fn diff(view: &SettingsView, wanted: impl Iterator<Item = (String, Value)>) -> Vec<PresetChange> {
|
||||
wanted
|
||||
.filter_map(|(key, to)| {
|
||||
let s = view.settings.iter().find(|s| s.meta.key == key)?;
|
||||
(!values_equal(&s.value, &to) || !s.present).then(|| PresetChange { title: s.meta.title.clone(), from: s.value.clone(), dangerous: s.meta.dangerous, key, to })
|
||||
})
|
||||
.filter(|c| !values_equal(&c.from, &c.to))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What applying a preset would change. Nothing is written; the UI shows "This preset will change N settings".
|
||||
pub fn preview_preset(root: &Path, scope: Scope, preset_id: &str) -> Result<PresetPreview> {
|
||||
let preset = scope.presets().iter().find(|p| p.id == preset_id).ok_or_else(|| Error::Invalid(format!("unknown preset {preset_id}")))?;
|
||||
let view = load(root, scope)?;
|
||||
let changes = diff(&view, preset.values.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
Ok(PresetPreview { id: preset.id.clone(), title: preset.title.clone(), description: preset.description.clone(), changes })
|
||||
}
|
||||
|
||||
/// "Restore recommended defaults": every non-default setting back to its schema default.
|
||||
pub fn preview_defaults(root: &Path, scope: Scope) -> Result<PresetPreview> {
|
||||
let view = load(root, scope)?;
|
||||
let changes = diff(&view, view.settings.iter().map(|s| (s.meta.key.clone(), s.meta.default.clone())));
|
||||
Ok(PresetPreview { id: "defaults".into(), title: "Recommended defaults".into(), description: "Every setting returns to its default value.".into(), changes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("srv");
|
||||
let meta = dir.path().join("srv.manager");
|
||||
crate::layout::testkit::fake_repack(&root);
|
||||
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||
let world = "# Server\r\n[worldserver]\r\nRealmID = 1\r\nWorldServerPort = @WORLD_PORT@\r\n\r\n# XP\r\nRate.XP.Kill = 1\r\nRate.Drop.Money = 1\r\nUnknown.Custom = \"keep me\"\r\nPlayerLimit = 0\r\n";
|
||||
fs::write(root.join("Settings/worldserver.conf.template"), world).unwrap();
|
||||
fs::write(root.join("Core/configs/worldserver.conf"), world.replace("@WORLD_PORT@", "8085")).unwrap();
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
(dir, root, meta)
|
||||
}
|
||||
|
||||
fn set(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
|
||||
pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_presets_are_self_consistent() {
|
||||
for scope in [Scope::Bots, Scope::Server] {
|
||||
let schema = scope.schema();
|
||||
assert!(!schema.settings.is_empty());
|
||||
for p in scope.presets() {
|
||||
for (k, v) in &p.values {
|
||||
let s = schema.get(k).unwrap_or_else(|| panic!("preset {} references unknown {k}", p.id));
|
||||
s.to_raw(v).unwrap_or_else(|e| panic!("preset {} value for {k}: {e}", p.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_reads_values_defaults_and_counts_unknowns() {
|
||||
let (_d, root, _m) = fixture();
|
||||
let v = load(&root, Scope::Server).unwrap();
|
||||
let xp = v.settings.iter().find(|s| s.meta.key == "Rate.XP.Kill").unwrap();
|
||||
assert_eq!(xp.value, json!(1.0));
|
||||
assert!(xp.present && xp.is_default);
|
||||
let quest = v.settings.iter().find(|s| s.meta.key == "Rate.XP.Quest").unwrap();
|
||||
assert!(!quest.present, "missing key falls back to default");
|
||||
assert!(v.unknown_keys >= 3, "RealmID, WorldServerPort, Unknown.Custom are not curated");
|
||||
assert!(v.drift_keys.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_changes_only_that_key_in_template_and_generated_conf() {
|
||||
let (_d, root, meta) = fixture();
|
||||
let tpl_before = fs::read_to_string(root.join("Settings/worldserver.conf.template")).unwrap();
|
||||
let r = save(&root, &meta, Scope::Server, &set(&[("Rate.XP.Kill", json!(2.5))])).unwrap();
|
||||
assert_eq!(r.changed.len(), 1);
|
||||
assert_eq!(r.restart, Some(Restart::World));
|
||||
for f in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
|
||||
let t = fs::read_to_string(root.join(f)).unwrap();
|
||||
assert!(t.contains("Rate.XP.Kill = 2.5\r\n"), "{f}: {t:?}");
|
||||
assert!(t.contains("Unknown.Custom = \"keep me\"\r\n"));
|
||||
}
|
||||
let tpl_after = fs::read_to_string(root.join("Settings/worldserver.conf.template")).unwrap();
|
||||
assert_eq!(tpl_after.replace("= 2.5", "= 1"), tpl_before, "nothing but the one value changed");
|
||||
assert!(tpl_after.contains("@WORLD_PORT@"), "template placeholders survive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_input_writes_nothing() {
|
||||
let (_d, root, meta) = fixture();
|
||||
let before = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||
let e = save(&root, &meta, Scope::Server, &set(&[("Rate.XP.Kill", json!(3)), ("Rate.Drop.Money", json!(-4)), ("Nope.Key", json!(1))])).unwrap_err();
|
||||
match e {
|
||||
Error::Validation(f) => {
|
||||
assert_eq!(f.len(), 2);
|
||||
assert!(f.iter().any(|x| x.key == "Rate.Drop.Money"));
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(fs::read(root.join("Core/configs/worldserver.conf")).unwrap(), before);
|
||||
assert!(list_snapshots(&meta).is_empty(), "no snapshot for a rejected save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_key_is_appended_and_noop_saves_do_nothing() {
|
||||
let (_d, root, meta) = fixture();
|
||||
let r = save(&root, &meta, Scope::Server, &set(&[("Rate.XP.Quest", json!(2))])).unwrap();
|
||||
assert_eq!(r.changed.len(), 1);
|
||||
assert!(r.changed[0].from.is_none());
|
||||
let t = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||
assert!(t.ends_with("# Added by CoA Server Manager\r\nRate.XP.Quest = 2\r\n"), "{t:?}");
|
||||
let again = save(&root, &meta, Scope::Server, &set(&[("Rate.XP.Quest", json!(2))])).unwrap();
|
||||
assert!(again.changed.is_empty() && again.snapshot.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_restore_roundtrip_is_byte_exact_and_undoable() {
|
||||
let (_d, root, meta) = fixture();
|
||||
let conf = root.join("Core/configs/worldserver.conf");
|
||||
let original = fs::read(&conf).unwrap();
|
||||
save(&root, &meta, Scope::Server, &set(&[("PlayerLimit", json!(50))])).unwrap();
|
||||
assert_ne!(fs::read(&conf).unwrap(), original);
|
||||
let snap = list_snapshots(&meta).remove(0);
|
||||
restore_snapshot(&meta, &snap.id).unwrap();
|
||||
assert_eq!(fs::read(&conf).unwrap(), original);
|
||||
assert!(list_snapshots(&meta).len() >= 2, "restore took its own snapshot");
|
||||
assert!(restore_snapshot(&meta, "../evil").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drift_detects_manual_edits_to_the_generated_conf_only() {
|
||||
let (_d, root, _m) = fixture();
|
||||
let conf = root.join("Core/configs/worldserver.conf");
|
||||
let t = fs::read_to_string(&conf).unwrap().replace("PlayerLimit = 0", "PlayerLimit = 99");
|
||||
fs::write(&conf, t).unwrap();
|
||||
assert_eq!(drift(&root).unwrap(), ["PlayerLimit"]);
|
||||
let v = load(&root, Scope::Server).unwrap();
|
||||
assert!(v.settings.iter().find(|s| s.meta.key == "PlayerLimit").unwrap().drift);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bots_ordering_rule_and_preset_preview() {
|
||||
let (_d, root, meta) = fixture();
|
||||
fs::write(root.join("Core/configs/modules/mod_coa_playerbots.conf"), "[worldserver]\nCoaBots.WorldBrain.PlannerMinMs = 2000\nCoaBots.WorldBrain.PlannerMaxMs = 8000\nCoaBots.Combat.VerboseLog = 1\n").unwrap();
|
||||
let e = save(&root, &meta, Scope::Bots, &set(&[("CoaBots.WorldBrain.PlannerMinMs", json!(9000))])).unwrap_err();
|
||||
assert!(matches!(e, Error::Validation(_)));
|
||||
let p = preview_preset(&root, Scope::Bots, "balanced").unwrap();
|
||||
assert!(p.changes.iter().any(|c| c.key == "CoaBots.Combat.VerboseLog" && c.to == json!(false)));
|
||||
let d = preview_defaults(&root, Scope::Bots).unwrap();
|
||||
assert!(d.changes.iter().all(|c| !values_equal(&c.from, &c.to)));
|
||||
// applying a preview through save() works end to end
|
||||
let map: BTreeMap<_, _> = p.changes.iter().map(|c| (c.key.clone(), c.to.clone())).collect();
|
||||
save(&root, &meta, Scope::Bots, &map).unwrap();
|
||||
assert!(preview_preset(&root, Scope::Bots, "balanced").unwrap().changes.is_empty(), "idempotent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bots_scope_requires_the_module_config() {
|
||||
let (_d, root, _m) = fixture();
|
||||
fs::remove_file(root.join("Core/configs/modules/mod_coa_playerbots.conf")).unwrap();
|
||||
assert!(load(&root, Scope::Bots).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Line-preserving reader/writer for AzerothCore `.conf` files.
|
||||
//!
|
||||
//! Invariant: `parse(text).to_text() == text` for any valid UTF-8 input. Every line keeps its own line ending,
|
||||
//! comments/blank lines/unknown keys are never touched, and `set` rewrites only the value part of one line.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Kind {
|
||||
Other,
|
||||
Entry { key: String, prefix_len: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Line {
|
||||
/// Text without its line terminator.
|
||||
text: String,
|
||||
/// The terminator this line had ("\n", "\r\n" or "" for an unterminated last line).
|
||||
eol: String,
|
||||
kind: Kind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConfFile {
|
||||
lines: Vec<Line>,
|
||||
bom: bool,
|
||||
default_eol: &'static str,
|
||||
}
|
||||
|
||||
fn is_key_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')
|
||||
}
|
||||
|
||||
fn classify(text: &str) -> Kind {
|
||||
let t = text.trim_start();
|
||||
if t.is_empty() || t.starts_with('#') || t.starts_with(';') || t.starts_with('[') {
|
||||
return Kind::Other;
|
||||
}
|
||||
let Some(eq) = text.find('=') else { return Kind::Other };
|
||||
let key = text[..eq].trim();
|
||||
if key.is_empty() || !key.chars().all(is_key_char) {
|
||||
return Kind::Other;
|
||||
}
|
||||
// prefix = everything up to and including '=' and the spaces after it
|
||||
let after = &text[eq + 1..];
|
||||
let spaces = after.len() - after.trim_start_matches([' ', '\t']).len();
|
||||
Kind::Entry { key: key.to_string(), prefix_len: eq + 1 + spaces }
|
||||
}
|
||||
|
||||
impl ConfFile {
|
||||
pub fn parse(input: &str) -> ConfFile {
|
||||
let (bom, body) = match input.strip_prefix('\u{feff}') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, input),
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
let (mut crlf, mut lf) = (0usize, 0usize);
|
||||
let mut rest = body;
|
||||
while !rest.is_empty() {
|
||||
let (raw, eol, next) = match rest.find('\n') {
|
||||
Some(i) if i > 0 && rest.as_bytes()[i - 1] == b'\r' => (&rest[..i - 1], "\r\n", &rest[i + 1..]),
|
||||
Some(i) => (&rest[..i], "\n", &rest[i + 1..]),
|
||||
None => (rest, "", ""),
|
||||
};
|
||||
match eol {
|
||||
"\r\n" => crlf += 1,
|
||||
"\n" => lf += 1,
|
||||
_ => {}
|
||||
}
|
||||
lines.push(Line { text: raw.to_string(), eol: eol.to_string(), kind: classify(raw) });
|
||||
rest = next;
|
||||
}
|
||||
ConfFile { lines, bom, default_eol: if crlf > lf { "\r\n" } else { "\n" } }
|
||||
}
|
||||
|
||||
pub fn parse_bytes(bytes: &[u8]) -> Result<ConfFile> {
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| Error::Invalid("configuration file is not valid UTF-8".into()))?;
|
||||
Ok(Self::parse(text))
|
||||
}
|
||||
|
||||
pub fn to_text(&self) -> String {
|
||||
let mut out = String::new();
|
||||
if self.bom {
|
||||
out.push('\u{feff}');
|
||||
}
|
||||
for l in &self.lines {
|
||||
out.push_str(&l.text);
|
||||
out.push_str(&l.eol);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Active (uncommented) entries in file order.
|
||||
pub fn entries(&self) -> impl Iterator<Item = (&str, &str)> {
|
||||
self.lines.iter().filter_map(|l| match &l.kind {
|
||||
Kind::Entry { key, prefix_len } => Some((key.as_str(), l.text[*prefix_len..].trim_end())),
|
||||
Kind::Other => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw value (quotes included) of the last active occurrence of `key` (the one the server ends up using).
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
self.entries().filter(|(k, _)| *k == key).map(|(_, v)| v).last()
|
||||
}
|
||||
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
self.get(key).is_some()
|
||||
}
|
||||
|
||||
/// Set `raw` (already formatted, quotes included) as the value of `key`. Returns true if the key was appended.
|
||||
/// `doc` lines (without `#`) are written above a newly appended key.
|
||||
pub fn set(&mut self, key: &str, raw: &str, doc: &[&str]) -> bool {
|
||||
if let Some(l) = self.lines.iter_mut().rev().find(|l| matches!(&l.kind, Kind::Entry { key: k, .. } if k == key)) {
|
||||
if let Kind::Entry { prefix_len, .. } = l.kind {
|
||||
let prefix = l.text[..prefix_len].to_string();
|
||||
l.text = format!("{prefix}{raw}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
let eol = self.default_eol;
|
||||
// Make sure the previous line is terminated before appending.
|
||||
if let Some(last) = self.lines.last_mut() {
|
||||
if last.eol.is_empty() {
|
||||
last.eol = eol.to_string();
|
||||
}
|
||||
}
|
||||
for d in doc {
|
||||
self.lines.push(Line { text: format!("# {d}"), eol: eol.to_string(), kind: Kind::Other });
|
||||
}
|
||||
let text = format!("{key} = {raw}");
|
||||
self.lines.push(Line { kind: classify(&text), text, eol: eol.to_string() });
|
||||
true
|
||||
}
|
||||
|
||||
/// The comment block directly above the last active occurrence of `key` (without the leading `#`).
|
||||
pub fn doc_for(&self, key: &str) -> Vec<String> {
|
||||
let Some(idx) = self.lines.iter().rposition(|l| matches!(&l.kind, Kind::Entry { key: k, .. } if k == key)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut doc = Vec::new();
|
||||
for l in self.lines[..idx].iter().rev() {
|
||||
let t = l.text.trim();
|
||||
if !t.starts_with('#') || t.trim_start_matches('#').trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
doc.push(t.trim_start_matches('#').trim().to_string());
|
||||
}
|
||||
doc.reverse();
|
||||
doc
|
||||
}
|
||||
|
||||
pub fn append_comment_block(&mut self, doc: &[&str]) {
|
||||
let eol = self.default_eol;
|
||||
if let Some(last) = self.lines.last_mut() {
|
||||
if last.eol.is_empty() {
|
||||
last.eol = eol.to_string();
|
||||
}
|
||||
}
|
||||
for d in doc {
|
||||
self.lines.push(Line { text: d.to_string(), eol: eol.to_string(), kind: Kind::Other });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip one pair of surrounding double quotes.
|
||||
pub fn unquote(raw: &str) -> &str {
|
||||
let t = raw.trim();
|
||||
t.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SAMPLE: &str = "# header\r\n[worldserver]\r\n\r\n# doc for a\r\nA.Key = 5\r\nB.Key=\"text with # hash\"\r\n#Commented = 1\r\nC = 7\r\nA.Key = 6\r\nlast = 1";
|
||||
|
||||
#[test]
|
||||
fn roundtrip_is_byte_identical_including_odd_input() {
|
||||
for s in [SAMPLE, "", "\n", "no newline", "a=1\n\n\nb = 2\n", "\u{feff}k = v\r\n", "mixed=1\nendings=2\r\nhere=3\n", "=novalue\nweird key = 1\n"] {
|
||||
assert_eq!(ConfFile::parse(s).to_text(), s, "input: {s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_returns_last_active_value_and_ignores_comments() {
|
||||
let f = ConfFile::parse(SAMPLE);
|
||||
assert_eq!(f.get("A.Key"), Some("6"));
|
||||
assert_eq!(f.get("B.Key"), Some("\"text with # hash\""));
|
||||
assert_eq!(f.get("Commented"), None);
|
||||
assert_eq!(f.get("C"), Some("7"));
|
||||
assert_eq!(unquote(f.get("B.Key").unwrap()), "text with # hash");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_rewrites_only_the_value_and_keeps_spacing() {
|
||||
let mut f = ConfFile::parse(SAMPLE);
|
||||
assert!(!f.set("C", "9", &[]));
|
||||
assert!(!f.set("A.Key", "10", &[]));
|
||||
let out = f.to_text();
|
||||
assert!(out.contains("C = 9\r\n"), "{out:?}");
|
||||
// last duplicate changed, first untouched
|
||||
assert!(out.contains("A.Key = 5\r\n") && out.contains("A.Key = 10\r\n"));
|
||||
// everything else byte-identical
|
||||
assert_eq!(out.replace("C = 9", "C = 7").replace("A.Key = 10", "A.Key = 6"), SAMPLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_appends_missing_key_with_doc_using_file_eol() {
|
||||
let mut f = ConfFile::parse("[worldserver]\r\nA = 1");
|
||||
assert!(f.set("New.Key", "\"x\"", &["Added by CoA Server Manager"]));
|
||||
assert_eq!(f.to_text(), "[worldserver]\r\nA = 1\r\n# Added by CoA Server Manager\r\nNew.Key = \"x\"\r\n");
|
||||
assert_eq!(f.get("New.Key"), Some("\"x\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_is_refused_rather_than_mangled() {
|
||||
assert!(ConfFile::parse_bytes(&[0x41, 0xFF, 0xFE]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Setting schemas (`schemas/bots.json`, `schemas/server.json`) and value validation/formatting.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SettingType {
|
||||
Bool,
|
||||
Int,
|
||||
Float,
|
||||
String,
|
||||
Enum,
|
||||
}
|
||||
|
||||
/// How much has to be restarted for a change to take effect.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Restart {
|
||||
Runtime,
|
||||
World,
|
||||
Full,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EnumOption {
|
||||
pub value: Value,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Setting {
|
||||
pub key: String,
|
||||
#[serde(rename = "type")]
|
||||
pub ty: SettingType,
|
||||
pub category: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub default: Value,
|
||||
#[serde(default)]
|
||||
pub min: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub max: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub options: Vec<EnumOption>,
|
||||
#[serde(default)]
|
||||
pub unit: Option<String>,
|
||||
#[serde(default)]
|
||||
pub advanced: bool,
|
||||
pub restart_required: Restart,
|
||||
#[serde(default)]
|
||||
pub dangerous: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Category {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Schema {
|
||||
pub schema: u32,
|
||||
pub scope: String,
|
||||
pub categories: Vec<Category>,
|
||||
pub settings: Vec<Setting>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub values: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PresetFile {
|
||||
pub schema: u32,
|
||||
pub presets: Vec<Preset>,
|
||||
}
|
||||
|
||||
impl Schema {
|
||||
pub fn parse(json: &str) -> Result<Schema> {
|
||||
let s: Schema = serde_json::from_str(json)?;
|
||||
s.check()?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&Setting> {
|
||||
self.settings.iter().find(|s| s.key == key)
|
||||
}
|
||||
|
||||
/// Structural sanity of the schema itself (caught by tests, not at user runtime).
|
||||
fn check(&self) -> Result<()> {
|
||||
let bad = |m: String| Err(Error::Invalid(format!("schema {}: {m}", self.scope)));
|
||||
let cats: Vec<&str> = self.categories.iter().map(|c| c.id.as_str()).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for s in &self.settings {
|
||||
if !seen.insert(&s.key) {
|
||||
return bad(format!("duplicate key {}", s.key));
|
||||
}
|
||||
if !cats.contains(&s.category.as_str()) {
|
||||
return bad(format!("{}: unknown category {}", s.key, s.category));
|
||||
}
|
||||
if s.ty == SettingType::Enum && s.options.is_empty() {
|
||||
return bad(format!("{}: enum without options", s.key));
|
||||
}
|
||||
if let Err(e) = s.to_raw(&s.default) {
|
||||
return bad(format!("{}: default is invalid: {e}", s.key));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON equality that treats 1 and 1.0 as the same number.
|
||||
pub fn values_equal(a: &Value, b: &Value) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
fn num_fmt(f: f64) -> String {
|
||||
if f.fract() == 0.0 && f.abs() < 1e15 {
|
||||
format!("{}", f as i64)
|
||||
} else {
|
||||
let s = format!("{f}");
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
impl Setting {
|
||||
/// Validate `value` and format it the way it is written to the `.conf` (strings are quoted).
|
||||
pub fn to_raw(&self, value: &Value) -> std::result::Result<String, String> {
|
||||
let range = |n: f64| -> std::result::Result<(), String> {
|
||||
if let Some(min) = self.min {
|
||||
if n < min {
|
||||
return Err(format!("must be at least {}", num_fmt(min)));
|
||||
}
|
||||
}
|
||||
if let Some(max) = self.max {
|
||||
if n > max {
|
||||
return Err(format!("must be at most {}", num_fmt(max)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match self.ty {
|
||||
SettingType::Bool => match value {
|
||||
Value::Bool(b) => Ok(if *b { "1" } else { "0" }.into()),
|
||||
_ => Err("must be on or off".into()),
|
||||
},
|
||||
SettingType::Int => match value.as_i64() {
|
||||
Some(i) => range(i as f64).map(|_| i.to_string()),
|
||||
None => Err("must be a whole number".into()),
|
||||
},
|
||||
SettingType::Float => match value.as_f64() {
|
||||
Some(f) if f.is_finite() => range(f).map(|_| num_fmt(f)),
|
||||
_ => Err("must be a number".into()),
|
||||
},
|
||||
SettingType::String => match value.as_str() {
|
||||
Some(s) if s.contains(['"', '\n', '\r']) => Err("must not contain quotes or line breaks".into()),
|
||||
Some(s) => Ok(format!("\"{s}\"")),
|
||||
None => Err("must be text".into()),
|
||||
},
|
||||
SettingType::Enum => {
|
||||
let opt = self.options.iter().find(|o| o.value == *value).ok_or("is not one of the allowed choices")?;
|
||||
Ok(match &opt.value {
|
||||
Value::String(s) => format!("\"{s}\""),
|
||||
other => other.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a raw `.conf` value into JSON according to the setting's type.
|
||||
pub fn from_raw(&self, raw: &str) -> std::result::Result<Value, String> {
|
||||
let t = raw.trim();
|
||||
let unq = super::parser::unquote(t);
|
||||
match self.ty {
|
||||
SettingType::Bool => match unq.to_ascii_lowercase().as_str() {
|
||||
"1" | "true" | "yes" | "on" => Ok(Value::Bool(true)),
|
||||
"0" | "false" | "no" | "off" => Ok(Value::Bool(false)),
|
||||
_ => Err(format!("{t:?} is not on/off")),
|
||||
},
|
||||
SettingType::Int => unq.parse::<i64>().map(Value::from).map_err(|_| format!("{t:?} is not a whole number")),
|
||||
SettingType::Float => unq
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.and_then(serde_json::Number::from_f64)
|
||||
.map(Value::Number)
|
||||
.ok_or_else(|| format!("{t:?} is not a number")),
|
||||
SettingType::String => Ok(Value::String(unq.to_string())),
|
||||
SettingType::Enum => {
|
||||
for o in &self.options {
|
||||
let matches = match &o.value {
|
||||
Value::String(s) => s == unq,
|
||||
other => other.to_string() == unq,
|
||||
};
|
||||
if matches {
|
||||
return Ok(o.value.clone());
|
||||
}
|
||||
}
|
||||
Err(format!("{t:?} is not one of the known choices"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn s(ty: SettingType, min: Option<f64>, max: Option<f64>) -> Setting {
|
||||
Setting {
|
||||
key: "K".into(),
|
||||
ty,
|
||||
category: "c".into(),
|
||||
title: "t".into(),
|
||||
description: "d".into(),
|
||||
default: json!(1),
|
||||
min,
|
||||
max,
|
||||
options: vec![],
|
||||
unit: None,
|
||||
advanced: false,
|
||||
restart_required: Restart::World,
|
||||
dangerous: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int_range_and_type_validation() {
|
||||
let st = s(SettingType::Int, Some(0.0), Some(100.0));
|
||||
assert_eq!(st.to_raw(&json!(50)).unwrap(), "50");
|
||||
assert!(st.to_raw(&json!(101)).is_err());
|
||||
assert!(st.to_raw(&json!(-1)).is_err());
|
||||
assert!(st.to_raw(&json!(1.5)).is_err());
|
||||
assert!(st.to_raw(&json!("5")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_bool_string_formatting() {
|
||||
let f = s(SettingType::Float, Some(0.0), None);
|
||||
assert_eq!(f.to_raw(&json!(1.5)).unwrap(), "1.5");
|
||||
assert_eq!(f.to_raw(&json!(2.0)).unwrap(), "2");
|
||||
assert!(f.to_raw(&json!(-0.1)).is_err());
|
||||
assert_eq!(s(SettingType::Bool, None, None).to_raw(&json!(true)).unwrap(), "1");
|
||||
assert!(s(SettingType::Bool, None, None).to_raw(&json!(1)).is_err());
|
||||
let st = s(SettingType::String, None, None);
|
||||
assert_eq!(st.to_raw(&json!("a b")).unwrap(), "\"a b\"");
|
||||
assert!(st.to_raw(&json!("bad\"quote")).is_err());
|
||||
assert!(st.to_raw(&json!("multi\nline")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enum_and_decode() {
|
||||
let mut e = s(SettingType::Enum, None, None);
|
||||
e.options = vec![EnumOption { value: json!(0), label: "A".into() }, EnumOption { value: json!(2), label: "B".into() }];
|
||||
assert_eq!(e.to_raw(&json!(2)).unwrap(), "2");
|
||||
assert!(e.to_raw(&json!(1)).is_err());
|
||||
assert_eq!(e.from_raw("2").unwrap(), json!(2));
|
||||
assert!(e.from_raw("9").is_err());
|
||||
assert_eq!(s(SettingType::Bool, None, None).from_raw(" 1 ").unwrap(), json!(true));
|
||||
assert_eq!(s(SettingType::String, None, None).from_raw("\"x y\"").unwrap(), json!("x y"));
|
||||
assert_eq!(s(SettingType::Float, None, None).from_raw("1.5").unwrap(), json!(1.5));
|
||||
assert!(s(SettingType::Int, None, None).from_raw("abc").is_err());
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,15 @@ pub enum Error {
|
||||
UnknownInstallation(String),
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
#[error("invalid values: {}", .0.iter().map(|f| format!("{}: {}", f.key, f.message)).collect::<Vec<_>>().join("; "))]
|
||||
Validation(Vec<FieldError>),
|
||||
}
|
||||
|
||||
/// A problem with one setting, addressed by key so the UI can highlight the field.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct FieldError {
|
||||
pub key: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Stable identifiers the UI maps to human messages. Raw exit codes never reach the user.
|
||||
@@ -129,6 +138,7 @@ impl Error {
|
||||
Error::InsufficientSpace { .. } => ErrorCode::DiskFull,
|
||||
Error::HashMismatch { .. } => ErrorCode::HashMismatch,
|
||||
Error::PathRejected(_) => ErrorCode::PathRejected,
|
||||
Error::Validation(_) => ErrorCode::InvalidConfigValue,
|
||||
_ => ErrorCode::Unknown,
|
||||
}
|
||||
}
|
||||
@@ -139,10 +149,15 @@ impl Error {
|
||||
pub struct UiError {
|
||||
pub human: Human,
|
||||
pub technical: String,
|
||||
pub fields: Vec<FieldError>,
|
||||
}
|
||||
|
||||
impl From<Error> for UiError {
|
||||
fn from(e: Error) -> Self {
|
||||
UiError { human: e.code().human(), technical: e.to_string() }
|
||||
let fields = match &e {
|
||||
Error::Validation(f) => f.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
UiError { human: e.code().human(), technical: e.to_string(), fields }
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod config;
|
||||
pub mod driver;
|
||||
pub mod error;
|
||||
pub mod fsx;
|
||||
|
||||
Reference in new issue
Block a user