|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const { spawn } = require('child_process'); |
| 4 | +const http = require('http'); |
| 5 | + |
| 6 | +const DEFAULT_PORT = Number(process.env.DEMO_PORT || 4173); |
| 7 | +const MAX_PORT = Number(process.env.DEMO_PORT_MAX || DEFAULT_PORT + 20); |
| 8 | +const HOST = process.env.DEMO_HOST || '127.0.0.1'; |
| 9 | +const MARKER = process.env.DEMO_MARKER || 'InkJS Smoke Demo'; |
| 10 | + |
| 11 | +const OCCUPIED_ERROR = 'occupied'; |
| 12 | + |
| 13 | +function wait(ms) { |
| 14 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 15 | +} |
| 16 | + |
| 17 | +function probeDemoServer(port, { host = HOST, marker = MARKER } = {}) { |
| 18 | + return new Promise((resolve) => { |
| 19 | + const req = http.get({ host, port, path: '/demo/', timeout: 1500 }, (res) => { |
| 20 | + let body = ''; |
| 21 | + res.on('data', (chunk) => { body += chunk.toString(); }); |
| 22 | + res.on('end', () => { |
| 23 | + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 400 && body.includes(marker)) { |
| 24 | + resolve({ status: 'demo' }); |
| 25 | + } else { |
| 26 | + resolve({ status: OCCUPIED_ERROR, reason: `Unexpected response code ${res.statusCode}` }); |
| 27 | + } |
| 28 | + }); |
| 29 | + }); |
| 30 | + req.on('timeout', () => { |
| 31 | + req.destroy(new Error('timeout')); |
| 32 | + }); |
| 33 | + req.on('error', (err) => { |
| 34 | + if (['ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'ENOTFOUND', 'ETIMEDOUT'].includes(err.code)) { |
| 35 | + resolve({ status: 'free' }); |
| 36 | + } else { |
| 37 | + resolve({ status: OCCUPIED_ERROR, reason: err.message }); |
| 38 | + } |
| 39 | + }); |
| 40 | + }); |
| 41 | +} |
| 42 | + |
| 43 | +async function findFreePort(start, end) { |
| 44 | + for (let port = start; port <= end; port += 1) { |
| 45 | + const probe = await probeDemoServer(port); |
| 46 | + if (probe.status === 'free') return port; |
| 47 | + if (probe.status === OCCUPIED_ERROR && port === start) throw new Error(`Port ${start} is in use by a non-demo process.`); |
| 48 | + } |
| 49 | + throw new Error(`No free port found in range ${start}-${end}`); |
| 50 | +} |
| 51 | + |
| 52 | +async function waitForDemo(port, opts = {}) { |
| 53 | + const timeoutAt = Date.now() + (opts.timeoutMs || 30_000); |
| 54 | + while (Date.now() < timeoutAt) { |
| 55 | + const probe = await probeDemoServer(port, opts); |
| 56 | + if (probe.status === 'demo') return true; |
| 57 | + if (probe.status === OCCUPIED_ERROR) throw new Error(probe.reason || `Port ${port} is occupied by a non-demo process.`); |
| 58 | + await wait(300); |
| 59 | + } |
| 60 | + throw new Error(`Demo server did not become ready on port ${port}`); |
| 61 | +} |
| 62 | + |
| 63 | +function startDemoServer(port, env = process.env) { |
| 64 | + const child = spawn('npm', ['run', 'serve-demo', '--', '--port', String(port)], { stdio: 'inherit', env }); |
| 65 | + const exited = new Promise((resolve) => { |
| 66 | + child.on('exit', (code, signal) => resolve({ code, signal })); |
| 67 | + }); |
| 68 | + const stop = async () => { |
| 69 | + if (!child || child.killed) return; |
| 70 | + child.kill('SIGTERM'); |
| 71 | + await Promise.race([exited, wait(5000)]); |
| 72 | + }; |
| 73 | + return { child, stop, exited }; |
| 74 | +} |
| 75 | + |
| 76 | +async function ensureDemoServer(options = {}) { |
| 77 | + const basePort = Number(options.basePort || DEFAULT_PORT); |
| 78 | + const maxPort = Number(options.maxPort || MAX_PORT); |
| 79 | + const host = options.host || HOST; |
| 80 | + const marker = options.marker || MARKER; |
| 81 | + const startServer = options.startServer || ((port) => startDemoServer(port, options.env)); |
| 82 | + |
| 83 | + // First check if something already answers; if demo, reuse. |
| 84 | + const probe = await probeDemoServer(basePort, { host, marker }); |
| 85 | + if (probe.status === 'demo') { |
| 86 | + process.env.DEMO_PORT = String(basePort); |
| 87 | + return { port: basePort, reused: true, close: async () => {} }; |
| 88 | + } |
| 89 | + if (probe.status === OCCUPIED_ERROR) { |
| 90 | + throw new Error(`Port ${basePort} is in use by a non-demo process.`); |
| 91 | + } |
| 92 | + |
| 93 | + const port = await findFreePort(basePort, maxPort); |
| 94 | + const { stop, exited } = startServer(port); |
| 95 | + try { |
| 96 | + await waitForDemo(port, { host, marker }); |
| 97 | + process.env.DEMO_PORT = String(port); |
| 98 | + return { |
| 99 | + port, |
| 100 | + reused: false, |
| 101 | + close: async () => { |
| 102 | + await stop(); |
| 103 | + await exited; |
| 104 | + }, |
| 105 | + }; |
| 106 | + } catch (err) { |
| 107 | + await stop(); |
| 108 | + await exited; |
| 109 | + throw err; |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +if (require.main === module) { |
| 114 | + (async () => { |
| 115 | + try { |
| 116 | + const { port, reused, close } = await ensureDemoServer(); |
| 117 | + console.log(`[demo-server] Using port ${port}${reused ? ' (reused existing server)' : ''}`); |
| 118 | + const stop = async () => { |
| 119 | + await close(); |
| 120 | + process.exit(0); |
| 121 | + }; |
| 122 | + process.on('SIGINT', stop); |
| 123 | + process.on('SIGTERM', stop); |
| 124 | + // Keep process alive only if we started the server; otherwise exit immediately. |
| 125 | + if (reused) { |
| 126 | + process.exit(0); |
| 127 | + } |
| 128 | + await new Promise(() => {}); |
| 129 | + } catch (err) { |
| 130 | + console.error('[demo-server] Failed to ensure demo server:', err.message); |
| 131 | + process.exit(1); |
| 132 | + } |
| 133 | + })(); |
| 134 | +} |
| 135 | + |
| 136 | +module.exports = { |
| 137 | + ensureDemoServer, |
| 138 | + probeDemoServer, |
| 139 | + waitForDemo, |
| 140 | + startDemoServer, |
| 141 | +}; |
0 commit comments