Stabilize server lifecycle, client settings and release qualification

This commit is contained in:
Дмитрий committed 2026-10-30 14:04:18 +05:00
1 parent 4d1a6e0b21
commit 30d2f56997
71 files changed
+2785 -168

No files matched your search

+4 -1
View File
@@ -11,10 +11,11 @@ const stubs = {
"@/lib/api": `export const api={}; export const asUiError=e=>e;`,
"@/lib/utils": `export const cn=(...s)=>s.filter(Boolean).join(' '); export const formatBytes=String; export const formatUptime=String;`,
"@/i18n": `export const useT=()=>k=>k; export const useHuman=()=>h=>h;`,
"@/lib/serverUpdate": `export const applyServerUpdate=async()=>false; export const useServerUpdate=()=>globalThis.__overviewUpdate;`,
"@/lib/serverUpdate": `export const serverUpdateBlocksRestart=()=>false; export const applyServerUpdate=async()=>false; export const useServerUpdate=()=>globalThis.__overviewUpdate;`,
"@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`,
"@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`,
"@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`,
"./ForceStopDialog": `export const ForceStopDialog=()=>null;`,
"@/screens/PublishCard": `export const ListingChip=()=>null;`,
"@/screens/PublishDialog": `export const PublishRealmDialog=()=>null;`,
"@/lib/registry": `export const useRegistryStatus=()=>({status:null});`,
@@ -28,6 +29,8 @@ const bundle = await rolldown({
external: (id, importer) => id === "react/jsx-runtime" || id === "lucide-react" || (id === "react" && !importer?.endsWith("Overview.tsx")),
plugins: [{ name: "overview-test",
resolveId(id, importer) {
if (id === "./ForceStopDialog") return "\0" + id;
if (id === "@/lib/serverLifecycle") return fileURLToPath(new URL("../src/lib/serverLifecycle.ts", import.meta.url));
if (id === "@/components/ui/split-button") return fileURLToPath(new URL("../src/components/ui/split-button.tsx", import.meta.url));
if (id.startsWith("@/") || (id === "react" && importer?.endsWith("Overview.tsx"))) return "\0" + id;
},
+62
View File
@@ -0,0 +1,62 @@
import assert from "node:assert/strict";
import test from "node:test";
import { registerHooks } from "node:module";
let handler;
let enabled = true;
let closeToTray = false;
let nextUpdate = null;
const calls = [];
globalThis.__closeTest = {
invoke: async (cmd, args) => { calls.push([cmd, args]); return cmd === "close_to_tray" ? closeToTray : undefined; },
window: { onCloseRequested: async cb => { handler = cb; return () => { handler = null; }; } },
check: async () => nextUpdate,
};
globalThis.localStorage = { getItem: () => enabled ? "on" : "off", setItem() {} };
registerHooks({ resolve(id, context, next) {
const stubs = {
react: "export const useSyncExternalStore=(subscribe,read)=>read();",
"@tauri-apps/api/core": "export const invoke=(...a)=>globalThis.__closeTest.invoke(...a);",
"@tauri-apps/api/window": "export const getCurrentWindow=()=>globalThis.__closeTest.window;",
"@tauri-apps/plugin-updater": "export const check=()=>globalThis.__closeTest.check();",
"@tauri-apps/plugin-process": "export const relaunch=async()=>{};",
};
if (id in stubs) return { shortCircuit:true, url:"data:text/javascript,"+encodeURIComponent(stubs[id]) };
return next(id, context);
}});
const { installOnClose, lookForUpdate } = await import("../src/lib/selfUpdate.ts");
async function close() {
const stop = installOnClose();
await Promise.resolve();
let prevented = false;
await handler({ preventDefault() { prevented = true; } });
assert.equal(prevented, true, "Tauri must never auto-destroy the hidden main window");
stop();
}
test("ordinary close delegates to native preferences without destroying the window", async () => {
calls.length = 0;
await close();
assert.deepEqual(calls, [["close_manager", undefined]]);
});
test("a cached update with automatic updates off still uses native close preferences", async () => {
nextUpdate = { version:"99", download:async()=>{}, install:async()=>{throw new Error("should not install")} };
await lookForUpdate({download:true});
enabled=false;calls.length=0;
await close();
assert.deepEqual(calls, [["close_manager", undefined]]);
});
test("failed automatic installation releases exit mode and preserves ordinary close handling", async () => {
enabled=true;calls.length=0;
await close();
assert.deepEqual(calls, [["close_to_tray",undefined],["manager_installing",{enabled:true}],["manager_installing",{enabled:false}],["close_manager",undefined]]);
});
test("minimizing to tray never starts a cached automatic installation", async () => {
await lookForUpdate({download:true});
closeToTray=true;calls.length=0;
await close();
assert.deepEqual(calls, [["close_to_tray",undefined],["close_manager",undefined]]);
});
+64
View File
@@ -0,0 +1,64 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ServerLifecycle, serverLifecycle } from "../src/lib/serverLifecycle.ts";
test("polls during a slow deliberate stop never rearm crash restart", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
state.request("stopping");
for (let i = 0; i < 50; i++) assert.equal(state.observe(true, true, false), false);
assert.equal(state.observe(false, false, false), false);
assert.equal(state.observe(false, false, false), false);
state.request("starting");
state.complete("starting");
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
assert.equal(state.observe(false, false, false), false);
});
test("update validation and rollback shutdowns are not crashes", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
assert.equal(state.observe(false, false, true), false);
assert.equal(state.observe(false, false, false), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, true), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
});
test("navigation retains a pending stop and a later external start rearms detection", () => {
const state = serverLifecycle("navigation");
state.observe(true, false, false);
state.request("stopping");
const returned = serverLifecycle("navigation");
assert.equal(returned, state);
assert.equal(returned.observe(false, false, false), false);
returned.complete("stopping");
assert.equal(returned.observe(false, false, false), false);
returned.observe(true, false, false);
assert.equal(returned.observe(false, false, false), true);
});
test("an update between status polls cannot look like a crash after completion", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
state.beginMaintenance();
state.endMaintenance();
assert.equal(state.observe(false, false, false), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
});
test("an intentional restart remains suppressed across navigation until the action completes", () => {
const state = serverLifecycle("restart-navigation");
state.observe(true, false, false);
state.request("restarting");
const returned = serverLifecycle("restart-navigation");
assert.equal(returned.observe(false, false, false), false);
assert.equal(returned.observe(true, false, false), false);
returned.complete("restarting");
returned.observe(true, false, false);
assert.equal(returned.observe(false, false, false), true);
});
+1
View File
@@ -16,6 +16,7 @@ globalThis.__hotfixApi = {
};
registerHooks({ resolve(specifier, context, next) {
if (specifier === "react") return { shortCircuit: true, url: "data:text/javascript,export const useSyncExternalStore=(subscribe,getSnapshot)=>getSnapshot();export const useState=()=>{throw new Error('React state is not used in this test');};" };
if (specifier === "@/lib/serverLifecycle") return { shortCircuit: true, url: new URL("../src/lib/serverLifecycle.ts", import.meta.url).href };
if (specifier === "@/lib/api") return { shortCircuit: true, url: "data:text/javascript,export const api=globalThis.__hotfixApi;export const asUiError=e=>({human:{code:'unknown'},technical:e.message});" };
if (specifier === "@tauri-apps/api/event") return { shortCircuit: true, url: "data:text/javascript,export const listen=async()=>()=>{};" };
if (specifier === "./serverUpdateStatus" && context.parentURL?.endsWith("/serverUpdate.ts")) return { shortCircuit: true, url: new URL("../src/lib/serverUpdateStatus.ts", import.meta.url).href };
+52
View File
@@ -64,6 +64,21 @@ def stop_all(config):
result = self.launch('stop-all', self.shutdown_fixture(console_error=error))
self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown'])
def test_force_stop_terminates_only_the_owned_world_before_mysql(self):
body = self.shutdown_fixture(console_error=None)
body = body.replace("return world if name == 'world' else None", "return world if name == 'world' and 'terminate' not in calls else None")
result = self.launch('force-stop-all', body)
self.assertEqual(result['launcher']['calls'], ['terminate', 'wait', 'mysql-shutdown'])
def test_force_stop_rejects_foreign_or_reused_pids_and_a_world_that_stays_alive(self):
for options, message in [({'foreign': True}, 'ownership could not be verified'),
({'same': False}, 'ownership could not be verified'),
({'stopped': False}, 'database was left running')]:
with self.subTest(options=options):
with self.assertRaisesRegex(Exception, message):
self.launch('force-stop-all', self.shutdown_fixture(**options))
self.assertNotIn('mysql-shutdown', self.launcher['calls'])
def test_healthy_console_keeps_graceful_shutdown(self):
result = self.launch('stop-all', self.shutdown_fixture(console_error=None))
self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown'])
@@ -128,6 +143,9 @@ def wait_ready(name, port, seconds=180):
time.sleep(0.5)
raise RuntimeError('world is still starting')
def start_mysql(): pass
def settings(): return {{}}
def process(name): return {{'pid': 1}}
def ra(command, config): return 'server info ready'
def main():
wait_ready('world', 1, {requested})
wait_ready('world', 2, {requested})
@@ -136,6 +154,40 @@ def main():
result = self.launch('start-all', body)
return clock[0], result['launcher']['calls']
def test_open_ports_do_not_finish_startup_until_commands_are_processed(self):
clock = [0.0]
def sleep(seconds): clock[0] += seconds
body = """
import time
calls=[]
def wait_ready(*args): pass
def start_mysql(): pass
def settings(): return {}
def process(name): return {'pid': 1}
def ra(command, config):
calls.append(command)
if time.monotonic() < 5: raise TimeoutError('main loop is loading')
return 'ready'
def main():
wait_ready('world',1)
wait_ready('world',2)
"""
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
result=self.launch('start-all',body)
self.assertEqual(clock[0],5)
self.assertEqual(set(result['launcher']['calls']),{'server info'})
def test_world_death_after_ports_open_is_a_startup_failure(self):
body="""
def wait_ready(*args): pass
def start_mysql(): pass
def settings(): return {}
def process(name): return None
def main(): pass
"""
with self.assertRaisesRegex(RuntimeError,'stopped before its console accepted'):
self.launch('start-world',body)
def test_legacy_coa_world_waits_for_both_ports_after_three_minutes(self):
elapsed, calls = self.world_start()
self.assertEqual((elapsed, calls), (480, [1, 2]))