refactor(app): split HTTP responsibilities and own state before recovery

This commit is contained in:
abaishu0730 committed 2026-10-19 08:59:35 +08:00
1 parent 098fec1007
commit 54e5bafd86
13 files changed
+430 -264

No files matched your search

+2 -155
View File
@@ -1,158 +1,5 @@
const http = require('node:http');
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { renderSnapshot, validateSnapshot } = require('./modules/pdf/exporter.cjs');
const { Store } = require('./modules/dashboard/store.cjs');
const { createDashboard } = require('./app/dashboard.cjs');
const { WorkspaceStore } = require('./modules/workspace/store.cjs');
const { BpmSessionManager } = require('./modules/bpm/session-manager.cjs');
const { BpmCustodian } = require('./modules/bpm/custodian.cjs');
const { MailStore } = require('./modules/mail/store.cjs');
const { MailService } = require('./modules/mail/service.cjs');
const { BpmScanStore } = require('./modules/bpm/scan-store.cjs');
const { BpmScanner } = require('./modules/bpm/scanner.cjs');
const { AssistantStore } = require('./modules/assistant/store.cjs');
const { AssistantService } = require('./modules/assistant/service.cjs');
const { ZcodeRuntime } = require('./modules/assistant/zcode-runtime.cjs');
const { RuntimeHealth } = require('./modules/health/runtime-health.cjs');
const { respondToPing } = require('./platform/service/ping.cjs');
const { StorageStore } = require('./modules/storage/store.cjs');
const { StorageService } = require('./modules/storage/service.cjs');
const { NotificationStore, NotificationService } = require('./modules/notifications/notifications.cjs');
function createServer(options) {
let busy = false;
const jobs = new Map();
const maxBytes = options.maxBodyBytes || 20 * 1024 * 1024;
return http.createServer(async (request, response) => {
if(respondToPing(request,response,options.watchdog))return;
const reply = (status, body) => { response.writeHead(status, { 'Content-Type':'application/json; charset=utf-8', 'Cache-Control':'no-store' }); response.end(JSON.stringify(body)); };
const origin = request.headers.origin || '';
if (!/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) return reply(403, {error:'仅接受已配对的浏览器扩展。'});
response.setHeader('Access-Control-Allow-Origin', origin);
response.setHeader('Vary', 'Origin');
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Methods','GET, POST, OPTIONS');
response.setHeader('Access-Control-Allow-Headers','Content-Type, X-Order-Token');
response.setHeader('Access-Control-Allow-Private-Network','true');
response.writeHead(204); response.end(); return;
}
const supplied = Buffer.from(String(request.headers['x-order-token'] || ''));
const expected = Buffer.from(options.token);
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy});
const jobRoute = /^\/jobs\/([a-f0-9]{32})$/.exec(request.url);
if (request.method === 'GET' && jobRoute) return jobs.has(jobRoute[1]) ? reply(200,jobs.get(jobRoute[1])) : reply(404,{error:'任务已过期,请检查输出目录后重试。'});
if (request.method !== 'POST' || request.url !== '/export') return reply(404, {error:'未知操作。'});
if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || '')) return reply(415, {error:'需要 JSON 数据。'});
if (Number(request.headers['content-length'] || 0) > maxBytes) { request.resume(); return reply(413, {error:'页面超过 20 MB 限制。'}); }
if (busy) return reply(409, {error:'正在导出其他订单,请稍后重试。'});
try {
const raw = await new Promise((resolve, reject) => {
const chunks = []; let total = 0; let overflow = false;
request.on('data', chunk => { total += chunk.length; if (total > maxBytes) { if (!overflow) { overflow=true; reject(Object.assign(new Error('页面过大。'),{status:413})); } } else if (!overflow) chunks.push(chunk); });
request.on('end', () => { if (!overflow) resolve(Buffer.concat(chunks).toString('utf8')); });
request.on('error', reject);
});
let snapshot;
try { snapshot = JSON.parse(raw); validateSnapshot(snapshot); } catch(error) { return reply(400, {error:error instanceof SyntaxError ? '页面数据不是有效 JSON。' : error.message}); }
if (busy) return reply(409,{error:'正在导出其他订单,请稍后重试。'});
busy = true;
const jobId = crypto.randomBytes(16).toString('hex');
if (jobs.size >= 20) jobs.delete(jobs.keys().next().value);
jobs.set(jobId,{status:'running',jobId});
try { options.store?.recordJob({jobId,status:'running',metadata:snapshot.metadata,...(snapshot.bpmOrder?{bpmOrder:{field:snapshot.bpmOrder.field,value:snapshot.bpmOrder.value}}:{})}); }
catch(error) {busy=false;jobs.delete(jobId);throw error;}
reply(202,{status:'running',jobId});
renderSnapshot(snapshot, options).then(result => {
const saved=options.store?.recordJob({status:'success',jobId,...result});
if(saved)options.storage?.automatic(saved).catch(()=>{});
jobs.set(jobId,{status:'success',jobId,...result});
console.log(`已保存:${result.filename} (${result.bytes} bytes)`);
}).catch(error=>{const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{busy=false;});
} catch(error) { if (!response.writableEnded) reply(error.status || 500,{error:error.message || '导出失败。'}); }
});
}
async function startService(options) {
// Complete file preparation before opening a socket: failed startup must exit cleanly.
await fs.mkdir(options.installedExtension,{recursive:true});
await fs.cp(options.extensionSourceDir,options.installedExtension,{recursive:true,filter:source => path.basename(source) !== 'local-config.js'});
await fs.writeFile(path.join(options.installedExtension,'local-config.js'),'globalThis.ORDER_LOCAL_CONFIG = '+JSON.stringify({endpoint:`http://127.0.0.1:${options.port}`,token:options.token})+';\n');
const server = createServer(options);
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(options.port,'127.0.0.1',resolve); });
return server;
}
async function main(options = {}) {
const startedAt=new Date().toISOString(),watchdog={token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt};
const root = path.resolve(__dirname,'..');
let config = options.config;
if(!config){
config={};
try { config = JSON.parse(await fs.readFile(path.join(root,'config.json'),'utf8')); } catch(error) { if(error.code !== 'ENOENT') throw error; }
}
const port = config.port || 18765;
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('端口需为 1024–65535。');
const stateDir = options.stateDir || path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation');
await fs.mkdir(stateDir,{recursive:true});
const tokenPath = path.join(stateDir,'pairing.key');
let token;
try { token = (await fs.readFile(tokenPath,'utf8')).trim(); } catch(error) { if(error.code !== 'ENOENT') throw error; token=crypto.randomBytes(32).toString('hex'); await fs.writeFile(tokenPath,token,{mode:0o600}); }
if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('本地配对文件损坏,请删除 pairing.key 后重启。');
const outputDir = path.resolve(root,config.outputDir || 'output/pdf');
const installedExtension = path.join(stateDir,'extension');
const dashboardConfig=config.dashboard || {};
const dashboardPort=dashboardConfig.port ?? 18766;
const dashboardHost=dashboardConfig.host || '0.0.0.0';
if(!Number.isInteger(dashboardPort) || dashboardPort<1024 || dashboardPort>65535 || dashboardPort===port)throw new Error('Web 看板端口需为 1024–65535,且不能与扩展服务相同。');
if(!['0.0.0.0','127.0.0.1'].includes(dashboardHost))throw new Error('Web 看板 host 请设置为 0.0.0.0(局域网)或 127.0.0.1(仅本机)。');
if(dashboardConfig.trustedProxy!==undefined && typeof dashboardConfig.trustedProxy!=='boolean')throw new Error('dashboard.trustedProxy 必须为布尔值。');
const store=new Store(path.join(stateDir,'dashboard'));
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
const bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
let server;
let dashboard;
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health;
try {
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
mailStore.migrateLegacy(store.settings().templates);
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
health.start();
}
catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`);
if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`);
}
let stopping;
const stop=()=>stopping ||= (async()=>{
health.close();
await assistant.stop();await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
workspace.close();
mailStore.close();
scanStore.close();
storageStore.close();
notificationStore.close();
assistantStore.close();
})();
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop};
}
const {createServer,startService}=require('./app/bridge.cjs');
const {main}=require('./app/application.cjs');
if (require.main === module) main().then(app=>{
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
process.once('SIGINT',stop);process.once('SIGTERM',stop);