mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a7a2069c0 | ||
|
|
736333d23d |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Graceful server shutdowns no longer trigger crash recovery
|
||||
---
|
||||
Automatic crash recovery requires a confirmed abnormal exit. Normal shutdowns and scheduled restarts are not counted as crashes.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure the visual day and night cycle from Modules
|
||||
---
|
||||
Modules now offers TimeIsTime clock settings when supported by the installed server.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Select parallel or global scaling and remove item class requirements
|
||||
---
|
||||
The scaling settings now offer the parallel and global progression modes and a switch for class-restricted equipment, including tier sets.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Starting the server waits for update checks and identifies ongoing maintenance
|
||||
---
|
||||
Downloading an update manifest no longer blocks startup. A start waits up to 30 seconds for a check to finish; other active maintenance still blocks it safely and shows its operation, process and start time.
|
||||
@@ -100,7 +100,7 @@ pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
|
||||
let root = fsx::canonicalize_lenient(root)?;
|
||||
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
Some(crate::update::operation_lock_for(&crate::registry::metadata_dir_for(&root)?, "starting server", true)?)
|
||||
Some(crate::update::operation_lock(&crate::registry::metadata_dir_for(&root)?)?)
|
||||
} else { None };
|
||||
if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::update::ensure_recovered(&crate::registry::metadata_dir_for(&root)?)?;
|
||||
|
||||
@@ -341,6 +341,20 @@ fn save_settings_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, changes:
|
||||
for (key, value) in changes {
|
||||
let value = value.trim();
|
||||
if let Some(field) = fields.get(key) { crate::squid::validate(field, value)?; }
|
||||
if id == "time-is-time" {
|
||||
let bounds = match key.as_str() {
|
||||
"TimeIsTime.SpeedRate" => Some((0.01, 60.0)),
|
||||
"TimeIsTime.HourOffset" => Some((-24.0, 24.0)),
|
||||
"TimeIsTime.TimeStart" => Some((0.0, 2147483647.0)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((min, max)) = bounds {
|
||||
let number = value.parse::<f64>().map_err(|_| Error::Invalid(format!("{key} must be a number.")))?;
|
||||
if !number.is_finite() || number < min || number > max || (key == "TimeIsTime.TimeStart" && number.fract() != 0.0) {
|
||||
return Err(Error::Invalid(format!("{key} must be between {min} and {max}.")));
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.switchable && key == &e.enable_key {
|
||||
return Err(Error::Invalid("Use the module switch to turn this module on or off.".into()));
|
||||
}
|
||||
@@ -397,6 +411,24 @@ fn save_settings_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, changes:
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn time_settings_are_validated_before_writing() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path();
|
||||
fs::create_dir_all(dir(root)).unwrap();
|
||||
fs::write(dir(root).join("mod-time_is_time.conf.dist"), "TimeIsTime.Enable = 0\nTimeIsTime.SpeedRate = 1\nTimeIsTime.HourOffset = 0\nTimeIsTime.TimeStart = 0\n").unwrap();
|
||||
let cat = catalog();
|
||||
for (key, value) in [("TimeIsTime.SpeedRate", "NaN"), ("TimeIsTime.SpeedRate", "0"),
|
||||
("TimeIsTime.HourOffset", "25"), ("TimeIsTime.TimeStart", "1.5")] {
|
||||
assert!(save_settings_in(&cat, root, root, "time-is-time", &BTreeMap::from([
|
||||
(key.into(), value.into())
|
||||
])).is_err());
|
||||
}
|
||||
assert!(save_settings_in(&cat, root, root, "time-is-time", &BTreeMap::from([
|
||||
("TimeIsTime.SpeedRate".into(), "60".into())
|
||||
])).is_ok());
|
||||
}
|
||||
|
||||
fn test_catalog() -> Vec<Entry> {
|
||||
let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
|
||||
id: id.into(),
|
||||
|
||||
@@ -68,6 +68,24 @@ pub fn read_state_record(root: &Path, name: &str) -> Option<ProcessIdentity> {
|
||||
fsx::read_json(&root.join(".state").join(format!("{name}.json"))).ok()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ProcessExit {
|
||||
process: ProcessIdentity,
|
||||
exit_code: i64,
|
||||
}
|
||||
|
||||
fn exited_state(root: &Path, name: &str, expected: &[String]) -> ServiceState {
|
||||
let exit: Option<ProcessExit> = fsx::read_json(&root.join(".state").join(format!("{name}-exit.json"))).ok();
|
||||
let record = read_state_record(root, name);
|
||||
match (exit, record) {
|
||||
(Some(exit), Some(record))
|
||||
if exit.process.same_as(&record)
|
||||
&& expected.iter().any(|exe| record.exe.eq_ignore_ascii_case(exe))
|
||||
&& exit.exit_code != 0 && exit.exit_code != 2 => ServiceState::Crashed,
|
||||
_ => ServiceState::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod sys {
|
||||
use super::ProcessIdentity;
|
||||
@@ -304,7 +322,7 @@ fn service_with(root: &Path, name: &'static str, exe: PathBuf, alternatives: &[P
|
||||
(None, Some(o)) => {
|
||||
(ServiceState::Stopped, false, Some(PortConflict { port, pid: o, exe: identity(o).map(|i| i.exe) }))
|
||||
}
|
||||
(None, None) => (ServiceState::Stopped, false, None),
|
||||
(None, None) => (exited_state(root, name, &expected), false, None),
|
||||
};
|
||||
ServiceStatus {
|
||||
name,
|
||||
@@ -400,4 +418,25 @@ mod tests {
|
||||
assert_eq!(o.world.state, ServiceState::Stopped);
|
||||
assert!(o.world.pid.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_matching_abnormal_exits_are_crashes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = dir.path().join(".state");
|
||||
std::fs::create_dir_all(&state).unwrap();
|
||||
let record = ProcessIdentity { pid: 42, created: 123, exe: "C:\\server\\worldserver.exe".into() };
|
||||
let expected = vec![record.exe.clone()];
|
||||
std::fs::write(state.join("world.json"), serde_json::to_vec(&record).unwrap()).unwrap();
|
||||
for (code, want) in [(0i64, ServiceState::Stopped), (2, ServiceState::Stopped), (1, ServiceState::Crashed),
|
||||
(3221225477, ServiceState::Crashed)] {
|
||||
std::fs::write(state.join("world-exit.json"), serde_json::to_vec(&serde_json::json!({
|
||||
"process": record, "exit_code": code
|
||||
})).unwrap()).unwrap();
|
||||
assert_eq!(exited_state(dir.path(), "world", &expected), want);
|
||||
}
|
||||
let newer = ProcessIdentity { created: 124, ..record };
|
||||
std::fs::write(state.join("world.json"), serde_json::to_vec(&newer).unwrap()).unwrap();
|
||||
assert_eq!(exited_state(dir.path(), "world", &expected), ServiceState::Stopped);
|
||||
assert_eq!(exited_state(dir.path(), "world", &["C:\\other.exe".into()]), ServiceState::Stopped);
|
||||
}
|
||||
}
|
||||
@@ -308,12 +308,9 @@ pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &s
|
||||
pub fn preview_with(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &str, resolutions: &BTreeMap<String, Resolution>, access: DatabaseAccess) -> Result<Preview> {
|
||||
refuse_for_docker(root)?;
|
||||
let meta_dir = crate::registry::metadata_dir_for(root)?;
|
||||
let observed_version = MetaDir::open(&meta_dir)?.1.core.version;
|
||||
let (m, _) = fetch_manifest(source, trusted_key)?;
|
||||
let _lock = operation_lock_for(&meta_dir, "checking updates", false)?;
|
||||
let _lock = operation_lock(&meta_dir)?;
|
||||
ensure_recovered(&meta_dir)?;
|
||||
let (_, current_meta) = MetaDir::open(&meta_dir)?;
|
||||
let meta = if current_meta.core.version != observed_version { ¤t_meta } else { meta };
|
||||
let (m, _) = fetch_manifest(source, trusted_key)?;
|
||||
check_manifest(&m)?;
|
||||
reject_downgrade(meta, &m)?;
|
||||
let mut items = plan(root, meta, &m, resolutions, None)?;
|
||||
@@ -783,26 +780,11 @@ pub fn rollback(root: &Path, meta_dir: &Path, id: &str, env: &dyn Env) -> Result
|
||||
}
|
||||
|
||||
pub(crate) fn operation_lock(meta_dir: &Path) -> Result<fs::File> {
|
||||
operation_lock_for(meta_dir, "server maintenance", false)
|
||||
}
|
||||
|
||||
pub(crate) fn operation_lock_for(meta_dir: &Path, operation: &str, wait_for_check: bool) -> Result<fs::File> {
|
||||
fs::create_dir_all(meta_dir)?;
|
||||
let lock = fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(meta_dir.join("update.lock"))?;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
loop {
|
||||
if fs4::fs_std::FileExt::try_lock_exclusive(&lock)? { break; }
|
||||
let owner = fsx::read_json::<serde_json::Value>(&meta_dir.join("update-lock-owner.json")).ok();
|
||||
let checking = owner.as_ref().and_then(|owner| owner.get("operation")).and_then(|value| value.as_str()) == Some("checking updates");
|
||||
if wait_for_check && checking && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
continue;
|
||||
}
|
||||
let details = owner.as_ref().and_then(|owner| Some(format!(" Operation: {}; Manager process: {}; started: {}.", owner.get("operation")?.as_str()?, owner.get("pid")?.as_u64()?, owner.get("started")?.as_str()?))).unwrap_or_default();
|
||||
return Err(Error::Invalid(format!("Another update, repair or recovery is in progress.{details} Wait for that operation to finish, then retry.")));
|
||||
if !fs4::fs_std::FileExt::try_lock_exclusive(&lock)? {
|
||||
return Err(Error::Invalid("Another update, repair or recovery is in progress.".into()));
|
||||
}
|
||||
let record = serde_json::json!({"operation": operation, "pid": std::process::id(), "started": chrono::Utc::now().to_rfc3339()});
|
||||
fsx::atomic_write_json(&meta_dir.join("update-lock-owner.json"), &record)?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
@@ -1376,25 +1358,6 @@ mod tests {
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_waits_for_an_update_check_but_not_for_active_maintenance() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let checker = operation_lock_for(temp.path(), "checking updates", false).unwrap();
|
||||
let root = temp.path().to_path_buf();
|
||||
let release = std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
drop(checker);
|
||||
});
|
||||
let start = operation_lock_for(&root, "starting server", true).unwrap();
|
||||
release.join().unwrap();
|
||||
let error = operation_lock(&root).unwrap_err().to_string();
|
||||
assert!(error.contains("starting server"));
|
||||
assert!(error.contains(&std::process::id().to_string()));
|
||||
drop(start);
|
||||
// Stale owner metadata is harmless once the OS lock is released.
|
||||
operation_lock(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_manager_realm_launcher_is_replaced_during_update() {
|
||||
let w = legacy_launcher_world(false);
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"modules": [
|
||||
{
|
||||
"id": "time-is-time",
|
||||
"name": "TimeIsTime",
|
||||
"description": {
|
||||
"en": "Adjust the visual day and night cycle without changing server timers.",
|
||||
"ru": "Настройка визуального цикла дня и ночи без изменения серверных таймеров.",
|
||||
"de": "Passt den sichtbaren Tag-Nacht-Zyklus an, ohne Serverzeiten zu ändern.",
|
||||
"fr": "Ajuste le cycle visuel jour-nuit sans modifier les minuteries du serveur.",
|
||||
"es": "Ajusta el ciclo visual día-noche sin cambiar los temporizadores del servidor."
|
||||
},
|
||||
"repo": "https://github.com/dunjeon/mod-TimeIsTime",
|
||||
"conf": "mod-time_is_time.conf",
|
||||
"enable_key": "TimeIsTime.Enable",
|
||||
"switchable": true,
|
||||
"default_on": false,
|
||||
"status": "beta",
|
||||
"icon": "clock"
|
||||
},
|
||||
{
|
||||
"id": "companions",
|
||||
"name": "CoA Companions",
|
||||
|
||||
@@ -14,6 +14,10 @@ const text = (values: string[], locale: Locale) => values[locales.indexOf(locale
|
||||
type Entry = { key: string; type: string; title: string[]; description: string[]; min?: number; max?: number; advanced?: boolean; options?: { value: string; label: string[] }[] };
|
||||
export const moduleSettingDefinitions: Entry[] = [];
|
||||
const fields = moduleSettingDefinitions;
|
||||
add("TimeIsTime.Announce", "bool", ["Announce on login", "Сообщение при входе"], ["Show a module notice when a character logs in.", "Показывать сообщение о модуле при входе персонажа."]);
|
||||
add("TimeIsTime.SpeedRate", "float", ["Day/night speed", "Скорость смены дня и ночи"], ["1 follows real time; 60 gives one game day every 24 minutes. Changes only the client visual clock.", "1 — реальное время; 60 — игровые сутки за 24 минуты. Меняет только визуальное время клиента."], { min: 0.01, max: 60 });
|
||||
add("TimeIsTime.HourOffset", "float", ["Hour offset", "Смещение часов"], ["Offset applied to the visual client clock, in hours.", "Смещение визуальных часов клиента в часах."], { min: -24, max: 24 });
|
||||
add("TimeIsTime.TimeStart", "int", ["Starting time", "Начальное время"], ["Unix timestamp used at every login; 0 uses the server clock.", "Unix-время при каждом входе; 0 использует часы сервера."], { min: 0, max: 2147483647 });
|
||||
function add(key: string, type: string, title: string[], description: string[], extra: Partial<Entry> = {}) {
|
||||
fields.push({ key, type, title, description, ...extra });
|
||||
}
|
||||
@@ -69,8 +73,11 @@ add(scaling + "LFG.DefaultChallengeSize", "int", ["Challenge group size", "Ра
|
||||
add(scaling + "GroupScaling.LockOnEncounterStart", "bool", ["Lock scaling during combat", "Фиксировать скейлинг на время боя", "Skalierung im Kampf sperren", "Figer l’adaptation en combat", "Fijar ajuste durante combate", "战斗期间锁定缩放"], ["Joining or leaving during a boss fight does not change its scaling.", "Вход и выход игроков во время боя с боссом не меняют скейлинг.", "Beitreten oder Verlassen während eines Bosskampfs ändert die Skalierung nicht.", "Les arrivées et départs pendant un boss ne changent pas l’adaptation.", "Entrar o salir durante un jefe no cambia el ajuste.", "首领战期间玩家进出不会改变缩放。"], { advanced: true });
|
||||
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic boundaries follow the level cap and enabled expansions. Custom uses the levels below.", "Автоматические границы зависят от максимального уровня и включённых дополнений. Ручные используют уровни ниже.", "Automatisch folgt der Maximalstufe und Erweiterungen. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique suit le niveau maximal et les extensions. Manuel utilise les niveaux ci-dessous.", "Automático sigue el nivel máximo y las expansiones. Manual usa los niveles siguientes.", "自动边界按等级上限和启用的资料片计算,自定义使用以下等级。"], { advanced: true, options: [
|
||||
{ value: "Auto", label: ["Automatic", "Автоматически", "Automatisch", "Automatique", "Automático", "自动"] },
|
||||
{ value: "Parallel", label: ["Parallel: Classic 1–60, TBC/WotLK 45–60", "Параллельно: классика 1–60, БК/ЛК 45–60", "Parallel: Classic 1–60, TBC/WotLK 45–60", "Parallèle : Classic 1–60, TBC/WotLK 45–60", "Paralelo: Classic 1–60, TBC/WotLK 45–60", "并行:经典1–60,TBC/WotLK45–60"] },
|
||||
{ value: "Global", label: ["Global: all eras 1–60", "Всё содержимое 1–60", "Alle Erweiterungen 1–60", "Toutes les extensions 1–60", "Todas las expansiones 1–60", "全部资料片1–60"] },
|
||||
{ value: "Custom", label: ["Custom", "Вручную", "Benutzerdefiniert", "Manuel", "Manual", "自定义"] },
|
||||
] });
|
||||
add(scaling + "Items.RemoveClassRestrictions", "bool", ["Remove item class requirements", "Убрать классовые ограничения предметов"], ["Allow all classes to equip class-restricted items, including tier sets. Requires a world server restart.", "Разрешает всем классам надевать предметы с классовыми ограничениями, включая комплекты T10. Требуется перезапуск игрового сервера."]);
|
||||
for (const era of ["Classic", "Tbc"]) add(scaling + `Progression.${era}End`, "int", [`${era} last level`, `Последний уровень ${era}`, `${era}-Endstufe`, `Dernier niveau ${era}`, `Último nivel ${era}`, `${era} 最高等级`], ["Used in custom progression. 0 chooses automatically.", "Для ручной прогрессии. 0 — автоматически.", "Für benutzerdefinierten Fortschritt. 0 wählt automatisch.", "Pour la progression manuelle. 0 choisit automatiquement.", "Para progresión manual. 0 elige automáticamente.", "用于自定义进度,0为自动。"], { min: 0, max: 80, advanced: true });
|
||||
add(scaling + "Debug", "bool", ["Detailed scaling logs", "Подробные логи скейлинга", "Ausführliche Skalierungsprotokolle", "Journaux détaillés", "Registros detallados", "详细缩放日志"], ["Log scaling calculations for troubleshooting.", "Записывает расчёты скейлинга для диагностики.", "Protokolliert Berechnungen zur Fehleranalyse.", "Enregistre les calculs pour le diagnostic.", "Registra cálculos para diagnóstico.", "记录缩放计算以排查问题。"], { advanced: true });
|
||||
|
||||
@@ -203,6 +210,6 @@ export function canonicalModuleValue(key: string, value: string): string {
|
||||
const v = value.trim().replace(/^"|"$/g, "");
|
||||
if (key === scaling + "SoloAssist.Mode") return ({ "0": "None", "1": "Light", "2": "Full", none: "None", light: "Light", full: "Full" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
if (key === scaling + "LFG.DefaultMode") return ({ "0": "Matchmaking", "1": "BotFill", "2": "CurrentParty", matchmaking: "Matchmaking", botfill: "BotFill", currentparty: "CurrentParty" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
if (key === scaling + "Progression.Mode") return v.toLowerCase() === "auto" ? "Auto" : v.toLowerCase() === "custom" ? "Custom" : v;
|
||||
if (key === scaling + "Progression.Mode") return ({ auto: "Auto", custom: "Custom", parallel: "Parallel", global: "Global" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
return v;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
|
||||
import { Bot, Clock, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
|
||||
import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -21,6 +21,7 @@ function GithubMark(props: { className?: string }) {
|
||||
|
||||
/** Icon and colours of a module's square tile, by the name the catalog gives it. */
|
||||
const TILES: Record<string, { icon: ComponentType<LucideProps>; from: string; to: string }> = {
|
||||
clock: { icon: Clock, from: "from-amber-500", to: "to-indigo-700" },
|
||||
bot: { icon: Bot, from: "from-emerald-500", to: "to-teal-700" },
|
||||
scaling: { icon: Scaling, from: "from-violet-500", to: "to-indigo-700" },
|
||||
plug: { icon: Plug, from: "from-amber-500", to: "to-orange-700" },
|
||||
|
||||
@@ -196,6 +196,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
if (alive.current) setPop(null);
|
||||
if (
|
||||
wasWorldRunningRef.current &&
|
||||
s.observed.world.state === "crashed" &&
|
||||
!userStoppedRef.current &&
|
||||
actionRef.current === null
|
||||
) {
|
||||
|
||||
Reference in new issue
Block a user