Harden server update history, recovery guards and repeated checks

This commit is contained in:
Дмитрий committed 2026-10-06 07:01:13 +05:00
1 parent 3940506987
commit 0d6d8a0db8
37 files changed
+1112 -99

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ export {};
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,download_bytes:6000000};
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};}
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
+1
View File
@@ -270,6 +270,7 @@ export interface UpdatePreview {
items: UpdatePlanItem[];
conflicts: string[];
migrations: number;
pending_migrations?: number;
download_bytes: number;
}
+26 -5
View File
@@ -1,6 +1,7 @@
import { useSyncExternalStore } from "react";
import { listen } from "@tauri-apps/api/event";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { isUpdateCurrent } from "./serverUpdateStatus";
/**
* Server update status for the main screen and the navigation: checked when the app starts and every five minutes,
@@ -16,11 +17,13 @@ export interface ServerUpdateState {
error: string | null;
/** The full error of the last update attempt, for the Settings card. */
uiError: UiError | null;
stateError: UiError | null;
stateRevision: number;
/** How the last update ended; kept here so the Settings card can show it after the user left and came back. */
result: { committed: string } | { pending: UpdateTxn } | null;
}
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, result: null };
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, stateError: null, stateRevision: 0, result: null };
const states = new Map<string, ServerUpdateState>();
const listeners = new Set<() => void>();
export const CHECK_EVERY_MS = 5 * 60 * 1000;
@@ -37,10 +40,10 @@ export async function checkServerUpdate(id: string): Promise<void> {
set(id, { checking: true });
try {
const p = await api.checkUpdate(id);
set(id, { preview: p, available: p.to_version !== (p.from_version ?? ""), error: null });
set(id, { preview: p, available: !isUpdateCurrent(p), error: null });
} catch (e) {
// offline or no package published: keep what we knew and stay quiet
set(id, { error: asUiError(e).human.code });
// A cached offer is no longer safe after an update or failed recheck.
set(id, { preview: null, available: false, error: asUiError(e).human.code });
} finally {
set(id, { checking: false });
}
@@ -57,6 +60,20 @@ export function clearServerUpdateResult(id: string) {
set(id, { result: null, uiError: null });
}
export async function refreshServerUpdateState(id: string): Promise<UpdateTxn | null> {
try {
const pending = await api.pendingUpdate(id);
const current = get(id).result;
set(id, { stateError: null, stateRevision: get(id).stateRevision + 1,
...(pending ? { available: false, preview: null } : {}),
result: pending ? { pending } : current && "committed" in current ? current : null });
return pending;
} catch (e) {
set(id, { stateError: asUiError(e), stateRevision: get(id).stateRevision + 1, available: false, preview: null });
throw e;
}
}
/**
* Apply an update. Without options this is the main-screen button: the pending update, only when no file needs a
* decision. With options (the Settings card) the owner has already chosen what to do with each changed file and may
@@ -65,7 +82,8 @@ export function clearServerUpdateResult(id: string) {
*/
export async function applyServerUpdate(id: string, opts?: { choices: Record<string, "keep" | "replace">; source?: string }): Promise<boolean> {
const p = get(id).preview;
if (get(id).applying) return false;
const current = get(id);
if (current.applying || current.stateError || (current.result && "pending" in current.result)) return false;
if (!opts && (!p || p.conflicts.length > 0)) return false;
set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null });
let un: (() => void) | undefined;
@@ -84,6 +102,9 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
return false;
} finally {
un?.();
try {
await refreshServerUpdateState(id);
} catch { /* The state error remains visible and prevents another apply. */ }
set(id, { applying: false });
void checkServerUpdate(id);
}
+7
View File
@@ -0,0 +1,7 @@
import type { UpdatePreview } from "./api";
export function isUpdateCurrent(preview: UpdatePreview): boolean {
return preview.from_version === preview.to_version
&& preview.items.every((item) => item.action === "skip")
&& (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0;
}
+45 -16
View File
@@ -1,7 +1,8 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
import { applyServerUpdate, clearServerUpdateResult, useServerUpdate } from "@/lib/serverUpdate";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -23,12 +24,14 @@ export function SettingsHome({ serverId }: { serverId: string }) {
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(null);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
const error = localError ?? upd.uiError;
const error = pendingStateError ?? localError ?? upd.uiError;
const [localDone, setDone] = useState<string | null>(null);
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>({});
@@ -36,16 +39,36 @@ export function SettingsHome({ serverId }: { serverId: string }) {
const [source, setSource] = useState("");
useEffect(() => {
void api.pendingUpdate(serverId).then(setPending).catch(() => {});
let active = true;
setPendingChecked(false);
setPending(null);
setPreview(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// the update finished (possibly while another tab was open): drop the stale preview, show what is left to decide
// Every finished attempt refreshes the disk state, including failures in the background.
useEffect(() => {
if (!upd.result) return;
if (!upd.stateRevision) return;
setPreview(null);
if ("pending" in upd.result) setPending(upd.result.pending);
else void api.pendingUpdate(serverId).then(setPending).catch(() => {});
}, [upd.result, serverId]);
setPendingChecked(!upd.stateError);
setPendingStateError(upd.stateError);
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
}, [upd.stateRevision, serverId]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
}
async function check() {
setBusy("check");
@@ -54,6 +77,8 @@ export function SettingsHome({ serverId }: { serverId: string }) {
clearServerUpdateResult(serverId);
setPreview(null);
try {
const txn = await refreshPending();
if (txn) return;
const p = await api.checkUpdate(serverId, source.trim() || undefined);
setPreview(p);
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
@@ -65,6 +90,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
@@ -81,6 +107,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
@@ -97,7 +124,10 @@ export function SettingsHome({ serverId }: { serverId: string }) {
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally { setBusy(null); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
@@ -165,28 +195,27 @@ export function SettingsHome({ serverId }: { serverId: string }) {
</div>
)}
{done && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<p className="mt-4 text-sm text-bad" role="alert">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
)}
{preview && preview.from_version === preview.to_version && preview.items.every((i) => i.action === "skip") && (
// The same version with no file to change: the database scripts of this package are all in the ledger already.
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !(preview.from_version === preview.to_version && preview.items.every((i) => i.action === "skip")) && (
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
<p className="mt-1 text-sm text-muted">
{preview.migrations > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.migrations })
{(preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
@@ -211,7 +240,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
</li>
))}
</ul>
<Button className="mt-4" variant="primary" disabled={!!busy} onClick={() => void update()}>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>