Files
weiguang-jewelry-ledger/新账系统/e2e/lib/server.js
T

93 lines
3.1 KiB
JavaScript
Raw Normal View History

'use strict';
// 父进程侧:以确定时钟启动应用子进程,提供时钟控制与停止。
const { fork } = require('node:child_process');
const path = require('node:path');
const CLOCK = path.join(__dirname, '..', 'fake-clock.cjs');
function startServer({
mode = 'trial',
dataDir,
startup = 'create',
clockStart,
seed = 'golden-seed',
tickMs = 0,
quiet = true,
} = {}) {
const child = fork(path.join(__dirname, 'server-child.cjs'), [], {
// E2E_MUTATION_REQUIRE:仅用于自检,额外预加载一个故意改变行为的脚本,确认对照能发现回归。
execArgv: [
'--require',
CLOCK,
...(process.env.E2E_MUTATION_REQUIRE ? ['--require', process.env.E2E_MUTATION_REQUIRE] : []),
'--disable-warning=ExperimentalWarning',
],
env: {
...process.env,
TZ: 'Asia/Shanghai',
FAKE_CLOCK_IPC: '1',
FAKE_CLOCK_START: clockStart || '2026-11-20T02:00:00.000Z',
FAKE_RANDOM_SEED: seed,
FAKE_CLOCK_TICK_MS: String(tickMs),
FEISHU_CONFIG: path.join(dataDir, 'no-feishu.json'),
APP_MODE: mode,
E2E_SERVER_OPTIONS: JSON.stringify({ mode, dataDir, startup }),
},
stdio: ['ignore', quiet ? 'pipe' : 'inherit', quiet ? 'pipe' : 'inherit', 'ipc'],
});
let output = '';
if (quiet) {
child.stdout.on('data', d => {
output += d;
});
child.stderr.on('data', d => {
output += d;
});
}
let seq = 0;
const waiting = new Map();
let readyResolve, readyReject;
const ready = new Promise((resolve, reject) => {
readyResolve = resolve;
readyReject = reject;
});
let stoppedResolve;
const stopped = new Promise(resolve => {
stoppedResolve = resolve;
});
child.on('message', message => {
if (message.type === 'ready') readyResolve(message);
else if (message.type === 'fatal') readyReject(new Error('应用启动失败:' + message.message + '\n' + output));
else if (message.type === 'fake-clock-ack') {
const w = waiting.get(message.id);
waiting.delete(message.id);
if (w) message.error ? w.reject(new Error(message.error)) : w.resolve(message.now);
} else if (message.type === 'stopped') stoppedResolve();
});
child.on('exit', code => {
readyReject(new Error('应用子进程退出 ' + code + '\n' + output));
stoppedResolve();
for (const w of waiting.values()) w.reject(new Error('应用子进程已退出'));
});
const clock = (op, ms) =>
new Promise((resolve, reject) => {
const id = ++seq;
waiting.set(id, { resolve, reject });
child.send({ type: 'fake-clock', op, ms, id });
});
return {
child,
async ready() {
const info = await ready;
return { ...info, base: 'http://127.0.0.1:' + info.port };
},
setTime: ms => clock('set', ms),
advance: ms => clock('advance', ms),
output: () => output,
async stop() {
if (child.exitCode !== null) return;
child.send({ type: 'stop' });
await Promise.race([stopped, new Promise(r => setTimeout(r, 5000))]);
if (child.exitCode === null) child.kill();
},
};
}
module.exports = { startServer };