lifecycle.test.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /**
  2. * Tests for the brainstorm server's lifecycle (idle timeout + shutdown).
  3. *
  4. * - The idle timeout is configurable (default 4h) and reported in server-info.
  5. * - Idle shutdown must close any open WebSocket so the process actually exits,
  6. * not hang on a lingering connection.
  7. * - start-server.sh exposes the timeout via --idle-timeout-minutes.
  8. *
  9. * Uses the `ws` npm package as a test client (test-only dependency).
  10. */
  11. const { spawn, execFileSync } = require('child_process');
  12. const WebSocket = require('ws');
  13. const fs = require('fs');
  14. const path = require('path');
  15. const assert = require('assert');
  16. const SERVER = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
  17. const START = path.join(__dirname, '../../skills/brainstorming/scripts/start-server.sh');
  18. const STOP = path.join(__dirname, '../../skills/brainstorming/scripts/stop-server.sh');
  19. const sleep = ms => new Promise(r => setTimeout(r, ms));
  20. function firstServerStarted(out) {
  21. return JSON.parse(out.trim().split('\n').find(l => l.includes('server-started')));
  22. }
  23. async function runTests() {
  24. let passed = 0, failed = 0;
  25. async function test(name, fn) {
  26. try { await fn(); console.log(` PASS: ${name}`); passed++; }
  27. catch (e) { console.log(` FAIL: ${name}`); console.log(` ${e.message}`); failed++; }
  28. }
  29. await test('server-info reports the configured idle_timeout_ms', async () => {
  30. const dir = fs.mkdtempSync('/tmp/bs-life-');
  31. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3401, BRAINSTORM_DIR: dir, BRAINSTORM_IDLE_TIMEOUT_MS: 1234567 } });
  32. let out = ''; srv.stdout.on('data', d => out += d.toString());
  33. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  34. try {
  35. const info = firstServerStarted(out);
  36. assert.strictEqual(info.idle_timeout_ms, 1234567, 'idle_timeout_ms should reflect the env override');
  37. } finally {
  38. srv.kill(); await sleep(100); fs.rmSync(dir, { recursive: true, force: true });
  39. }
  40. });
  41. await test('idle shutdown closes an open WebSocket and the process exits', async () => {
  42. const dir = fs.mkdtempSync('/tmp/bs-life-');
  43. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3402, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'lifetoken', BRAINSTORM_IDLE_TIMEOUT_MS: 200, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
  44. let out = ''; srv.stdout.on('data', d => out += d.toString());
  45. let exited = false, code = null; srv.on('exit', c => { exited = true; code = c; });
  46. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  47. const ws = new WebSocket('ws://localhost:3402/?key=lifetoken');
  48. await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); });
  49. // 200ms idle, checked every 100ms — should shut down and exit well within 4s,
  50. // *despite* the open WS, only if shutdown() closes client sockets.
  51. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  52. try {
  53. assert(exited, 'process must exit after idle shutdown even with an open WebSocket');
  54. assert.strictEqual(code, 0, 'should exit cleanly (0)');
  55. assert(fs.existsSync(path.join(dir, 'state', 'server-stopped')), 'should write server-stopped');
  56. } finally {
  57. try { ws.close(); } catch (e) {}
  58. if (!exited) srv.kill();
  59. fs.rmSync(dir, { recursive: true, force: true });
  60. }
  61. });
  62. await test('start-server.sh --idle-timeout-minutes sets the timeout', async () => {
  63. const dir = fs.mkdtempSync('/tmp/bs-life-');
  64. let info;
  65. const out = execFileSync('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5'], { encoding: 'utf8' });
  66. info = firstServerStarted(out);
  67. try {
  68. assert.strictEqual(info.idle_timeout_ms, 5 * 60 * 1000, '5 minutes -> 300000 ms');
  69. } finally {
  70. execFileSync('bash', [STOP, path.dirname(info.state_dir)], { stdio: 'ignore' });
  71. fs.rmSync(dir, { recursive: true, force: true });
  72. }
  73. });
  74. await test('persists the bound port AND key, and restores both on restart', async () => {
  75. const dir = fs.mkdtempSync('/tmp/bs-port-');
  76. const portFile = path.join(dir, '.last-port');
  77. const tokenFile = path.join(dir, '.last-token');
  78. const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
  79. const a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
  80. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  81. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  82. const infoA = firstServerStarted(outA);
  83. const keyA = new URL(infoA.url).searchParams.get('key');
  84. assert(fs.existsSync(portFile) && fs.existsSync(tokenFile), 'should write the port and token files');
  85. a.kill(); await sleep(400); // free the port
  86. const b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
  87. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  88. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  89. const infoB = firstServerStarted(outB);
  90. const keyB = new URL(infoB.url).searchParams.get('key');
  91. b.kill(); await sleep(100); fs.rmSync(dir, { recursive: true, force: true });
  92. assert.strictEqual(infoB.port, infoA.port, 'restart should reuse the same port');
  93. // Same key too — otherwise the open tab's cookie would 403 against the restart.
  94. assert.strictEqual(keyB, keyA, 'restart should reuse the same session key');
  95. });
  96. await test('falls back to a random port when the preferred port is taken', async () => {
  97. const dir = fs.mkdtempSync('/tmp/bs-port-');
  98. const portFile = path.join(dir, '.last-port');
  99. const a = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'a'), BRAINSTORM_PORT: 3415, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  100. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  101. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  102. fs.writeFileSync(portFile, '3415'); // preferred port, but it's taken by A
  103. const b = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'b'), BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  104. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  105. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  106. const portB = firstServerStarted(outB).port;
  107. const persisted = fs.readFileSync(portFile, 'utf8').trim();
  108. a.kill(); b.kill(); await sleep(100); fs.rmSync(dir, { recursive: true, force: true });
  109. assert.notStrictEqual(portB, 3415, 'must not bind the already-taken port');
  110. assert(portB >= 49152, 'should fall back to a random high port');
  111. // The fallback must NOT clobber the shared port file — A still owns 3415 and
  112. // its open tab must keep reconnecting there.
  113. assert.strictEqual(persisted, '3415', 'fallback must not overwrite .last-port');
  114. });
  115. await test('auto-opens the browser once, on the first screen', async () => {
  116. const dir = fs.mkdtempSync('/tmp/bs-open-');
  117. const marker = path.join(dir, 'opened.log');
  118. const openCmd = `sh -c 'echo "$0" >> ${marker}'`; // capture the launch instead of opening a browser
  119. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3417, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN: '1', BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  120. let out = ''; srv.stdout.on('data', d => out += d.toString());
  121. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  122. // First screen, with no browser connected -> should auto-open.
  123. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  124. await sleep(700);
  125. // Second screen -> must NOT open again.
  126. fs.writeFileSync(path.join(dir, 'content', 'second.html'), '<h2>Second</h2>');
  127. await sleep(700);
  128. const lines = fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').trim().split('\n').filter(Boolean) : [];
  129. // The opened URL must carry the key AND be reachable — a keyless URL hits 403.
  130. let status = 0;
  131. if (lines[0]) {
  132. status = await new Promise(r => require('http').get(lines[0], res => { res.resume(); r(res.statusCode); }).on('error', () => r(0)));
  133. }
  134. srv.kill(); await sleep(100);
  135. fs.rmSync(dir, { recursive: true, force: true });
  136. assert.strictEqual(lines.length, 1, 'should open exactly once');
  137. assert(lines[0].includes('3417'), `should open the server URL, got: ${lines[0]}`);
  138. assert(/[?&]key=/.test(lines[0]), `opened URL must carry the session key, got: ${lines[0]}`);
  139. assert.strictEqual(status, 200, 'the opened URL must be reachable (valid key), not the 403 page');
  140. });
  141. await test('does NOT auto-open unless approved (BRAINSTORM_OPEN unset)', async () => {
  142. const dir = fs.mkdtempSync('/tmp/bs-open-');
  143. const marker = path.join(dir, 'opened.log');
  144. const openCmd = `sh -c 'echo "$0" >> ${marker}'`;
  145. // BRAINSTORM_OPEN intentionally NOT set — auto-open must stay off.
  146. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3418, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  147. let out = ''; srv.stdout.on('data', d => out += d.toString());
  148. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  149. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  150. await sleep(700);
  151. srv.kill(); await sleep(100);
  152. const opened = fs.existsSync(marker);
  153. fs.rmSync(dir, { recursive: true, force: true });
  154. assert(!opened, 'must not open the browser without explicit approval');
  155. });
  156. await test('unauthenticated requests do not defeat the idle timeout', async () => {
  157. const dir = fs.mkdtempSync('/tmp/bs-life-');
  158. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3419, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'authtok', BRAINSTORM_IDLE_TIMEOUT_MS: 400, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
  159. let out = ''; srv.stdout.on('data', d => out += d.toString());
  160. let exited = false; srv.on('exit', () => { exited = true; });
  161. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  162. // Flood with UNAUTHENTICATED (keyless → 403) requests. These must NOT count
  163. // as activity, so the idle timeout still fires and the process exits.
  164. const hammer = setInterval(() => { require('http').get('http://localhost:3419/', r => r.resume()).on('error', () => {}); }, 60);
  165. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  166. clearInterval(hammer);
  167. if (!exited) srv.kill();
  168. fs.rmSync(dir, { recursive: true, force: true });
  169. assert(exited, 'idle shutdown must still fire despite a flood of unauthenticated requests');
  170. });
  171. console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  172. if (failed > 0) process.exit(1);
  173. }
  174. runTests().catch(err => { console.error('Test failed:', err); process.exit(1); });