Scheduled daily restart of the world (#202)

Settings/restart-schedule.json (Settings, Startup) holds a local time and a countdown.
The Rust world supervisor asks the world for 'server restart <seconds>' once that time has
passed (by at most 15 minutes, for a world that ran before it), and starts the world
again when it exits with RESTART_EXIT_CODE; the database and auth keep running. While it
is under way (.state/scheduled-restart) the status says so and the Manager does not take
the down world for a crash. Extra worlds follow their server's schedule. Repacks with the
Python supervisor do not run the schedule; the card says the server needs an update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Opus 5.5 committed 2026-11-15 20:26:14 +05:00
1 parent 20657df203
commit 260d10b729
17 files changed
+395 -19

No files matched your search

@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Restart the world every day at a chosen time
---
Settings, Startup, Scheduled restart: at that local time the world restarts with an in-game countdown and comes back by itself; the database keeps running. It works without the Manager open and needs a server with the new launcher.
+1
View File
@@ -14,6 +14,7 @@
pub mod ops;
pub mod relay;
pub mod render;
pub mod schedule;
pub mod services;
pub mod settings;
pub mod spawn;
+162
View File
@@ -0,0 +1,162 @@
//! Restarts on a schedule (#202): once a day at the owner's local time, the world supervisor asks the world to
//! restart with an in-game countdown, waits for it to exit with AzerothCore's restart code and starts it again.
//! The database and the auth server keep running.
use std::path::{Path, PathBuf};
use std::time::Duration;
use chrono::{Local, NaiveDateTime, NaiveTime, Timelike};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
const FILE: &str = "Settings/restart-schedule.json";
/// Present while a scheduled restart is under way, so a world that is briefly down is not taken for a crash.
const UNDER_WAY: &str = ".state/scheduled-restart";
/// The exit code of `server restart` (AzerothCore's `RESTART_EXIT_CODE`).
pub const RESTART_EXIT_CODE: i32 = 2;
/// A restart missed by more than this (the computer slept, the world started late) waits for the next day.
const LATE: Duration = Duration::from_secs(15 * 60);
/// A world that has not come back within this time no longer counts as restarting.
const UNDER_WAY_LIMIT: Duration = Duration::from_secs(45 * 60);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RestartSchedule {
pub enabled: bool,
/// Local time, `HH:MM`.
pub time: String,
/// The in-game countdown before the restart, in minutes (1-60).
pub warning_minutes: u32,
}
impl Default for RestartSchedule {
fn default() -> Self {
Self {
enabled: false,
time: "05:00".into(),
warning_minutes: 5,
}
}
}
impl RestartSchedule {
fn at(&self) -> Option<NaiveTime> {
NaiveTime::parse_from_str(self.time.trim(), "%H:%M").ok()
}
fn validate(&self) -> Result<()> {
if self.at().is_none() {
return Err(Error::Invalid("The restart time must be HH:MM, for example 05:00.".into()));
}
if !(1..=60).contains(&self.warning_minutes) {
return Err(Error::Invalid("The restart warning must be 1 to 60 minutes.".into()));
}
Ok(())
}
/// The scheduled moment of `now`'s day, when a restart is due at `now` for a world started at `started`:
/// the moment has passed by less than [`LATE`] and the world was already running before it.
pub fn due(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
if !self.enabled {
return None;
}
let moment = now.date().and_time(self.at()?);
let late = now.signed_duration_since(moment).to_std().ok()?;
(late <= LATE && started < moment).then_some(moment)
}
}
/// The folder whose schedule a world follows: an extra world (`<server>/.realms/<name>`) follows its server's.
fn owner(root: &Path) -> PathBuf {
if crate::launcher::settings::is_extra_world(root) {
if let Some(main) = root.parent().and_then(Path::parent) {
return main.to_path_buf();
}
}
root.to_path_buf()
}
pub fn load(root: &Path) -> RestartSchedule {
crate::fsx::read_json(&owner(root).join(FILE)).unwrap_or_default()
}
pub fn save(root: &Path, schedule: &RestartSchedule) -> Result<RestartSchedule> {
let mut schedule = schedule.clone();
schedule.time = schedule.time.trim().to_string();
if schedule.enabled {
schedule.validate()?;
} else if schedule.at().is_none() {
schedule.time = RestartSchedule::default().time;
}
crate::fsx::atomic_write_json(&owner(root).join(FILE), &schedule)?;
Ok(schedule)
}
pub fn now() -> NaiveDateTime {
Local::now().naive_local().with_nanosecond(0).unwrap_or_else(|| Local::now().naive_local())
}
pub fn mark_under_way(root: &Path) -> Result<()> {
let path = root.join(UNDER_WAY);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, b"")?;
Ok(())
}
pub fn clear_under_way(root: &Path) {
let _ = std::fs::remove_file(root.join(UNDER_WAY));
}
/// A scheduled restart of this world is under way (its world may be down for a few minutes).
pub fn under_way(root: &Path) -> bool {
std::fs::metadata(root.join(UNDER_WAY))
.and_then(|m| m.modified())
.is_ok_and(|t| t.elapsed().is_ok_and(|age| age < UNDER_WAY_LIMIT))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> NaiveDateTime {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
#[test]
fn a_restart_is_due_once_after_its_time_for_a_world_that_ran_before_it() {
let s = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5 };
let started = at("2026-11-14 20:00");
assert_eq!(s.due(at("2026-11-15 04:59"), started), None);
assert_eq!(s.due(at("2026-11-15 05:00"), started), Some(at("2026-11-15 05:00")));
assert_eq!(s.due(at("2026-11-15 05:14"), started), Some(at("2026-11-15 05:00")));
assert_eq!(s.due(at("2026-11-15 05:16"), started), None, "missed by too much");
// The world that came back at 05:06 is not restarted again that day.
assert_eq!(s.due(at("2026-11-15 05:10"), at("2026-11-15 05:06")), None);
assert_eq!(s.due(at("2026-11-16 05:01"), at("2026-11-15 05:06")), Some(at("2026-11-16 05:00")));
let off = RestartSchedule { enabled: false, ..s };
assert_eq!(off.due(at("2026-11-15 05:00"), started), None);
}
#[test]
fn schedules_are_validated_and_extra_worlds_follow_their_server() {
let d = tempfile::tempdir().unwrap();
assert_eq!(load(d.path()), RestartSchedule::default());
let bad = RestartSchedule { enabled: true, time: "25:00".into(), warning_minutes: 5 };
assert!(save(d.path(), &bad).is_err());
let quiet = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 0 };
assert!(save(d.path(), &quiet).is_err());
let good = RestartSchedule { enabled: true, time: " 04:30 ".into(), warning_minutes: 10 };
assert_eq!(save(d.path(), &good).unwrap().time, "04:30");
let extra = d.path().join(".realms/secondary");
std::fs::create_dir_all(&extra).unwrap();
assert!(load(&extra).enabled);
assert!(!under_way(d.path()));
mark_under_way(d.path()).unwrap();
assert!(under_way(d.path()));
clear_under_way(d.path());
assert!(!under_way(d.path()));
}
}
+60 -14
View File
@@ -13,7 +13,7 @@ use std::time::{Duration, Instant};
use crate::error::{Error, ErrorCode, Result};
use crate::launcher::services::{self, ensure_free, mysql, spawn, start_mysql, wait_ready, Progress};
use crate::launcher::spawn::Proc;
use crate::launcher::{settings::Settings, squid, state};
use crate::launcher::{schedule, settings::Settings, squid, state};
fn stop_relay_flag(root: &Path) -> std::path::PathBuf {
state::dir(root).join("stop-relay")
@@ -169,24 +169,70 @@ fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result<Proc> {
}
/// The supervisor (`watch-world`): run the world, keep the relay alive while it runs, stop the relay after it.
/// `launcher` is the launcher executable that runs the relay (`None`: the Python relay).
pub fn watch_world(root: &Path, launcher: Option<&Path>, log: Progress) -> Result<()> {
/// `launcher` is the launcher executable that runs the relay (`None`: the Python relay). At the owner's scheduled
/// time it asks the world to restart with an in-game countdown and starts it again when it exits for that.
pub fn watch_world(root: &Path, launcher: Option<&Path>, offset: i32, log: Progress) -> Result<()> {
squid::validate_bots(root)?;
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
let mut relay: Option<Proc> = None;
while world.try_wait().is_none() {
let dead = relay.as_ref().is_none_or(|r| r.try_wait().is_some());
if dead {
match spawn_relay(root, launcher) {
Ok(r) => relay = Some(r),
Err(e) => {
log(&format!("Report relay could not start ({e}); retrying."));
std::thread::sleep(Duration::from_secs(5));
continue;
loop {
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
let started = schedule::now();
let mut requested = false;
let mut last_check: Option<Instant> = None;
let code = loop {
if let Some(code) = world.try_wait() {
break code;
}
let dead = relay.as_ref().is_none_or(|r| r.try_wait().is_some());
if dead {
match spawn_relay(root, launcher) {
Ok(r) => relay = Some(r),
Err(e) => {
log(&format!("Report relay could not start ({e}); retrying."));
std::thread::sleep(Duration::from_secs(5));
continue;
}
}
}
if last_check.is_none_or(|t| t.elapsed() >= Duration::from_secs(30)) {
last_check = Some(Instant::now());
if schedule::under_way(root) && !requested {
// The world that a scheduled restart started again is back once it accepts connections.
if Settings::load(root, offset).is_ok_and(|cfg| services::ready(root, "world", cfg.world_port)) {
schedule::clear_under_way(root);
}
}
if !requested {
let plan = schedule::load(root);
if plan.due(schedule::now(), started).is_some() {
let seconds = plan.warning_minutes * 60;
let asked = Settings::load(root, offset).and_then(|cfg| {
crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
.and_then(|mut ra| ra.run(&format!("server restart {seconds}")))
});
match asked {
Ok(_) => {
schedule::mark_under_way(root)?;
requested = true;
log(&format!("Scheduled restart: the world restarts in {} minutes.", plan.warning_minutes));
}
Err(e) => log(&format!("Scheduled restart could not be requested ({e}); retrying.")),
}
}
}
}
std::thread::sleep(Duration::from_secs(2));
};
if requested && code == schedule::RESTART_EXIT_CODE as u32 {
log("Scheduled restart: starting the world again.");
if let Err(e) = squid::validate_bots(root) {
schedule::clear_under_way(root);
return Err(e);
}
continue;
}
std::thread::sleep(Duration::from_secs(2));
schedule::clear_under_way(root);
break;
}
std::fs::write(stop_relay_flag(root), b"")?;
if let Some(r) = relay {
+1 -1
View File
@@ -100,7 +100,7 @@ fn run(args: Args) -> Result<(), String> {
match args.action.as_str() {
"watch-world" => {
let me = std::env::current_exe().map_err(|x| x.to_string())?;
return world::watch_world(root, Some(&me), &|m| say(m)).map_err(e);
return world::watch_world(root, Some(&me), args.offset, &|m| say(m)).map_err(e);
}
"relay-worker" => return coa_core::launcher::relay::worker(root).map_err(e),
"debug-logs-status" => {
+50 -2
View File
@@ -350,6 +350,8 @@ struct StatusView {
observed: Observed,
busy: bool,
path_exists: bool,
/// A scheduled restart is under way: a world that is down for a few minutes did not crash.
scheduled_restart: bool,
}
/// Where the Manager keeps its own state (server list, logs). `%LOCALAPPDATA%` on Windows, the XDG data folder elsewhere.
@@ -548,9 +550,12 @@ async fn server_status(
let root = path_of(&state, &id)?;
let busy = state.busy.lock().map(|b| b.contains(&id)).unwrap_or(false);
let path_exists = root.is_dir();
let observed = tauri::async_runtime::spawn_blocking(move || {
let (observed, scheduled_restart) = tauri::async_runtime::spawn_blocking(move || {
let ports = layout::read_ports(&root);
process::observe(&root, &ports)
(
process::observe(&root, &ports),
coa_core::launcher::schedule::under_way(&root),
)
})
.await
.map_err(|e| Error::Invalid(e.to_string()))?;
@@ -558,6 +563,7 @@ async fn server_status(
observed,
busy,
path_exists,
scheduled_restart,
})
}
@@ -1238,6 +1244,46 @@ async fn realm_select(
result
}
#[derive(serde::Serialize)]
struct RestartScheduleView {
schedule: coa_core::launcher::schedule::RestartSchedule,
/// The server ships the Rust world supervisor that carries out the schedule.
supported: bool,
}
#[tauri::command]
async fn restart_schedule(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<RestartScheduleView, UiError> {
let root = path_of(&state, &id)?;
blocking(move || {
Ok(RestartScheduleView {
schedule: coa_core::launcher::schedule::load(&root),
supported: root.join("Scripts/coa-launcher.exe").is_file(),
})
})
.await
}
/// Restart the world every day at the owner's local time; the running supervisor reads it within a minute.
#[tauri::command]
async fn restart_schedule_save(
state: State<'_, AppState>,
id: String,
schedule: coa_core::launcher::schedule::RestartSchedule,
) -> std::result::Result<RestartScheduleView, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
Ok(RestartScheduleView {
schedule: coa_core::launcher::schedule::save(&root, &schedule)?,
supported: root.join("Scripts/coa-launcher.exe").is_file(),
})
})
.await
}
#[tauri::command]
async fn mysql_custom(
state: State<'_, AppState>,
@@ -3034,6 +3080,8 @@ pub fn run() {
realm_rename,
mysql_custom,
mysql_custom_save,
restart_schedule,
restart_schedule_save,
check_database,
repair_server,
module_set_enabled,
+1
View File
@@ -39,6 +39,7 @@ export {};
if(cmd==="pending_update") return null;
if(cmd==="plugin:app|version") return "0.8.2";
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
if(cmd==="restart_schedule"||cmd==="restart_schedule_save"){const w=window as any;w.__sched=w.__sched??{enabled:false,time:"05:00",warningMinutes:5};if(cmd==="restart_schedule_save"){const s=args.schedule;if(s.enabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.time))throw new Error("The restart time must be HH:MM, for example 05:00.");w.__sched={...s};}return {schedule:w.__sched,supported:true};}
if(cmd==="mysql_custom"||cmd==="mysql_custom_save"){const w=window as any;if(cmd==="mysql_custom_save")w.__my=args.text;const text:string=w.__my??"";const applied=text.split("\n").map((l:string)=>l.trim()).filter((l:string)=>l&&!l.startsWith("#")&&!/^(port|datadir|basedir|bind[-_]address)\b/i.test(l)).map((l:string)=>l+"\n").join("");return {text,applied};}
if(cmd==="realm_names"||cmd==="realm_rename"){const w=window as any;w.__rn=w.__rn??{};const defs:[number,string][]=[[1,"Conquest of Azeroth"],[2,"Wildcard"]];if(cmd==="realm_rename"){await new Promise(r=>setTimeout(r,300));const n=(args.name??"").trim();if(n.length>32||n.includes('"'))throw new Error("The realm name can have at most 32 characters.");if(n)w.__rn[args.realmId]=n;else delete w.__rn[args.realmId];}return defs.map(([id,d])=>({id,name:w.__rn[id]??d,defaultName:d,custom:id in w.__rn}));}
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
+8
View File
@@ -778,6 +778,14 @@ const de: Partial<Record<keyof typeof en, string>> = {
"mysql.save": "Speichern",
"mysql.saved": "Gespeichert; Server neu starten, um sie anzuwenden.",
"mysql.applied": "Angewandte Optionen: {count}",
"sched.title": "Geplanter Neustart",
"sched.enable": "Die Welt jeden Tag neu starten",
"sched.time": "Uhrzeit",
"sched.warning": "Vorwarnung (Minuten)",
"sched.hint": "Die Welt startet zu dieser Uhrzeit dieses Computers neu, mit einem Countdown im Spielchat; die Datenbank läuft weiter, Spieler melden sich danach wieder an. Ein laufender Server übernimmt die neue Zeit innerhalb einer Minute.",
"sched.save": "Speichern",
"sched.saved": "Gespeichert.",
"sched.unsupported": "Dieser Server kann das noch nicht: Aktualisiere ihn auf einen Build mit dem neuen Launcher.",
"realm.namesTitle": "Realmnamen",
"realm.namesHint": "So heißt der Realm in der Realmliste der Spieler. Ein laufender Server zeigt den Namen sofort, und er bleibt nach Updates erhalten.",
"realm.nameSave": "Speichern",
+8
View File
@@ -62,6 +62,14 @@ const en = {
"mysql.save": "Save",
"mysql.saved": "Saved; restart the server to apply.",
"mysql.applied": "Options applied: {count}",
"sched.title": "Scheduled restart",
"sched.enable": "Restart the world every day",
"sched.time": "Time",
"sched.warning": "Warning (minutes)",
"sched.hint": "The world restarts at this time of this computer with a countdown in the game chat; the database keeps running and players log in again after it. A minute after saving, the running server follows the new time.",
"sched.save": "Save",
"sched.saved": "Saved.",
"sched.unsupported": "This server cannot do it yet: update the server to a build with the new launcher.",
"realm.namesTitle": "Realm names",
"realm.namesHint": "The name players see in the realm list. A running server shows it at once, and it stays after updates.",
"realm.nameSave": "Save",
+8
View File
@@ -778,6 +778,14 @@ const es: Partial<Record<keyof typeof en, string>> = {
"mysql.save": "Guardar",
"mysql.saved": "Guardado; reinicia el servidor para aplicarlo.",
"mysql.applied": "Opciones aplicadas: {count}",
"sched.title": "Reinicio programado",
"sched.enable": "Reiniciar el mundo cada día",
"sched.time": "Hora",
"sched.warning": "Aviso (minutos)",
"sched.hint": "El mundo se reinicia a esta hora de este ordenador con una cuenta atrás en el chat del juego; la base de datos sigue en marcha y los jugadores vuelven a entrar después. Un servidor en marcha sigue la nueva hora en menos de un minuto.",
"sched.save": "Guardar",
"sched.saved": "Guardado.",
"sched.unsupported": "Este servidor aún no puede hacerlo: actualízalo a una versión con el nuevo lanzador.",
"realm.namesTitle": "Nombres de los reinos",
"realm.namesHint": "El nombre que ven los jugadores en la lista de reinos. Un servidor en marcha lo muestra al instante y se mantiene tras las actualizaciones.",
"realm.nameSave": "Guardar",
+8
View File
@@ -778,6 +778,14 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"mysql.save": "Enregistrer",
"mysql.saved": "Enregistré ; redémarrez le serveur pour appliquer.",
"mysql.applied": "Options appliquées : {count}",
"sched.title": "Redémarrage planifié",
"sched.enable": "Redémarrer le monde chaque jour",
"sched.time": "Heure",
"sched.warning": "Avertissement (minutes)",
"sched.hint": "Le monde redémarre à cette heure de cet ordinateur avec un compte à rebours dans le chat du jeu ; la base de données continue de tourner et les joueurs se reconnectent ensuite. Un serveur en marche suit la nouvelle heure en moins d'une minute.",
"sched.save": "Enregistrer",
"sched.saved": "Enregistré.",
"sched.unsupported": "Ce serveur ne le permet pas encore : mettez-le à jour vers une version avec le nouveau lanceur.",
"realm.namesTitle": "Noms des royaumes",
"realm.namesHint": "Le nom que les joueurs voient dans la liste des royaumes. Un serveur en marche l'affiche aussitôt, et il reste après les mises à jour.",
"realm.nameSave": "Enregistrer",
+8
View File
@@ -65,6 +65,14 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"mysql.save": "Сохранить",
"mysql.saved": "Сохранено; перезапустите сервер, чтобы применить.",
"mysql.applied": "Применяется параметров: {count}",
"sched.title": "Перезапуск по расписанию",
"sched.enable": "Перезапускать мир каждый день",
"sched.time": "Время",
"sched.warning": "Предупреждение (минуты)",
"sched.hint": "Мир перезапускается в это время этого компьютера, с обратным отсчётом в игровом чате; база данных продолжает работать, игроки заходят снова после перезапуска. Работающий сервер подхватывает новое время в течение минуты.",
"sched.save": "Сохранить",
"sched.saved": "Сохранено.",
"sched.unsupported": "Этот сервер пока так не умеет: обновите его до сборки с новым лаунчером.",
"realm.namesTitle": "Названия реалмов",
"realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.",
"realm.nameSave": "Сохранить",
+8
View File
@@ -63,6 +63,14 @@ const zh = {
"mysql.save": "保存",
"mysql.saved": "已保存;重启服务器后生效。",
"mysql.applied": "生效的选项:{count}",
"sched.title": "定时重启",
"sched.enable": "每天重启世界",
"sched.time": "时间",
"sched.warning": "提前警告(分钟)",
"sched.hint": "世界会在本机的这个时间重启,并在游戏聊天中倒计时;数据库保持运行,玩家在重启后重新登录。正在运行的服务器会在一分钟内采用新时间。",
"sched.save": "保存",
"sched.saved": "已保存。",
"sched.unsupported": "此服务器暂不支持:请将服务器更新到带有新启动器的版本。",
"realm.namesTitle": "服务器名称",
"realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。",
"realm.nameSave": "保存",
+5
View File
@@ -54,9 +54,12 @@ export interface StatusView {
observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null };
busy: boolean;
path_exists: boolean;
scheduled_restart?: boolean;
}
export type RealmMode = "coa" | "wildcard" | "reborn";
export interface RestartSchedule { enabled: boolean; time: string; warningMinutes: number }
export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean }
export interface CustomMysql { text: string; applied: string }
export interface RealmName { id: number; name: string; defaultName: string; custom: boolean }
export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean; with_reborn: boolean; reborn_world_port: number | null; reborn_running: boolean }
@@ -488,6 +491,8 @@ export const api = {
realmProfiles: (id: string) => invoke<RealmProfiles>("realm_profiles", { id }),
realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke<RealmProfiles>("realm_select", { id, mode, restart }),
realmSimultaneous: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_simultaneous", { id, enabled }),
restartSchedule: (id: string) => invoke<RestartScheduleView>("restart_schedule", { id }),
restartScheduleSave: (id: string, schedule: RestartSchedule) => invoke<RestartScheduleView>("restart_schedule_save", { id, schedule }),
mysqlCustom: (id: string) => invoke<CustomMysql>("mysql_custom", { id }),
mysqlCustomSave: (id: string, text: string) => invoke<CustomMysql>("mysql_custom_save", { id, text }),
realmNames: (id: string) => invoke<RealmName[]>("realm_names", { id }),
+1 -1
View File
@@ -228,7 +228,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
} else {
if (alive.current) setPop(null);
if (
lifecycle.observe(false, actionRef.current !== null, serverUpdateBlocksRestart(server.id))
lifecycle.observe(false, actionRef.current !== null || s.scheduled_restart === true, serverUpdateBlocksRestart(server.id))
) {
setHasCrashHistory(true);
const now = Date.now();
+57
View File
@@ -0,0 +1,57 @@
import { useEffect, useState } from "react";
import { api, asUiError, type RestartSchedule } from "@/lib/api";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";
/** A daily world restart at a chosen local time, with an in-game countdown (#202). */
export function RestartScheduleSettings({ serverId }: { serverId: string }) {
const t = useT();
const [saved, setSaved] = useState<RestartSchedule | null>(null);
const [draft, setDraft] = useState<RestartSchedule>({ enabled: false, time: "05:00", warningMinutes: 5 });
const [supported, setSupported] = useState(true);
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
void api.restartSchedule(serverId).then(v => { if (alive) { setSaved(v.schedule); setDraft(v.schedule); setSupported(v.supported); } }).catch(e => { if (alive) setError(asUiError(e).technical); });
return () => { alive = false; };
}, [serverId]);
async function save() {
setBusy(true); setError(null); setDone(false);
try { const v = await api.restartScheduleSave(serverId, draft); setSaved(v.schedule); setDraft(v.schedule); setSupported(v.supported); setDone(true); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
const changed = !!saved && JSON.stringify(saved) !== JSON.stringify(draft);
const minutesOk = Number.isInteger(draft.warningMinutes) && draft.warningMinutes >= 1 && draft.warningMinutes <= 60;
const input = "rounded border border-line bg-bg px-2 py-1 text-sm text-ink outline-none focus:border-gold";
return <Card className="mt-6 p-6" aria-busy={busy}>
<h2 className="font-semibold">{t("sched.title")}</h2>
<label className="mt-3 flex cursor-pointer items-center gap-3">
<input type="checkbox" className="h-4 w-4 accent-[#c9a24a]" checked={draft.enabled} disabled={busy || !saved} onChange={e => { setDraft(d => ({ ...d, enabled: e.target.checked })); setDone(false); }} />
<span className="text-sm font-medium">{t("sched.enable")}</span>
</label>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm">
<label className="flex items-center gap-2">
<span>{t("sched.time")}</span>
<input type="time" className={input} value={draft.time} disabled={busy || !draft.enabled} onChange={e => { setDraft(d => ({ ...d, time: e.target.value })); setDone(false); }} />
</label>
<label className="flex items-center gap-2">
<span>{t("sched.warning")}</span>
<input type="number" min={1} max={60} step={1} className={`${input} w-20`} value={draft.warningMinutes} disabled={busy || !draft.enabled} onChange={e => { setDraft(d => ({ ...d, warningMinutes: Number(e.target.value) })); setDone(false); }} />
</label>
</div>
<p className="mt-2 text-sm text-muted">{t("sched.hint")}</p>
{!supported && <p className="mt-2 text-sm text-warn">{t("sched.unsupported")}</p>}
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy || !changed || (draft.enabled && !minutesOk)} onClick={() => void save()}>{t("sched.save")}</Button>
{done && <span className="text-xs text-muted">{t("sched.saved")}</span>}
</div>
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>;
}
+2 -1
View File
@@ -14,6 +14,7 @@ import { GameDataCard } from "./GameDataCard";
import { RealmStartupSettings } from "./RealmStartupSettings";
import { RealmNameSettings } from "./RealmNameSettings";
import { MySqlSettings } from "./MySqlSettings";
import { RestartScheduleSettings } from "./RestartScheduleSettings";
import { AutoRestartSettings } from "./AutoRestartSettings";
import { DiagnosticsCard } from "./DiagnosticsCard";
import { RepairCard } from "./RepairCard";
@@ -52,7 +53,7 @@ export function SettingsHome({ serverId, path, onForget }: { serverId: string; s
<button onClick={() => setSection("client")} className="mt-5 flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border border-line px-5 py-4 text-left text-sm hover:bg-white/5"><span>{t("settings.clientLink")}</span><span aria-hidden>→</span></button>
<ReleaseHistory selection={history} onSelect={setHistory} />
</div>
<div hidden={section !== "startup"} className="max-w-3xl"><RealmNameSettings serverId={serverId} /><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /></div>
<div hidden={section !== "startup"} className="max-w-3xl"><RealmNameSettings serverId={serverId} /><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /><RestartScheduleSettings serverId={serverId} /></div>
<div hidden={section !== "client"} className="max-w-3xl"><ClientCard serverId={serverId} /><GameDataCard serverId={serverId} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><ServerLoggingSettings serverId={serverId} /><MySqlSettings serverId={serverId} /><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "interface"} className="max-w-3xl"><Card className="mt-6 p-6"><h2 className="font-semibold">{t("settings.language")}</h2><p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p><LanguagePicker className="mt-4" /></Card><WindowSettings /><PublicServerSettings /></div>