okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split into f-split-s6326e39118

main
5.7 KiB97 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { spawn } from 'node:child_process';
4import { mkdtemp, rm } from 'node:fs/promises';
5import { tmpdir } from 'node:os';
6import { join } from 'node:path';
7import { createServer } from 'node:net';
8import { fileURLToPath } from 'node:url';
9import { createControl } from '../server/control-runtime.mjs';
10
11/**
12 * The host's side of "closing always ends what this app started":
13 *  - it asks Control to tie each engine's life to the host's own (--die-with-pid),
14 *  - it takes every ordinary stop signal down the clean path,
15 *  - started by the desktop shell, it leaves when the shell is gone (a kill or a crash is not announced).
16 * The owner runtime's side (the engine ends when the host's pid is gone) is tested in tests/terminal.
17 */
18const root = fileURLToPath(new URL('..', import.meta.url));
19const delay = ms => new Promise(r => setTimeout(r, ms));
20async function freePort() { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
21const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
22async function until(fn, ms = 15000) { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await delay(100); } return false; }
23
24test('start asks Control to end the engine with this host; cleanup asks it to end what a lost owner left', async () => {
25  const seen = [];
26  const control = createControl({
27    control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } },
28    run: async args => { seen.push(args.join(' ')); return { code: 0, json: { ok: true }, text: '', stderr: '' }; },
29  });
30  await control.start('app-1');
31  await control.start('app-2', { dieWithPid: 4242 });
32  await control.start('app-3', { dieWithPid: null });
33  await control.cleanup();
34  assert.deepEqual(seen, [
35    `runtime start --profile app-1 --wait 300 --shutdown-timeout 15 --die-with-pid ${process.pid} --output json`,
36    'runtime start --profile app-2 --wait 300 --shutdown-timeout 15 --die-with-pid 4242 --output json',
37    'runtime start --profile app-3 --wait 300 --shutdown-timeout 15 --output json',
38    'runtime cleanup --output json',
39  ]);
40});
41
42async function startHost(extraEnv = {}, spawnOptions = {}) {
43  const home = await mkdtemp(join(tmpdir(), 'strata-host-life-'));
44  const port = await freePort();
45  const host = spawn(process.execPath, ['server/index.mjs'], {
46    cwd: root, stdio: 'ignore', ...spawnOptions,
47    env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1', ...extraEnv },
48  });
49  let up = false;
50  for (let i = 0; i < 120 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }
51  assert.ok(up, 'host started');
52  return { host, port, home, done: () => rm(home, { recursive: true, force: true }) };
53}
54
55test('SIGTERM and SIGHUP end the host through the clean shutdown (exit 0)', { skip: process.platform === 'win32' && 'Windows has no SIGTERM/SIGHUP to send' }, async t => {
56  for (const signal of ['SIGTERM', 'SIGHUP']) {
57    const h = await startHost();
58    t.after(h.done);
59    const exited = new Promise(r => h.host.once('exit', (code, sig) => r({ code, sig })));
60    h.host.kill(signal);
61    const result = await Promise.race([exited, delay(20000).then(() => 'timeout')]);
62    assert.notEqual(result, 'timeout', `${signal}: the host did not end`);
63    assert.deepEqual(result, { code: 0, sig: null }, signal);
64  }
65});
66
67test('Started by the shell (STRATA_EXIT_WITH_PARENT=1), the host leaves when its parent is killed', async t => {
68  // a stand-in shell: it starts the host and then waits to be killed hard
69  const home = await mkdtemp(join(tmpdir(), 'strata-host-parent-'));
70  t.after(() => rm(home, { recursive: true, force: true }));
71  const port = await freePort();
72  const shell = spawn(process.execPath, ['-e', `
73    const {spawn}=require('node:child_process');
74    const h=spawn(process.execPath,['server/index.mjs'],{cwd:${JSON.stringify(root)},stdio:'ignore',env:{...process.env,STRATA_EXIT_WITH_PARENT:'1',STRATA_HOME:${JSON.stringify(home)},STRATA_MODELS_DIR:${JSON.stringify(join(home, 'models'))},STRATA_PORT:'${port}',STRATA_SHARE_PORT:'${await freePort()}',STRATA_TUNNEL_PORT:'${await freePort()}',STRATA_REAL_ENGINE:'1'}});
75    console.log(h.pid);
76    setInterval(()=>{},1000);
77  `], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'] });
78  const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim()))));
79  t.after(() => { try { process.kill(hostPid, 'SIGKILL'); } catch { /* gone */ } shell.kill('SIGKILL'); });
80  let up = false;
81  for (let i = 0; i < 120 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }
82  assert.ok(up, 'host started');
83  assert.ok(alive(hostPid));
84  shell.kill('SIGKILL');                         // TerminateProcess on Windows: nothing is announced
85  assert.ok(await until(() => !alive(hostPid), 20000), 'the host outlived its killed shell');
86  let reachable = true;
87  try { await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) }); } catch { reachable = false; }
88  assert.equal(reachable, false, 'the port is free again');
89});
90
91test('Without STRATA_EXIT_WITH_PARENT a host started from a source checkout does not follow its parent', async t => {
92  const h = await startHost();
93  t.after(h.done);
94  t.after(() => h.host.kill('SIGKILL'));
95  await delay(2500);
96  assert.equal(alive(h.host.pid), true);
97});