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

+97
View File
@@ -0,0 +1,97 @@
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { Store } = require('../modules/dashboard/store.cjs');
const { createDashboard } = require('./dashboard.cjs');
const { startService } = require('./bridge.cjs');
const { acquireInstanceLock } = require('../platform/service/instance-lock.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 { StorageStore } = require('../modules/storage/store.cjs');
const { StorageService } = require('../modules/storage/service.cjs');
const { NotificationStore } = require('../modules/notifications/store.cjs');
const { NotificationService } = require('../modules/notifications/service.cjs');
async function closeServer(server){
if(!server)return;
// An unbound dashboard still owns its session DB.
if(!server.listening){server.closeSessionStore?.();return;}
await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));
}
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 = require('../shared/paths.cjs').PROJECT_ROOT;
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');
const ownership=await acquireInstanceLock(stateDir);
const cleanup=[];
let stopping;
const stop=()=>stopping ||= (async()=>{
const errors=[];
// Stop producers before closing stores. Every teardown gets an attempt, even after a failure.
for(const close of cleanup)try{await close();}catch(error){errors.push(error);}
try{await ownership.release();}catch(error){errors.push(error);}
if(errors.length)throw new AggregateError(errors,'关闭服务时部分资源清理失败。');
})();
let server,dashboard,store,workspace,bpmSessions,custodian;
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health;
try {
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 必须为布尔值。');
store=new Store(path.join(stateDir,'dashboard'));
workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
// Register conditional closures before constructing later resources; partial startup follows the same path.
cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown());
cleanup.push(()=>closeServer(dashboard),()=>closeServer(server),()=>workspace.close());
cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>assistantStore?.close());
bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
custodian=new BpmCustodian({workspace,manager:bpmSessions});
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'));notificationStore.recover();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();
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}`);
}
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop};
}catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
}
module.exports={main};