fix: drain accepted exports and close failed store initialization

This commit is contained in:
abaishu0730 committed 2026-10-19 09:11:40 +08:00
1 parent 54e5bafd86
commit a420d2d9fb
12 files changed
+204 -71

No files matched your search

+5 -3
View File
@@ -25,7 +25,7 @@ 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;}
if(!server.listening){await server.drainExports?.();server.closeSessionStore?.();return;}
await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));
}
async function main(options = {}) {
@@ -43,6 +43,7 @@ async function main(options = {}) {
const cleanup=[];
let stopping;
const stop=()=>stopping ||= (async()=>{
server?.stopAcceptingExports?.();
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);}
@@ -67,8 +68,9 @@ async function main(options = {}) {
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(()=>closeServer(server));
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(()=>closeServer(dashboard),()=>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});
@@ -81,7 +83,7 @@ async function main(options = {}) {
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});
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
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();
+21 -4
View File
@@ -7,9 +7,11 @@ const { respondToPing } = require('../platform/service/ping.cjs');
function createServer(options) {
let busy = false;
let accepting = true;
const pending = new Set();
const jobs = new Map();
const maxBytes = options.maxBodyBytes || 20 * 1024 * 1024;
return http.createServer(async (request, response) => {
const server = 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 || '';
@@ -29,6 +31,7 @@ function createServer(options) {
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 (!accepting) { request.resume(); return reply(503, {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:'正在导出其他订单,请稍后重试。'});
@@ -39,6 +42,7 @@ function createServer(options) {
request.on('end', () => { if (!overflow) resolve(Buffer.concat(chunks).toString('utf8')); });
request.on('error', reject);
});
if (!accepting) return reply(503, {error:'服务正在停止。'});
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:'正在导出其他订单,请稍后重试。'});
@@ -49,14 +53,27 @@ function createServer(options) {
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 task = Promise.resolve().then(() => (options.renderSnapshot || renderSnapshot)(snapshot, options)).then(async 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;});
busy=false;
// Archival remains background work for API/busy semantics, but belongs to shutdown.
if(saved)await options.storage?.automatic(saved).catch(()=>{});
}).catch(error=>{busy=false;const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{pending.delete(task);});
pending.add(task);
} catch(error) { if (!response.writableEnded) reply(error.status || 500,{error:error.message || '导出失败。'}); }
});
server.stopAcceptingExports = () => { accepting = false; };
server.drainExports = () => Promise.all([...pending]);
// HTTP completion does not imply that an accepted background export has finished.
const close = server.close.bind(server);
server.close = callback => {
server.stopAcceptingExports();
close(error => { server.drainExports().then(() => callback?.(error), failure => callback?.(error || failure)); });
return server;
};
return server;
}
async function startService(options) {