From b3f43a8007b78694c349a5173d3ad42921e33d9d Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 23 Nov 2026 12:17:00 -0600 Subject: [PATCH 01/10] Refactor server operation locking and update handling - Replaced `try_lock_server` with a FIFO-fair `lock_server` method to queue operations on servers, preventing concurrent modifications during backups, updates, or restarts. - Introduced `asa_cache_lock` to manage access to the shared server cache, ensuring safe concurrent reads and writes. - Enhanced update handling in the UI to provide clearer notifications about auto-update plans and their statuses. - Implemented retry logic for failed auto-updates to avoid repeated failures flooding notifications. - Improved error handling during server updates to ensure the UI accurately reflects server statuses. --- src-tauri/src/commands/backup_manager.rs | 45 ++- src-tauri/src/commands/countdown.rs | 106 +++---- src-tauri/src/commands/scheduler.rs | 325 ++++++++++++--------- src-tauri/src/commands/server.rs | 7 +- src-tauri/src/commands/steamcmd.rs | 28 +- src-tauri/src/state/mod.rs | 70 +++-- src-tauri/src/state/scheduler.rs | 9 + src/app/page.tsx | 3 +- src/app/settings/page.tsx | 4 + src/components/layout/SchedulerManager.tsx | 56 +++- src/components/server/ServerCard.tsx | 8 +- src/components/server/tabs/OverviewTab.tsx | 8 +- src/lib/scheduler-sync.ts | 57 ++-- src/lib/update-utils.ts | 49 +++- 14 files changed, 509 insertions(+), 266 deletions(-) diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 768f4c8..bcfc22c 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -480,19 +480,42 @@ pub async fn execute_tick(app: &AppHandle) { let servers = db::get_servers(&conn); let pool = app.state::(); - for server in &servers { - if !running_ids.contains(&server.id) { - continue; - } + // (server, deferred) — a server busy with a restart/update/stop when its + // turn comes is pushed to the back of the queue instead of being skipped + // until next hour, so every other server's backup goes ahead first and + // the busy one is backed up as soon as that operation finishes. + let mut queue: std::collections::VecDeque<(&db::ServerRow, bool)> = servers.iter() + .filter(|s| running_ids.contains(&s.id)) + .map(|s| (s, false)) + .collect(); - // Skip a server currently undergoing a scheduled restart/update — - // reading its files while they're mid-overwrite could produce a - // silently incomplete archive. Picked up again on the next hourly - // tick. Held for the rest of this iteration. + while let Some((server, deferred)) = queue.pop_front() { + // Reading a server's files while a restart/update is overwriting them + // could produce a silently incomplete archive, so the lock is held + // for the rest of this iteration. let app_state = app.state::(); - let Some(_lock) = app_state.try_lock_server(&server.id) else { - eprintln!("[backup_manager] Skipping backup for {} — restart/update in progress", server.id); - continue; + let _lock = if deferred { + let guard = app_state.lock_server(&server.id).await; + // Whatever we waited on may have stopped or restarted the server — + // only back up one that's still fully up (a fresh boot after an + // update gets its backup on the next hourly tick). + let still_up = app_state.running_servers.lock().unwrap() + .get(&server.id) + .is_some_and(|rs| rs.confirmed_running); + if !still_up { + eprintln!("[backup_manager] Skipping backup for {} — no longer running after waiting", server.id); + continue; + } + guard + } else { + match app_state.try_lock_server(&server.id) { + Some(guard) => guard, + None => { + eprintln!("[backup_manager] Deferring backup for {} — another operation is in progress", server.id); + queue.push_back((server, true)); + continue; + } + } }; let schedules = db::get_server_schedules(&conn, &server.id); diff --git a/src-tauri/src/commands/countdown.rs b/src-tauri/src/commands/countdown.rs index 2561168..694ae79 100644 --- a/src-tauri/src/commands/countdown.rs +++ b/src-tauri/src/commands/countdown.rs @@ -286,19 +286,18 @@ pub async fn start_graceful_restart( // Fail fast if a backup/update is already in progress for this server — // held for the whole operation, including the countdown, since a backup // that started mid-countdown and was still running when doexit fires - // would hit the same race this guards against. Not a `ServerLockGuard` - // (RAII) since that can't cross into the spawned 'static task below — - // released manually on every exit path instead, the same way - // `stopping_servers`/`countdowns` already span this spawn boundary. - if !state.busy_servers.lock().unwrap().insert(params.server_id.clone()) { + // would hit the same race this guards against. The guard is owned, so it + // moves into the spawned task below and is released when that finishes. + let Some(server_lock) = state.try_lock_server(¶ms.server_id) else { deregister_countdown(&state, ¶ms.server_id); return Err(format!("An operation is already in progress for {} — try again in a moment", params.server_id)); - } + }; let app2 = app.clone(); // Spawn so the command returns immediately. tauri::async_runtime::spawn(async move { + let _server_lock = server_lock; let state2 = app2.state::(); let result = run_countdown( &app2, @@ -335,7 +334,6 @@ pub async fn start_graceful_restart( error: None, }); } - state2.busy_servers.lock().unwrap().remove(¶ms.server_id); }); Ok(()) @@ -373,24 +371,18 @@ pub async fn start_graceful_update( let mut rx = try_register_countdown(&state, ¶ms.server_id)?; // Fail fast if a backup/restart is already in progress for this server — - // see start_graceful_restart's comment for why this can't be a - // `ServerLockGuard` (RAII) across the spawn boundary below. Released by - // `ReleaseBusyOnDrop` inside the spawned task instead, since that task - // has several early-return exit points this needs to cover uniformly. - if !state.busy_servers.lock().unwrap().insert(params.server_id.clone()) { + // see start_graceful_restart. Moved into the spawned task below, which + // releases it on whichever of its exit paths it takes. + let Some(server_lock) = state.try_lock_server(¶ms.server_id) else { deregister_countdown(&state, ¶ms.server_id); return Err(format!("An operation is already in progress for {} — try again in a moment", params.server_id)); - } + }; let app2 = app.clone(); tauri::async_runtime::spawn(async move { + let _server_lock = server_lock; let state2 = app2.state::(); - struct ReleaseBusyOnDrop<'a> { state: &'a AppState, server_id: &'a str } - impl Drop for ReleaseBusyOnDrop<'_> { - fn drop(&mut self) { self.state.busy_servers.lock().unwrap().remove(self.server_id); } - } - let _release_busy = ReleaseBusyOnDrop { state: &state2, server_id: ¶ms.server_id }; // Only run countdown if server is actually running. let proceed = if was_running { @@ -435,23 +427,38 @@ pub async fn start_graceful_update( error: None, }); - // Run SteamCMD update. + // Sync the shared cache into the server directory. The cache was + // already brought current by the update check that flagged this + // server — running SteamCMD again here (as this used to) meant one + // SteamCMD process per server against the same shared cache dir, + // which isn't safe when several updates overlap. let channel = format!("steamcmd://output/{}", params.server_id); - if let Err(e) = tokio::fs::create_dir_all(¶ms.cache_dir).await { - eprintln!("Failed to create cache dir: {e}"); - } - - let update_result = crate::commands::steamcmd::steamcmd_app_update( - &app2, - ¶ms.steamcmd_path, - ¶ms.cache_dir, - false, - &channel, - None, - ).await; - - if let Err(e) = update_result { - eprintln!("Scheduled update SteamCMD failed: {e}"); + let sync_result: Result<(), String> = async { + tokio::fs::create_dir_all(¶ms.cache_dir).await + .map_err(|e| format!("Failed to create cache dir: {e}"))?; + let _cache_guard = state2.asa_cache_lock.clone().read_owned().await; + let cache_path = std::path::PathBuf::from(¶ms.cache_dir); + let server_path = std::path::PathBuf::from(¶ms.install_path); + let app_clone = app2.clone(); + let channel_clone = channel.clone(); + tokio::task::spawn_blocking(move || { + // Not individually cancellable from this countdown-triggered path — a never-set flag is correct here. + let no_abort = std::sync::atomic::AtomicBool::new(false); + crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) + }) + .await + .map_err(|e| format!("Sync task panicked: {e}"))? + .map_err(|e| format!("Failed to sync server files: {e}")) + }.await; + + if let Err(e) = sync_result { + // Leave update_available set — the update did NOT happen. + crate::commands::notifications::dispatch_notification( + &app2, "update_failed", Some(¶ms.server_id), ¶ms.server_name, + "Server Update Failed", + &format!("Failed to update {}: {e}", params.server_name), + "error", + ).await; emit_status(&app2, &ServerStatus { server_id: params.server_id.clone(), status: "stopped".into(), @@ -462,29 +469,28 @@ pub async fn start_graceful_update( return; } - // Sync updated cache to server directory. - let cache_path = std::path::PathBuf::from(¶ms.cache_dir); - let server_path = std::path::PathBuf::from(¶ms.install_path); - let app_clone = app2.clone(); - let channel_clone = channel.clone(); - if let Err(e) = tokio::task::spawn_blocking(move || { - // Not individually cancellable from this countdown-triggered path — a never-set flag is correct here. - let no_abort = std::sync::atomic::AtomicBool::new(false); - crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) - }).await.map_err(|e| e.to_string()).and_then(|r| r.map_err(|e| e.to_string())) { - eprintln!("Cache sync failed: {e}"); + let acf = std::path::Path::new(¶ms.install_path).join(crate::commands::steamcmd::ACF_REL_PATH); + if let Some(build_id) = crate::commands::steamcmd::read_acf_build_id(&acf) { + crate::commands::build_version::record_install(&app2, ¶ms.server_id, &build_id); } - // Emit update-available cleared. - let _ = app2.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ - "updateApplied": true, - "serverId": params.server_id, - })); + // Clear the flag before announcing it, so the frontend's refresh on + // this event reads the cleared value. if let Some(db_path) = state2.get_db_path() { if let Ok(conn) = crate::db::open(&db_path) { crate::db::clear_update_available(&conn, ¶ms.server_id); } } + let _ = app2.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ + "updateApplied": true, + "serverId": params.server_id, + })); + crate::commands::notifications::dispatch_notification( + &app2, "server_updated", Some(¶ms.server_id), ¶ms.server_name, + "Server Updated", + &format!("{} has been updated successfully.", params.server_name), + "success", + ).await; // Restart if requested — hand off to the staggered startup queue // rather than starting directly, same as the scheduler's post-update diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 6339ef9..64e5c2b 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -31,30 +31,22 @@ pub struct SchedulerFiredPayload { /// and once on startup after the DB is ready. Rust fires entries purely based on /// `next_run_ms` — cron parsing lives entirely in the frontend (cron-parser). /// -/// Preserves `u64::MAX` for any entry that is currently in-flight. The frontend -/// may push a stale (already-past) `next_run_ms` for such entries before it has -/// had a chance to update the DB with the fire's real result — overwriting -/// `u64::MAX` with that stale value would cause an immediate re-fire on the -/// next tick. Only guard against *stale* incoming values though: the resync -/// that runs right after the fire actually completes carries a genuinely -/// future `next_run_ms`, and must be allowed through — otherwise the entry -/// would stay locked at `u64::MAX` forever (every later resync would see the -/// still-MAX stored value and re-lock its own fresh value too), so a schedule -/// would only ever fire once per app session. +/// Any entry whose fire task is still running (tracked in +/// `SchedulerState::in_flight`) stays parked at `u64::MAX` regardless of what +/// the frontend pushes — it only gets re-armed by the resync that follows its +/// own `scheduler://fired` event, after the task has removed itself from +/// `in_flight`. #[tauri::command] pub async fn sync_schedules( entries: Vec, state: tauri::State<'_, SchedulerState>, ) -> Result<(), String> { - let now = now_ms(); + let in_flight = state.in_flight.lock().unwrap().clone(); let mut store = state.entries.lock().unwrap(); let mut updated = entries; for entry in updated.iter_mut() { - if let Some(existing) = store.iter().find(|e| e.schedule_id == entry.schedule_id) { - if existing.next_run_ms == u64::MAX && entry.next_run_ms <= now { - // Entry is in-flight and this push still looks stale — keep the guard. - entry.next_run_ms = u64::MAX; - } + if in_flight.contains(&entry.schedule_id) { + entry.next_run_ms = u64::MAX; } } *store = updated; @@ -126,25 +118,49 @@ async fn fire_wipe_dinos(app: &AppHandle, entry: &crate::state::scheduler::Sched Ok(()) } +/// Wait for this server's operation lock, queueing behind whatever backup / +/// restart / update / stop already holds it. Returns the guard plus whether +/// we actually had to wait (i.e. something else ran on this server first). +async fn queue_for_server(app: &AppHandle, server_id: &str) -> (crate::state::ServerLockGuard, bool) { + let state = app.state::(); + if let Some(guard) = state.try_lock_server(server_id) { + return (guard, false); + } + (state.lock_server(server_id).await, true) +} + +fn is_confirmed_running(app: &AppHandle, server_id: &str) -> bool { + let state = app.state::(); + let registry = state.running_servers.lock().unwrap(); + registry.get(server_id).map(|rs| rs.confirmed_running).unwrap_or(false) +} + async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { if !super::server::is_server_running(app, &entry.server_id) { return Ok(()); } - // Mid-boot (spawned but not yet RCON-confirmed) — see fire_update for why - // this skips the countdown/graceful handshake entirely. - let is_confirmed_running = { - let state = app.state::(); - let registry = state.running_servers.lock().unwrap(); - registry.get(&entry.server_id).map(|rs| rs.confirmed_running).unwrap_or(false) - }; - // Refuse to restart a server whose hourly backup is currently in - // progress — killing the process mid-backup can produce a silently - // incomplete archive. The restart will fire again at its next scheduled - // occurrence. + // Queue behind any backup / update / stop already in progress on this + // server rather than failing — killing the process mid-backup could + // produce a silently incomplete archive, but dropping the restart until + // its next occurrence (as this used to) isn't what anyone wants either. + let (_lock, waited) = queue_for_server(app, &entry.server_id).await; let state = app.state::(); - let _lock = state.try_lock_server(&entry.server_id) - .ok_or_else(|| format!("A backup is currently in progress for {} — restart will retry next time", entry.server_id))?; + + // Re-evaluate now that we hold the lock — whatever we waited on may have + // stopped or restarted the server already. + if !super::server::is_server_running(app, &entry.server_id) { + return Ok(()); + } + // Mid-boot (spawned but not yet RCON-confirmed) — see fire_update for why + // this skips the countdown/graceful handshake entirely. + let is_confirmed_running = is_confirmed_running(app, &entry.server_id); + if waited && !is_confirmed_running { + // We queued behind something (typically an update) that already + // restarted this server — it's booting fresh right now, so a second + // restart would only throw that boot away. + return Ok(()); + } if is_confirmed_running { let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); @@ -154,12 +170,9 @@ async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::Schedule let (tx, mut rx) = tokio::sync::mpsc::channel::(1); { - let state = app.state::(); let mut cd = state.countdowns.lock().unwrap(); - // Refuse to start a second countdown for this server — otherwise a - // restart and an update schedule (or two restarts) becoming due in - // the same tick would silently overwrite each other's countdown - // handle and both run their own stop/start sequence concurrently. + // A countdown not started under this server's lock (shouldn't + // happen, but never clobber another task's cancel handle). if cd.contains_key(&entry.server_id) { return Err(format!("A countdown is already in progress for {}", entry.server_id)); } @@ -178,10 +191,7 @@ async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::Schedule &mut rx, ).await; - { - let state = app.state::(); - state.countdowns.lock().unwrap().remove(&entry.server_id); - } + state.countdowns.lock().unwrap().remove(&entry.server_id); if matches!(result, super::countdown::CountdownResult::Cancel) { return Ok(()); @@ -239,6 +249,11 @@ async fn fire_global_update_check( .unwrap_or_else(|| "0".to_string()); let state = app.state::(); + // A manual check is running right now — skip this tick silently (before + // announcing anything to the UI); the next scheduled tick will retry. + if state.abort_flags.lock().unwrap().contains_key(crate::commands::steamcmd::ASA_CACHE_CHECK_KEY) { + return Ok(()); + } let _ = app.emit(crate::events::ASA_UPDATE_CHECK_RUNNING, serde_json::json!({ "running": true })); let result = crate::commands::steamcmd::update_cache_inner( crate::commands::steamcmd::ASA_CACHE_CHECK_KEY, @@ -273,23 +288,61 @@ async fn fire_global_update_check( } async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { + use crate::commands::server::{emit_status, ServerStatus}; + use crate::commands::steamcmd::{get_cache_build_id, read_acf_build_id, ACF_REL_PATH}; + let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); let sep = if entry.base_dir.contains('\\') { '\\' } else { '/' }; let cache_dir = format!("{}{sep}lokiasam{sep}cache{sep}asa-server", entry.base_dir); - let is_running = super::server::is_server_running(app, &entry.server_id); + let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; + let skip_if_players = cfg["skipIfPlayersOnline"].as_bool().unwrap_or(false); + let restart_after = cfg["restartAfterUpdate"].as_bool().unwrap_or(true); + // When false, restart_after applies even if the server was stopped before + // the update (used by per-server Auto-Update automation's "Only restart if + // server was already running" toggle — unchecked means "always end up + // running after an update"). + let only_if_running = cfg["onlyIfRunning"].as_bool().unwrap_or(true); + let message = cfg["message"].as_str().unwrap_or("Server going down for update in {time}.").to_string(); + let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); + + // Queue behind any backup / restart / stop / manual update already + // running on this server instead of failing — overwriting files + // mid-backup could produce a silently incomplete archive, so we wait our + // turn and then pick up wherever that operation left the server. + let (_lock, _waited) = queue_for_server(app, &entry.server_id).await; + let state = app.state::(); + + // Whatever we waited on may already have applied this exact update + // (e.g. the user clicked Update All, or a manual update ran) — if the + // server's installed build already matches the cache, there's nothing to + // do, and stopping/restarting it would just kick players for no reason. + let installed_build = read_acf_build_id(&std::path::Path::new(&entry.install_path).join(ACF_REL_PATH)); + let cache_build = get_cache_build_id(&cache_dir); + if installed_build.is_some() && installed_build == cache_build { + if let Some(db_path) = state.get_db_path() { + if let Ok(conn) = crate::db::open(&db_path) { + crate::db::clear_update_available(&conn, &entry.server_id); + } + } + let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ + "updateApplied": true, + "serverId": entry.server_id, + })); + return Ok(()); + } + + // Evaluated only now, after the wait — the server's state may have + // changed completely while we were queued. + let is_running = super::server::is_server_running(app, &entry.server_id); // Distinguish "fully up and joinable" from "spawned but still mid-boot" — // the confirmed_running flag on the running_servers entry tells them apart. - let is_confirmed_running = { - let state = app.state::(); - let registry = state.running_servers.lock().unwrap(); - registry.get(&entry.server_id).map(|rs| rs.confirmed_running).unwrap_or(false) - }; + let is_confirmed_running = is_confirmed_running(app, &entry.server_id); // A server that hadn't even been spawned yet, but was sitting in the // startup queue, isn't caught by is_running at all — read the live DB // status directly to catch that case too. - let was_queued_for_startup = app.state::().get_db_path() + let was_queued_for_startup = state.get_db_path() .and_then(|p| crate::db::open(&p).ok()) .and_then(|conn| crate::db::get_server_status(&conn, &entry.server_id)) .as_deref() == Some("startup_queued"); @@ -298,16 +351,6 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE // branch below for why that always finishes the launch regardless of // only_if_running, and does so via the startup queue rather than directly. let interrupted_startup = (is_running && !is_confirmed_running) || was_queued_for_startup; - let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; - let skip_if_players = cfg["skipIfPlayersOnline"].as_bool().unwrap_or(false); - let restart_after = cfg["restartAfterUpdate"].as_bool().unwrap_or(true); - // When false, restart_after applies even if the server was stopped before - // the update (used by per-server Auto-Update automation's "Only restart if - // server was already running" toggle — unchecked means "always end up - // running after an update"). - let only_if_running = cfg["onlyIfRunning"].as_bool().unwrap_or(true); - let message = cfg["message"].as_str().unwrap_or("Server going down for update in {time}.").to_string(); - let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); // Skip entirely if players are online and the schedule says to. if is_running && skip_if_players { @@ -320,15 +363,6 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE } } - // Refuse to update a server whose hourly backup is currently reading its - // files — overwriting them mid-backup can produce a silently incomplete - // archive. The per-server auto-update entry is regenerated on the next - // schedule sync as long as update_available stays set, so this retries - // shortly rather than being lost. - let state = app.state::(); - let _lock = state.try_lock_server(&entry.server_id) - .ok_or_else(|| format!("A backup is currently in progress for {} — update will retry shortly", entry.server_id))?; - if is_running && !is_confirmed_running { // Mid-boot: the process is spawned but RCON isn't up yet, so there's no // world state to save and no players to warn — the countdown and the @@ -347,11 +381,8 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE } else if is_confirmed_running { let (tx, mut rx) = tokio::sync::mpsc::channel::(1); { - let state = app.state::(); let mut cd = state.countdowns.lock().unwrap(); - // See fire_restart — refuse to clobber a countdown already in - // progress for this server (e.g. a restart schedule racing this - // update schedule in the same tick). + // See fire_restart — never clobber another task's cancel handle. if cd.contains_key(&entry.server_id) { return Err(format!("A countdown is already in progress for {}", entry.server_id)); } @@ -370,10 +401,7 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE &mut rx, ).await; - { - let state = app.state::(); - state.countdowns.lock().unwrap().remove(&entry.server_id); - } + state.countdowns.lock().unwrap().remove(&entry.server_id); if matches!(result, super::countdown::CountdownResult::Cancel) { return Ok(()); @@ -387,8 +415,14 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE state.wait_for_stop_handoff(&entry.server_id, notify).await; } + crate::commands::notifications::dispatch_notification( + app, "update_started", Some(&entry.server_id), &entry.server_name, + "Auto-Update Started", + &format!("Applying ASA server update to {}…", entry.server_name), + "info", + ).await; + // Emit "updating" so the server card shows the spinner. - use crate::commands::server::{emit_status, ServerStatus}; emit_status(app, &ServerStatus { server_id: entry.server_id.clone(), status: "updating".into(), @@ -402,52 +436,67 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE // brought current by the global check that flagged this server as // outdated in the first place (same as the manual/bulk apply path, which // only ever calls apply_cache_to_server, never steamcmd_app_update). - // Re-running a full SteamCMD app_update per server was not just redundant - // but actively unsafe: when several servers' "When Found" automation - // fires in the same tick, each spawned its own SteamCMD process against - // this same shared cache directory concurrently, which SteamCMD does not - // handle safely (lock contention/hangs between instances) — this was the - // actual cause of updates appearing to stall the startup queue. + // Re-running SteamCMD per server would mean several SteamCMD processes + // against the same shared cache directory at once, which SteamCMD does + // not handle safely. let channel = format!("steamcmd://output/{}", entry.server_id); - tokio::fs::create_dir_all(&cache_dir) + let sync_result: Result<(), String> = async { + tokio::fs::create_dir_all(&cache_dir) + .await + .map_err(|e| format!("Failed to create cache dir: {e}"))?; + + // Read half of the cache lock — several servers may sync at once, but + // never while an update check has SteamCMD rewriting the cache. + let _cache_guard = state.asa_cache_lock.clone().read_owned().await; + let cache_path = std::path::PathBuf::from(&cache_dir); + let server_path = std::path::PathBuf::from(&entry.install_path); + let app_clone = app.clone(); + let channel_clone = channel.clone(); + tokio::task::spawn_blocking(move || { + // Scheduled updates aren't individually cancellable — a never-set flag is correct here. + let no_abort = std::sync::atomic::AtomicBool::new(false); + crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) + }) .await - .map_err(|e| format!("Failed to create cache dir: {e}"))?; - - // Sync updated files to the server directory (preserving Saved/). - let cache_path = std::path::PathBuf::from(&cache_dir); - let server_path = std::path::PathBuf::from(&entry.install_path); - let app_clone = app.clone(); - let channel_clone = channel.clone(); - tokio::task::spawn_blocking(move || { - // Scheduled updates aren't individually cancellable — a never-set flag is correct here. - let no_abort = std::sync::atomic::AtomicBool::new(false); - crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) - }) - .await - .map_err(|e| format!("Sync task panicked: {e}"))? - .map_err(|e| format!("Failed to sync server files: {e}"))?; + .map_err(|e| format!("Sync task panicked: {e}"))? + .map_err(|e| format!("Failed to sync server files: {e}")) + } + .await; - // Record updated build ID and trigger internet version fetch - let acf = std::path::Path::new(&entry.install_path) - .join(crate::commands::steamcmd::ACF_REL_PATH); - if let Some(build_id) = crate::commands::steamcmd::read_acf_build_id(&acf) { - crate::commands::build_version::record_install(app, &entry.server_id, &build_id); + if let Err(e) = sync_result { + // Never leave the server stuck on the "updating" spinner — the + // update_available flag stays set so it's retried / visible. + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + status: "stopped".into(), + pid: None, + uptime_seconds: None, + error: Some(e.clone()), + }); + return Err(e); } - let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ - "updateApplied": true, - "serverId": entry.server_id, - })); + // Record updated build ID and trigger internet version fetch + let acf = std::path::Path::new(&entry.install_path).join(ACF_REL_PATH); + let new_build = read_acf_build_id(&acf); + if let Some(build_id) = &new_build { + crate::commands::build_version::record_install(app, &entry.server_id, build_id); + } // Clear the per-server update flag — otherwise the UI keeps showing // "Update Available" and, for "immediately" mode, the next scheduler // sync would generate this same auto-update entry all over again. - if let Some(db_path) = app.state::().get_db_path() { + if let Some(db_path) = state.get_db_path() { if let Ok(conn) = crate::db::open(&db_path) { crate::db::clear_update_available(&conn, &entry.server_id); } } + let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ + "updateApplied": true, + "serverId": entry.server_id, + })); + // Restart if requested — either the server was already fully running, the // schedule says to bring it up regardless (only_if_running = false), or it // was on its way up (mid-boot or queued) when this update interrupted it. @@ -459,31 +508,28 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE // starting directly — several servers restarting after the same update // check shouldn't all cold-boot at once. The "server://any-change" // listener re-enqueues on this status. - if restart_after && (is_confirmed_running || !only_if_running || interrupted_startup) { - use crate::commands::server::{emit_status, ServerStatus}; - emit_status(app, &ServerStatus { - server_id: entry.server_id.clone(), - status: "startup_queued".into(), - pid: None, - uptime_seconds: None, - error: None, - }); - } else { - // No restart is coming — the server was already stopped and the - // automation config says to leave it that way (or restart_after is - // off). Nothing else ever clears the "updating" status set above for - // this case, so without this the server sits stuck showing the - // in-progress spinner (Overview/dashboard) until the user manually - // Cancels and Reinstalls, even though the update itself succeeded. - use crate::commands::server::{emit_status, ServerStatus}; - emit_status(app, &ServerStatus { - server_id: entry.server_id.clone(), - status: "stopped".into(), - pid: None, - uptime_seconds: None, - error: None, - }); - } + let restarting = restart_after && (is_confirmed_running || !only_if_running || interrupted_startup); + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + // No restart coming → explicitly "stopped"; nothing else would ever + // clear the "updating" status set above for this case. + status: if restarting { "startup_queued" } else { "stopped" }.into(), + pid: None, + uptime_seconds: None, + error: None, + }); + + crate::commands::notifications::dispatch_notification( + app, "server_updated", Some(&entry.server_id), &entry.server_name, + "Server Auto-Updated", + &format!( + "{} was updated{}{}.", + entry.server_name, + new_build.map(|b| format!(" to build {b}")).unwrap_or_default(), + if restarting { " and is restarting" } else { "" }, + ), + "success", + ).await; Ok(()) } @@ -504,6 +550,12 @@ pub fn tick_scheduler(app: &AppHandle) { due.push(entry.clone()); } } + // Registered under the entries lock so a concurrent sync_schedules + // can't slip in between and re-arm one of these. + let mut in_flight = scheduler.in_flight.lock().unwrap(); + for entry in &due { + in_flight.insert(entry.schedule_id.clone()); + } due }; @@ -539,6 +591,19 @@ pub fn tick_scheduler(app: &AppHandle) { _ => (false, Some(format!("Unknown schedule type: {schedule_type}"))), }; + if schedule_type == "update" && !success { + crate::commands::notifications::dispatch_notification( + &app, "update_failed", Some(&server_id), &server_name, + "Auto-Update Failed", + &format!("{server_name}: {}", error.as_deref().unwrap_or("unknown error")), + "error", + ).await; + } + + // Cleared before emitting `scheduler://fired`, so the resync the + // frontend runs in response is allowed to re-arm this entry. + app.state::().in_flight.lock().unwrap().remove(&schedule_id); + let _ = app.emit( "scheduler://fired", SchedulerFiredPayload { diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 092dc9b..7fc64bc 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1410,9 +1410,10 @@ pub async fn graceful_stop_server( // Held for the whole operation (including the player-warning countdown, // which can run for several minutes) so a scheduled backup can't start - // mid-shutdown and produce a truncated archive. - let _lock = state.try_lock_server(&server_id) - .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + // mid-shutdown and produce a truncated archive. Queues behind a backup + // that's already running rather than failing — the stop simply happens + // once the backup has finished reading the server's files. + let _lock = state.lock_server(&server_id).await; let (pid, install_path, server_name) = { let registry = state.running_servers.lock().unwrap(); diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index 6ee9240..fb782a4 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -504,6 +504,7 @@ pub async fn install_server( let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); let result = async { + let _cache_guard = state.asa_cache_lock.clone().write_owned().await; emit_line(&app_handle, &channel, "stdout", &format!("Ensuring server cache at: {cache_dir}"))?; tokio::fs::create_dir_all(&cache_dir).await @@ -565,6 +566,7 @@ pub async fn update_server( let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); let result = async { + let _cache_guard = state.asa_cache_lock.clone().write_owned().await; emit_line(&app_handle, &channel, "stdout", "Checking for updates (cache)…")?; tokio::fs::create_dir_all(&cache_dir).await .map_err(|e| format!("Failed to ensure cache directory: {e}"))?; @@ -613,8 +615,12 @@ pub async fn validate_server_files( cache_dir: String, steamcmd_path: String, app_handle: tauri::AppHandle, + state: tauri::State<'_, crate::state::AppState>, ) -> Result<(), String> { let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); + // Overwrites this server's files — queue behind any backup reading them. + let _lock = state.lock_server(&server_id).await; + let _cache_guard = state.asa_cache_lock.clone().write_owned().await; emit_line(&app_handle, &channel, "stdout", "Validating server files in cache…")?; tokio::fs::create_dir_all(&cache_dir).await @@ -742,6 +748,10 @@ pub async fn update_cache_inner( let abort = state.register_abort(server_id); let result: Result = async { + // Exclusive access to the cache while SteamCMD rewrites it — waits for + // any in-progress cache→server syncs (auto-update/apply) to finish + // first, and holds off new ones until the check is done. + let _cache_guard = state.asa_cache_lock.clone().write_owned().await; emit_line(app_handle, &channel, "stdout", "Updating server cache from Steam…")?; tokio::fs::create_dir_all(&cache_dir) .await @@ -792,14 +802,26 @@ pub async fn apply_cache_to_server( // Auto-Update landing on the same server around the same moment — both // used to sync the cache into the same install directory concurrently // with no coordination at all. - let _lock = state.try_lock_server(&server_id) - .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + // + // Queues (rather than failing) behind a backup or other operation that's + // already running on this server, so "Update All" doesn't fail a server + // just because its hourly backup happened to be mid-way through. + let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); + let _lock = match state.try_lock_server(&server_id) { + Some(guard) => guard, + None => { + let _ = emit_line(&app_handle, &channel, "stdout", + "Waiting for another operation on this server (e.g. a backup) to finish…"); + state.lock_server(&server_id).await + } + }; let op_key = format!("server_{server_id}"); let abort = state.register_abort(&op_key); - let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); let result = async { + // Never copy from the cache while an update check is rewriting it. + let _cache_guard = state.asa_cache_lock.clone().read_owned().await; emit_line(&app_handle, &channel, "stdout", "Syncing updated files to server (preserving Saved/ data)…")?; diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index b3817af..a77928e 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -60,12 +60,21 @@ pub struct AppState { /// Used by Rust-side business logic (backup manager, notification dispatch) to open /// their own rusqlite connections without blocking the Tauri plugin-sql connection. pub db_path: Mutex>, - /// Server IDs currently undergoing a backup, restart, or update — held for - /// the whole operation so the hourly backup tick and a scheduled - /// restart/update can never run concurrently against the same server - /// (a restart/update killing or overwriting files mid-backup can produce - /// a silently-incomplete archive). Acquire via `try_lock_server`. - pub busy_servers: Mutex>, + /// Per-server operation locks (backup, restart, update, stop, delete…). + /// Each server gets its own FIFO-fair async mutex, so automated work + /// (hourly backups, scheduled restarts/updates, auto-update) *queues* + /// behind whatever is already running on that server instead of failing + /// outright — e.g. a restart that comes due mid-backup now runs as soon + /// as the backup finishes rather than being dropped until its next + /// occurrence. Interactive callers that would rather fail fast use + /// `try_lock_server`; queued callers use `lock_server`. + pub server_locks: Mutex>>>, + /// Guards the shared ASA server cache directory. SteamCMD writing to the + /// cache (update check, reinstall, verify) takes the write half; copying + /// the cache into a server install (apply/auto-update) takes the read + /// half — so several servers can sync at once, but never while SteamCMD + /// is mid-way through rewriting the files they're copying. + pub asa_cache_lock: Arc>, /// Server IDs whose current stop is being orchestrated by a restart/update /// flow rather than a plain Stop. The process-exit watcher spawned back /// when the server was originally started predates that flow and @@ -81,20 +90,10 @@ pub struct AppState { pub restart_handoff: Mutex>>, } -/// RAII guard returned by `AppState::try_lock_server` — releases the lock -/// when dropped, on every exit path (return, `?`, panic unwind) of whichever -/// scope holds it. -pub struct ServerLockGuard<'a> { - state: &'a AppState, - server_id: String, -} - -impl Drop for ServerLockGuard<'_> { - fn drop(&mut self) { - self.state.busy_servers.lock().unwrap().remove(&self.server_id); - } -} - +/// Guard returned by `AppState::try_lock_server` / `lock_server` — releases +/// the server's lock when dropped, on every exit path. Owned (`'static`), so +/// it can be moved into a spawned task that outlives the command call. +pub type ServerLockGuard = tokio::sync::OwnedMutexGuard<()>; impl AppState { pub fn new() -> Self { @@ -111,21 +110,30 @@ impl AppState { abort_flags: Mutex::new(HashMap::new()), countdowns: Mutex::new(HashMap::new()), db_path: Mutex::new(None), - busy_servers: Mutex::new(HashSet::new()), + server_locks: Mutex::new(HashMap::new()), + asa_cache_lock: Arc::new(tokio::sync::RwLock::new(())), restart_handoff: Mutex::new(HashMap::new()), } } - /// Attempt to mark a server as busy (backup/restart/update in progress). - /// Returns `None` if another operation already holds the lock; otherwise - /// a guard that releases it when dropped. - pub fn try_lock_server(&self, server_id: &str) -> Option> { - let inserted = self.busy_servers.lock().unwrap().insert(server_id.to_string()); - if inserted { - Some(ServerLockGuard { state: self, server_id: server_id.to_string() }) - } else { - None - } + fn server_mutex(&self, server_id: &str) -> Arc> { + Arc::clone( + self.server_locks.lock().unwrap() + .entry(server_id.to_string()) + .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))), + ) + } + + /// Attempt to take a server's operation lock without waiting. Returns + /// `None` if another operation already holds it. + pub fn try_lock_server(&self, server_id: &str) -> Option { + self.server_mutex(server_id).try_lock_owned().ok() + } + + /// Take a server's operation lock, waiting in FIFO order behind any + /// operation that already holds it (or is already queued for it). + pub async fn lock_server(&self, server_id: &str) -> ServerLockGuard { + self.server_mutex(server_id).lock_owned().await } /// Store the database file path (called from init_stats_recorder). diff --git a/src-tauri/src/state/scheduler.rs b/src-tauri/src/state/scheduler.rs index 84a37ee..9e3e0d2 100644 --- a/src-tauri/src/state/scheduler.rs +++ b/src-tauri/src/state/scheduler.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use std::collections::HashSet; use std::sync::Mutex; /// One schedule entry with all data needed to fire the action — no DB access required. @@ -45,12 +46,20 @@ pub struct ScheduleEntry { /// Atomically replaced by `sync_schedules` whenever the frontend saves changes. pub struct SchedulerState { pub entries: Mutex>, + /// Schedule IDs whose fire task is still running. `sync_schedules` keeps + /// these parked at `u64::MAX` no matter what `next_run_ms` the frontend + /// pushes, so a resync mid-fire (e.g. one triggered by an unrelated + /// schedule finishing) can never re-arm an entry that's still executing — + /// a per-server auto-update in a 15-minute warning countdown used to get + /// re-fired every ~15 s this way. + pub in_flight: Mutex>, } impl SchedulerState { pub fn new() -> Self { Self { entries: Mutex::new(Vec::new()), + in_flight: Mutex::new(HashSet::new()), } } } diff --git a/src/app/page.tsx b/src/app/page.tsx index 2fb4354..24c43d5 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -20,7 +20,7 @@ import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; import { getAppSetting, updateServerStatus } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; -import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToAllServers, isAutoUpdateImmediate, type ServerUpdateInfo } from "@/lib/update-utils"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToAllServers, isAutoUpdateImmediate, getAutoUpdatePlan, type ServerUpdateInfo } from "@/lib/update-utils"; import { restartServerGracefully, stopServerGracefully } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -438,6 +438,7 @@ export default function DashboardPage() { installedBuild: "—", cachedBuild: "—", autoUpdateImmediate: false, + autoUpdatePlan: getAutoUpdatePlan(s), })); const anyUpdatesStarting = serversWithUpdates.some((s) => s.status === "starting"); diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 6492da3..7bc00e7 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -32,6 +32,7 @@ import { } from "@/lib/db"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { useAutostart } from "@/hooks/useAutostart"; +import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToAllServers, isAutoUpdateImmediate } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; @@ -994,6 +995,9 @@ function ServerUpdatesSection({ onPreDownload }: { onPreDownload?: () => void }) const handleAutoCheckChange = async (value: string) => { setAutoCheck(value); await setAppSetting("asa_auto_check_hours", value); + // Apply immediately — otherwise the new mode only took effect after the + // next unrelated resync (or an app restart). + await syncSchedulesToRust(); }; return ( diff --git a/src/components/layout/SchedulerManager.tsx b/src/components/layout/SchedulerManager.tsx index 96917e7..c7844c0 100644 --- a/src/components/layout/SchedulerManager.tsx +++ b/src/components/layout/SchedulerManager.tsx @@ -18,11 +18,16 @@ import { updateScheduleRun, getScheduleById, setAppSetting, rollupOldStats, } from "@/lib/db"; import { getNextCronDate } from "@/components/shared/CronBuilder"; -import { syncSchedulesToRust } from "@/lib/scheduler-sync"; -import { runPerServerUpdateCheck } from "@/lib/update-utils"; +import { syncSchedulesToRust, noteAutoUpdateFailure } from "@/lib/scheduler-sync"; +import { runPerServerUpdateCheck, describeUpdatePlans } from "@/lib/update-utils"; import { useAppStore } from "@/store/useAppStore"; import type { SchedulerFiredPayload, UpdateCheckResult } from "@/lib/tauri-commands"; +/** Toast id for the background update check — one toast that goes from + * "checking…" to the result, instead of a check that's only visible as a + * small TopBar spinner. */ +const BG_CHECK_TOAST_ID = "asa-background-update-check"; + // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- @@ -38,6 +43,13 @@ export function SchedulerManager() { // off it) reflect a check that's running in the background. useTauriEvent<{ running: boolean }>("asa://update-check/running", (payload) => { setAsaCacheOpLabel(payload.running ? "Checking ASA updates (background)…" : null); + if (payload.running) { + toast.loading("Checking for ASA server updates…", { + id: BG_CHECK_TOAST_ID, + description: "Automatic check — SteamCMD is updating the shared server cache.", + duration: Infinity, + }); + } }); // SteamCMD only actually pulls bytes for part of a "check" run — most of it @@ -91,8 +103,26 @@ export function SchedulerManager() { setAppSetting("asa_latest_build_id", r.latestBuildId), setAppSetting("asa_last_checked", new Date().toISOString()), ]); - await runPerServerUpdateCheck(false); + const summary = await runPerServerUpdateCheck(false); queryClient.invalidateQueries({ queryKey: ["servers"] }); + + // Resolve the "checking…" toast with what was found and what will + // happen about it. Newly flagged servers also get a bell notification + // (from runPerServerUpdateCheck) carrying the same breakdown. + const n = summary.allWithUpdates.length; + if (n === 0) { + toast.success("ASA servers are up to date", { + id: BG_CHECK_TOAST_ID, + description: `Automatic check finished — build ${r.latestBuildId}.`, + duration: 6000, + }); + } else { + toast.info(`${n} server${n === 1 ? " needs" : "s need"} an update`, { + id: BG_CHECK_TOAST_ID, + description: describeUpdatePlans(summary.allWithUpdates), + duration: 15000, + }); + } } }, ); @@ -108,7 +138,11 @@ export function SchedulerManager() { // ever emitting that event if the check itself errors out. if (!success) { await setAppSetting("asa_last_checked", new Date().toISOString()); - toast.error(`Auto update check failed: ${error ?? "unknown error"}`); + toast.error("Automatic update check failed", { + id: BG_CHECK_TOAST_ID, + description: error ?? "unknown error", + duration: 10000, + }); } syncSchedulesToRust(); return; @@ -121,13 +155,13 @@ export function SchedulerManager() { await updateScheduleRun(scheduleId, lastRun, nextDate?.toISOString() ?? null); } catch { /* non-fatal */ } - if (success) { - const labels: Record = { - restart: "Scheduled restart completed", - update: "Scheduled update completed", - }; - if (labels[scheduleType]) { - toast.success(`[${serverName}] ${labels[scheduleType]}.`); + // Update results (start / success / failure) are reported by Rust as + // real notifications (toast + bell), so they're not repeated here. + if (scheduleType === "update") { + if (!success) noteAutoUpdateFailure(payload.serverId); + } else if (success) { + if (scheduleType === "restart") { + toast.success(`[${serverName}] Scheduled restart completed.`); } } else { toast.error(`[${serverName}] Scheduled ${scheduleType} failed: ${error ?? "unknown error"}`); diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index d4faff4..9deac9d 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -385,7 +385,13 @@ export function ServerCard({ server }: Props) { steamcmdPath, restartAfter: restartAfterUpdate, startParams, - }).catch((err) => toast.error(`Update failed: ${err}`)); + }).catch(async (err) => { + // Refused before anything happened (e.g. a backup is running) — + // undo the optimistic "stopping" so the server doesn't look stuck. + await updateServerStatus(server.id, server.status, server.pid); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + toast.error(`Update failed: ${err}`); + }); return; } diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index df21108..66e1d9d 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -826,7 +826,13 @@ export function OverviewTab({ server, onNavigateToConfig }: Props) { steamcmdPath, restartAfter: restartAfterUpdate, startParams, - }).catch((err) => toast.error(`Update failed: ${err}`)); + }).catch(async (err) => { + // Refused before anything happened (e.g. a backup is running) — + // undo the optimistic "stopping" so the server doesn't look stuck. + await updateServerStatus(server.id, server.status, server.pid); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + toast.error(`Update failed: ${err}`); + }); return; } diff --git a/src/lib/scheduler-sync.ts b/src/lib/scheduler-sync.ts index a11833d..a1da6a1 100644 --- a/src/lib/scheduler-sync.ts +++ b/src/lib/scheduler-sync.ts @@ -16,6 +16,24 @@ import { ensureMapsCacheLoaded, findMapById } from "@/lib/maps"; import { getNextCronDate } from "@/components/shared/CronBuilder"; import { launchArgsToExtraArgs } from "@/lib/server-utils"; +/** When this app session started — the "on startup" update check is due + * whenever the last check predates it (i.e. hasn't happened this session). */ +const SESSION_STARTED_MS = Date.now(); +/** Fixed fire time for this session's startup check, computed once — every + * resync used to push it another 30 s into the future, and any resync while + * it was running re-armed it to fire a second time. */ +let startupCheckAtMs: number | null = null; + +/** serverId → earliest time a failed "When Found" auto-update may retry. + * Without this, a persistent failure (disk full, permissions…) re-fired + * every 15 s forever, each time with its own error notification. */ +const autoUpdateRetryAfter = new Map(); +const AUTO_UPDATE_RETRY_BACKOFF_MS = 10 * 60_000; + +export function noteAutoUpdateFailure(serverId: string): void { + autoUpdateRetryAfter.set(serverId, Date.now() + AUTO_UPDATE_RETRY_BACKOFF_MS); +} + function isTauriEnv(): boolean { return ( typeof window !== "undefined" && @@ -128,40 +146,35 @@ export async function syncSchedulesToRust(): Promise { // ── Global auto-update-check entry ───────────────────────────────────── // Fires the shared cache update on startup and/or hourly, depending on // the asa_auto_check_hours setting: - // "startup" — fire once ~30 s after launch - // "startup_hourly" — fire ~30 s after launch, then repeat every hour + // "startup" — once per app launch, ~30 s after startup + // "startup_hourly" — once ~30 s after launch, then every hour // "disabled" / "0" — no scheduled check const [autoCheckMode, lastChecked] = await Promise.all([ getAppSetting("asa_auto_check_hours"), getAppSetting("asa_last_checked"), ]); const mode = autoCheckMode ?? "disabled"; - const isStartupHourly = mode === "startup_hourly"; - const isStartup = mode === "startup" || isStartupHourly; // Legacy numeric values ("1","6","12","24") treated as startup_hourly. const legacyHours = parseInt(mode); const isLegacy = !isNaN(legacyHours) && legacyHours > 0; + const isHourly = mode === "startup_hourly" || isLegacy; + const isStartup = mode === "startup" || isHourly; - if ((isStartup || isLegacy) && steamcmdPath && baseDir && servers.length > 0) { - const intervalMs = isStartupHourly || isLegacy ? 3_600_000 : 0; + if (isStartup && steamcmdPath && baseDir && servers.length > 0) { + const intervalMs = isHourly ? 3_600_000 : 0; + const lastCheckedMs = lastChecked ? new Date(lastChecked).getTime() : NaN; + const checkedThisSession = !isNaN(lastCheckedMs) && lastCheckedMs >= SESSION_STARTED_MS; // null means "don't schedule a global check this sync" — this must // never short-circuit the rest of the function (per-server auto-update // entries below still need to be built and sent regardless). let nextRunMs: number | null = null; - if (!lastChecked) { - // Never checked — fire 30 s after startup. - nextRunMs = Date.now() + 30_000; - } else if (isStartupHourly || isLegacy) { - const scheduled = new Date(lastChecked).getTime() + intervalMs; - // If overdue, give a 30-second startup buffer before firing. - nextRunMs = scheduled < Date.now() ? Date.now() + 30_000 : scheduled; - } else { - // "startup" mode — only fire if we've never checked (handled above), - // or if it's been at least 24h since the last check. - const sinceLastCheck = Date.now() - new Date(lastChecked).getTime(); - if (sinceLastCheck >= 24 * 3_600_000) { - nextRunMs = Date.now() + 30_000; - } + if (!checkedThisSession) { + // Every launch checks once (a manual check this session counts). + startupCheckAtMs ??= Date.now() + 30_000; + nextRunMs = startupCheckAtMs; + } else if (isHourly) { + // May be in the past if overdue — Rust fires it on the next tick. + nextRunMs = lastCheckedMs + intervalMs; } if (nextRunMs !== null) entries.push({ @@ -193,7 +206,7 @@ export async function syncSchedulesToRust(): Promise { // Synthesized (not stored as `schedules` rows) from each server's // update_automation_json, same pattern as the global-update-check entry // above. Reuses the existing fully-graceful `fire_update` handler in - // scheduler.rs — countdown warning, SaveWorld+doexit, SteamCMD update, + // scheduler.rs — countdown warning, SaveWorld+doexit, cache→server // sync, conditional restart — the same safe-shutdown path manual updates // already use. Only generated when there's actually an update available, // so this never restarts a server just to find nothing changed. @@ -212,7 +225,7 @@ export async function syncSchedulesToRust(): Promise { let nextRunMs: number | null = null; if (automation.mode === "immediately") { - nextRunMs = Date.now() + 15_000; + nextRunMs = Math.max(Date.now() + 15_000, autoUpdateRetryAfter.get(server.id) ?? 0); } else if (automation.mode === "at_time") { const [h, m] = automation.update_time.split(":").map(Number); const cron = `${isNaN(m) ? 0 : m} ${isNaN(h) ? 3 : h} * * *`; diff --git a/src/lib/update-utils.ts b/src/lib/update-utils.ts index 35864ec..7134c1c 100644 --- a/src/lib/update-utils.ts +++ b/src/lib/update-utils.ts @@ -29,6 +29,43 @@ export interface ServerUpdateInfo { * will apply automatically within seconds, so manual-update UI should not * offer to double it up. */ autoUpdateImmediate: boolean; + /** What the server's Auto-Update automation will do about it. */ + autoUpdatePlan: AutoUpdatePlan; +} + +export type AutoUpdatePlan = + | { kind: "now" } + | { kind: "at_time"; time: string } + | { kind: "manual" }; + +/** How (and whether) `server`'s Auto-Update automation will apply a pending update. */ +export function getAutoUpdatePlan(server: Pick): AutoUpdatePlan { + try { + const cfg = JSON.parse(server.update_automation_json || "{}"); + if (cfg.mode === "immediately") return { kind: "now" }; + if (cfg.mode === "at_time") return { kind: "at_time", time: cfg.update_time || "03:00" }; + } catch { /* malformed — treat as off */ } + return { kind: "manual" }; +} + +/** Multi-line summary of what will happen to each outdated server, e.g. for + * the background check's notification — so it's clear whether anything is + * actually going to apply the update or it's waiting on the user. */ +export function describeUpdatePlans(updates: ServerUpdateInfo[]): string { + const now = updates.filter((u) => u.autoUpdatePlan.kind === "now").map((u) => u.name); + const manual = updates.filter((u) => u.autoUpdatePlan.kind === "manual").map((u) => u.name); + const timed = new Map(); + for (const u of updates) { + if (u.autoUpdatePlan.kind !== "at_time") continue; + timed.set(u.autoUpdatePlan.time, [...(timed.get(u.autoUpdatePlan.time) ?? []), u.name]); + } + const lines: string[] = []; + if (now.length > 0) lines.push(`Auto-updating now: ${now.join(", ")}.`); + for (const [time, names] of timed) lines.push(`Auto-update scheduled for ${time}: ${names.join(", ")}.`); + if (manual.length > 0) { + lines.push(`Auto-Update is off for ${manual.join(", ")} — use Update All on the dashboard to apply.`); + } + return lines.join("\n"); } export interface UpdateCheckSummary { @@ -129,6 +166,7 @@ export async function runPerServerUpdateCheck(silent = false): Promise newlyAvailable.includes(s.id)))}`; await dispatchNotification({ eventType: NOTIFICATION_EVENTS.UPDATE_AVAILABLE, @@ -244,7 +284,12 @@ export async function applyUpdateToServer( await tauriCmd.gracefulStopServer( serverId, rconPort, rconPassword, shutdownWarn.warnPlayers, shutdownWarn.warnMinutes, shutdownWarn.warnMessage, - ); + ).catch((e) => { + // The stop queues behind any backup/restart already running on this + // server — if that operation stopped it in the meantime, there's + // simply nothing left to stop. + if (!String(e).includes("is not running")) throw e; + }); } onStatusChange?.("Applying update…"); From 08cbcc7764ab85d287d2f01ff2d828c59d946742 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 23 Nov 2026 12:34:48 -0600 Subject: [PATCH 02/10] refactor: enhance directory handling for GE-Proton extraction --- src-tauri/src/commands/proton.rs | 38 +++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src-tauri/src/commands/proton.rs b/src-tauri/src/commands/proton.rs index 9e396c0..f3d8166 100644 --- a/src-tauri/src/commands/proton.rs +++ b/src-tauri/src/commands/proton.rs @@ -30,6 +30,16 @@ fn is_valid_proton_dir(p: &Path) -> bool { && (p.join("files/bin/wine64").exists() || p.join("files/bin/wine").exists()) } +/// Strip the architecture suffix newer GE-Proton archives append to the +/// extracted folder name (e.g. "GE-Proton11-14-x86_64" -> "GE-Proton11-14") +/// so it can be compared against the release tag. +fn strip_arch_suffix(name: &str) -> &str { + name.strip_suffix("-x86_64") + .or_else(|| name.strip_suffix("_x86_64")) + .or_else(|| name.strip_suffix("-x86-64")) + .unwrap_or(name) +} + fn emit_download_line(app: &AppHandle, msg: &str) { let _ = app.emit( "proton://output/download", @@ -250,7 +260,7 @@ async fn download_proton_ge_inner( let target_clone = target.clone(); let tag_clone = tag.clone(); let abort_extract = std::sync::Arc::clone(abort); - tokio::task::spawn_blocking(move || { + let dir_name = tokio::task::spawn_blocking(move || { use flate2::read::GzDecoder; use tar::Archive; @@ -258,6 +268,10 @@ async fn download_proton_ge_inner( // abort check — funnels through the same cleanup below instead of // leaving the downloaded archive (and any partially-extracted files) // behind on a genuine extraction error. + // Name of the archive's top-level directory. Older releases extract to + // "{tag}/", newer ones to "{tag}-x86_64/", so read it from the archive + // instead of assuming. + let mut top_dir: Option = None; let result: Result<(), String> = (|| { let f = std::fs::File::open(&tar_path_clone) .map_err(|e| format!("Failed to open archive: {e}"))?; @@ -271,12 +285,23 @@ async fn download_proton_ge_inner( return Err("Aborted".into()); } let mut entry = entry.map_err(|e| format!("Archive entry error: {e}"))?; + if top_dir.is_none() { + if let Ok(p) = entry.path() { + if let Some(std::path::Component::Normal(first)) = p + .components() + .find(|c| !matches!(c, std::path::Component::CurDir)) + { + top_dir = Some(first.to_string_lossy().into_owned()); + } + } + } entry .unpack_in(&target_clone) .map_err(|e| format!("Failed to extract entry: {e}"))?; } Ok(()) })(); + let dir_name = top_dir.unwrap_or_else(|| tag_clone.clone()); match &result { Ok(()) => { @@ -286,17 +311,17 @@ async fn download_proton_ge_inner( // Covers both "Aborted" and a genuine extraction error — // either way the archive and any partial extraction are junk. let _ = std::fs::remove_file(&tar_path_clone); - let _ = std::fs::remove_dir_all(target_clone.join(&tag_clone)); + let _ = std::fs::remove_dir_all(target_clone.join(&dir_name)); } } - result + result.map(|()| dir_name) }) .await .map_err(|e| format!("Extraction task error: {e}"))??; - let extracted_path = target.join(&tag); + let extracted_path = target.join(&dir_name); - if !extracted_path.exists() { + if !is_valid_proton_dir(&extracted_path) { return Err(format!( "Extraction finished but expected directory not found: {}", extracted_path.display() @@ -362,7 +387,8 @@ pub async fn check_proton_ge_update(current_path: String) -> Result Date: Mon, 23 Nov 2026 13:20:46 -0600 Subject: [PATCH 03/10] feat: add Message of the Day feature with duration control in ConfigTab --- .../layout/ModBrowserEventHandler.tsx | 1 + src/components/server/tabs/ConfigTab.tsx | 92 ++++++++++++- .../wizard/ServerCreationWizard.tsx | 127 +++++++++++++----- 3 files changed, 182 insertions(+), 38 deletions(-) diff --git a/src/components/layout/ModBrowserEventHandler.tsx b/src/components/layout/ModBrowserEventHandler.tsx index e182c25..075bc43 100644 --- a/src/components/layout/ModBrowserEventHandler.tsx +++ b/src/components/layout/ModBrowserEventHandler.tsx @@ -46,6 +46,7 @@ export function ModBrowserEventHandler() { // The wizard's ModsStep listens for this event directly and updates its own state. if (data.serverId === "wizard-temp") { incrementModAddedCount(); + if (data.source === "verify") incrementVerifyProgress(); return; } diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index c559ba3..bcd54e8 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -6,7 +6,7 @@ import { useSavedFlash } from "@/hooks/useSavedFlash"; import { Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight, Settings2, X, ToggleLeft, ToggleRight, Terminal, - HelpCircle, Upload, FileText, Clipboard, Wand2, Sparkles, Package, + HelpCircle, Upload, FileText, Clipboard, Wand2, Sparkles, Package, MessageSquare, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -978,6 +978,81 @@ function ActiveEventCard({ server }: { server: ServerRow }) { ); } +// --------------------------------------------------------------------------- +// Message of the Day card +// --------------------------------------------------------------------------- + +const MOTD_SECTION = "MessageOfTheDay"; +const MOTD_DEFAULT_DURATION = 20; + +function MotdCard({ + config, + onChange, +}: { + config: ServerConfigJson; + onChange: (updated: ServerConfigJson) => void; +}) { + const gus = config.gameUserSettings as Record>; + const message = gus?.[MOTD_SECTION]?.Message ?? ""; + const parsedDuration = parseInt(gus?.[MOTD_SECTION]?.Duration ?? "", 10); + const duration = isNaN(parsedDuration) ? MOTD_DEFAULT_DURATION : parsedDuration; + + const commit = (nextMessage: string, nextDuration: number) => { + const updated = { ...gus }; + // An empty message disables the MOTD — drop the section entirely, + // matching what the creation wizard writes. + if (nextMessage.trim()) { + updated[MOTD_SECTION] = { ...(gus?.[MOTD_SECTION] ?? {}), Message: nextMessage, Duration: String(nextDuration) }; + } else { + delete updated[MOTD_SECTION]; + } + onChange({ ...config, gameUserSettings: updated }); + }; + + return ( +
+
+ +
+

Message of the Day

+

+ Shown to players in a pop-up when they join. Single line only — leave blank to disable. +

+
+
+
+ commit(e.target.value.replace(/[\r\n]+/g, " "), duration)} + placeholder="Welcome to the server!" + className="h-8 text-sm flex-1 min-w-48" + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+ +
+ commit(message, v)} + min={1} + max={120} + step={1} + defaultValue={MOTD_DEFAULT_DURATION} + /> +
+ seconds +
+
+
+ ); +} + /** * Shared shape behind Shutdown/Restart/Update Warning cards — previously * three independent ~90-line copies differing only in which @@ -1774,9 +1849,11 @@ export function ConfigTab({ server }: Props) { - {/* INI Field Groups — Active Event slots in right after Session, since - it's session-scoped state (like the map/name/password above it) - even though it isn't an INI field. */} + {/* INI Field Groups — Active Event and MOTD slot in right after Session, since + they're session-scoped state (like the map/name/password above it). + Active Event isn't an INI field; MOTD gets its own card because it + lives in a separate [MessageOfTheDay] section and needs a paired + message + duration control. */} {INI_FIELD_GROUPS.map((g, idx) => ( - {g.id === "session" && } + {g.id === "session" && ( + <> + + { setConfig(updated); setIsDirty(true); }} /> + + )} ))} diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index 0beceac..6b742c1 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -37,7 +37,7 @@ import { LokiIcon } from "@/components/shared/LokiIcon"; import { useAllMaps } from "@/hooks/useAllMaps"; import { GAME_MODES, PRESET_STYLES, INI_FIELD_GROUPS, buildPresetConfig, - LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, ARK_EVENTS, + LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, ARK_EVENTS, ARK_EVENT_MOD_IDS, type ArkMap, type GameModeConfig, type PresetStyle, type LaunchParameter, type ArkEvent, } from "@/data/game-data"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; @@ -788,28 +788,23 @@ function BasicInfoStep({ - Shown to players in a pop-up when they join. Leave blank to disable. Use \n for line breaks. + Shown to players in a pop-up when they join. Leave blank to disable. Single line only — ASA does not support line breaks. -