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) {
+12 -6
View File
@@ -9,12 +9,18 @@ function installedRuntime(dir){try{
}catch{return '';}}
class AssistantStore{
constructor(dir){
this.dir=path.resolve(dir);this.defaultRuntime=installedRuntime(this.dir);this.vault=new BpmVault({stateDir:this.dir});this.db=new DatabaseSync(path.join(this.dir,'assistant.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
try {
this.dir=path.resolve(dir);this.defaultRuntime=installedRuntime(this.dir);this.vault=new BpmVault({stateDir:this.dir});this.db=new DatabaseSync(path.join(this.dir,'assistant.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,value){return this.vault.encode('assistant:'+id,value);}
+14 -7
View File
@@ -2,13 +2,20 @@
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const invalid=message=>Object.assign(new Error(message),{status:400});
class BpmScanStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
constructor(dir){
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
+7 -2
View File
@@ -7,8 +7,13 @@ const SESSION_MS=30*DAY;
const digest=token=>crypto.createHash('sha256').update(token).digest('hex');
class SessionStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
issue(userId,now=Date.now()){
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
+8 -3
View File
@@ -5,9 +5,14 @@ const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||n
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
class RuntimeHealth {
constructor({stateDir,startedAt=new Date().toISOString(),instanceId='',...sources}){
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`);
try {
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
remember(kind,id,{successAt,failureAt}={}){
const old=this.db.prepare('SELECT last_success AS lastSuccessAt,last_failure AS lastFailureAt FROM observations WHERE kind=? AND id=?').get(kind,id)||{};
+16 -9
View File
@@ -5,15 +5,22 @@ const email=value=>{if(typeof value!=='string'||value.length>254||!/^[A-Za-z0-9.
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
const at=()=>new Date().toISOString();const hash=raw=>crypto.createHash('sha256').update(raw).digest('hex');
class MailStore{
constructor(dir){this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
constructor(dir){
try {
this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
summary(p){return JSON.stringify({subject:p.subject,sender:p.sender,attachmentCount:p.attachments.length});}
recoverSends(){this.db.prepare("UPDATE sends SET status='unknown' WHERE status='sending'").run();}
+17 -10
View File
@@ -2,16 +2,23 @@
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {DEFAULT_MAP,validateMap,hash}=require('./mapping.cjs');
class NotificationStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
`);
this.db.exec('CREATE TABLE IF NOT EXISTS retry_audit(id TEXT PRIMARY KEY,item_id TEXT NOT NULL,payload BLOB NOT NULL)');
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
constructor(dir){
try {
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
`);
this.db.exec('CREATE TABLE IF NOT EXISTS retry_audit(id TEXT PRIMARY KEY,item_id TEXT NOT NULL,payload BLOB NOT NULL)');
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
recover(){return this.transaction(()=>{
this.db.exec("UPDATE items SET status='pending' WHERE status='reserved' AND batch_id IN(SELECT id FROM batches WHERE status='prepared'); UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending') AND status IN('reserved','sending'); UPDATE batches SET status='cancelled' WHERE status='prepared'; UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';");this.exhaustEligible();
+13 -7
View File
@@ -10,13 +10,19 @@ const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||
const now=()=>new Date().toISOString();
class StorageStore{
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
try {
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
throw error;
}
}
row(id){if(typeof id!=='string')fail('请选择存储服务器。');const row=this.db.prepare('SELECT * FROM servers WHERE id=?').get(id);if(!row)fail('存储服务器不存在。',404);return row;}
secret(id){const row=this.row(id);try{const saved=this.vault.decode(id,row.payload);return {authMode:'credentials',passwordless:false,...saved,id,version:row.version,state:JSON.parse(row.state)};}catch{fail('存储凭据无法解密,请联系管理员。',503);}}
+18 -13
View File
@@ -9,19 +9,24 @@ const validDate=date=>typeof date==='string' && /^\d{4}-\d{2}-\d{2}$/.test(date)
class WorkspaceStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
try {
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
meta(key){return JSON.parse(this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key).value);}
+12 -7
View File
@@ -2,13 +2,18 @@
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../security/vault.cjs');
class SupervisorStore {
constructor(stateDir){
this.dir=path.join(path.resolve(stateDir),'supervisor');new BpmVault({stateDir:this.dir}).destroy();
this.db=new DatabaseSync(path.join(this.dir,'supervisor.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY,at TEXT NOT NULL,kind TEXT NOT NULL,detail TEXT NOT NULL);`);
const file=path.join(this.dir,'control.key');try{fs.writeFileSync(file,crypto.randomBytes(32).toString('hex'),{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}
this.token=fs.readFileSync(file,'utf8').trim();if(!/^[a-f0-9]{64}$/.test(this.token))throw Error('服务守护控制文件无效。');
try {
this.dir=path.join(path.resolve(stateDir),'supervisor');new BpmVault({stateDir:this.dir}).destroy();
this.db=new DatabaseSync(path.join(this.dir,'supervisor.sqlite'));
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY,at TEXT NOT NULL,kind TEXT NOT NULL,detail TEXT NOT NULL);`);
const file=path.join(this.dir,'control.key');try{fs.writeFileSync(file,crypto.randomBytes(32).toString('hex'),{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}
this.token=fs.readFileSync(file,'utf8').trim();if(!/^[a-f0-9]{64}$/.test(this.token))throw Error('服务守护控制文件无效。');
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
}
}
get(key){const r=this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key);return r?JSON.parse(r.value):null;}
set(key,value){this.db.prepare('INSERT INTO metadata VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,JSON.stringify(value));}
+61
View File
@@ -0,0 +1,61 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net'),http=require('node:http');
const {DatabaseSync}=require('node:sqlite');
const {main,createServer}=require('../../src/server.cjs');let render;
const {acquireInstanceLock}=require('../../src/platform/service/instance-lock.cjs');
const turn=()=>new Promise(r=>setImmediate(r));
const gate=()=>{let release;const promise=new Promise(r=>release=r);return {promise,release};};
async function port(){const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;}
async function fixture(){const stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-final-lifecycle-'));return {stateDir,quiet:true,config:{port:await port(),outputDir:path.join(stateDir,'output'),dashboard:{port:await port(),host:'127.0.0.1'}}};}
const snapshot={html:'<p>fixture</p>',metadata:{order:'order',project:'project',model:'model',serial:'serial'}};
function post(port,token,{partial=false}={}){let finish;const response=new Promise((resolve,reject)=>{const req=http.request({host:'127.0.0.1',port,path:'/export',method:'POST',headers:{Origin:'chrome-extension://'+'a'.repeat(32),'X-Order-Token':token,'Content-Type':'application/json',Connection:'close'}},res=>{let body='';res.on('data',c=>body+=c);res.on('end',()=>resolve({status:res.statusCode,body:JSON.parse(body)}));});req.on('error',reject);const raw=JSON.stringify(snapshot);if(partial){req.write(raw.slice(0,5));finish=()=>req.end(raw.slice(5));}else req.end(raw);});return {response,finish:()=>finish()};}
test('application stop retains ownership and storage until accepted rendering and automatic archive settle',async t=>{
const options=await fixture(),renderGate=gate(),archiveGate=gate(),archiveStarted=gate();let app,stopping,writes=0;
render=async()=>{await renderGate.promise;return {filename:'fixture.pdf',bytes:1};};
t.after(async()=>{renderGate.release();archiveGate.release();await stopping?.catch(()=>{});await app?.stop();await fs.rm(options.stateDir,{recursive:true,force:true});});
app=await main({...options,renderSnapshot:(...args)=>render(...args)});const token=(await fs.readFile(path.join(options.stateDir,'pairing.key'),'utf8')).trim();
let storageStopped=false;const originalStop=app.storage.stop.bind(app.storage);app.storage.stop=async()=>{storageStopped=true;await originalStop();};
app.storage.automatic=async job=>{assert.equal(storageStopped,false);archiveStarted.release();await archiveGate.promise;app.storage.jobs.recordJob({...job,archiveFixture:true});writes++;};
const accepted=await post(options.config.port,token).response;assert.equal(accepted.status,202);
let done=false;stopping=app.stop().then(()=>{done=true;});await new Promise(r=>setTimeout(r,40));
assert.equal(done,false,'stop must wait for accepted renderer');assert.equal(storageStopped,false);await assert.rejects(acquireInstanceLock(options.stateDir),e=>e.code==='ORDER_INSTANCE_OWNED');
renderGate.release();await archiveStarted.promise;await turn();assert.equal(done,false,'stop must wait for automatic archive');await assert.rejects(acquireInstanceLock(options.stateDir),e=>e.code==='ORDER_INSTANCE_OWNED');
archiveGate.release();await stopping;assert.equal(writes,1);assert.equal(storageStopped,true);
const replacement=await main(options);await replacement.stop();await turn();assert.equal(writes,1);
});
test('request whose body completes after shutdown begins cannot start a new export',async t=>{
let rendered=0;render=async()=>{rendered++;return {filename:'fixture.pdf',bytes:1};};const server=createServer({token:'fixture',renderSnapshot:(...args)=>render(...args)});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const received=new Promise(r=>server.once('request',r));const pending=post(server.address().port,'fixture',{partial:true});await received;
const closing=new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));pending.finish();const response=await pending.response;await closing;
assert.equal(response.status,503);assert.equal(rendered,0);
});
test('malformed workspace migration closes its allocated database before ownership release and permits repaired retry',async t=>{
const options=await fixture();t.after(()=>fs.rm(options.stateDir,{recursive:true,force:true}));await fs.mkdir(path.join(options.stateDir,'workspace'));const file=path.join(options.stateDir,'workspace','workspace.sqlite');const db=new DatabaseSync(file);db.exec("CREATE TABLE connections(id TEXT PRIMARY KEY,value TEXT NOT NULL); INSERT INTO connections VALUES('legacy','{broken');");db.close();
const original=DatabaseSync.prototype.exec;let allocated;
DatabaseSync.prototype.exec=function(sql){if(sql.includes('PRAGMA foreign_keys=ON'))allocated=this;return original.call(this,sql);};
try{await assert.rejects(main(options),SyntaxError);}finally{DatabaseSync.prototype.exec=original;}
try{assert.throws(()=>allocated.prepare('SELECT 1'),/not open|closed/i);}finally{try{allocated.close();}catch{}}
const repair=new DatabaseSync(file);repair.exec('DELETE FROM connections');repair.close();const app=await main(options);await app.stop();
});
test('all allocating store constructors close the database and destroy the vault when initialization fails',async t=>{
const cases=[['workspace','WorkspaceStore'],['mail','MailStore'],['notifications','NotificationStore'],['storage','StorageStore'],['assistant','AssistantStore'],['bpm/scan-store','BpmScanStore'],['dashboard/sessions','SessionStore'],['health/runtime-health','RuntimeHealth'],['../platform/service/store','SupervisorStore']];
const {BpmVault}=require('../../src/platform/security/vault.cjs');
for(const [name,exportName] of cases)await t.test(name,async()=>{const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-constructor-'));let allocated,destroyed=0;const exec=DatabaseSync.prototype.exec,destroy=BpmVault.prototype.destroy;DatabaseSync.prototype.exec=function(){allocated=this;throw new Error('initialization fixture');};BpmVault.prototype.destroy=function(){destroyed++;return destroy.call(this);};
try{const file=name.includes('/')?name:name+'/store';const Type=require('../../src/modules/'+file+'.cjs')[exportName];assert.throws(()=>new Type(exportName==='RuntimeHealth'?{stateDir:dir}:dir),/initialization fixture/);assert.throws(()=>allocated.prepare('SELECT 1'),/not open|closed/i,name);if(['mail','notifications','storage','assistant'].includes(name))assert.equal(destroyed,1,name);}
finally{DatabaseSync.prototype.exec=exec;BpmVault.prototype.destroy=destroy;try{allocated?.close();}catch{}await fs.rm(dir,{recursive:true,force:true});}
});
});
test('automatic archive remains background work and finishing it cannot clear a newer renderer busy state',async t=>{
const archive=gate(),archiveStarted=gate(),secondRender=gate();let calls=0;const records=[];
const server=createServer({token:'fixture',store:{recordJob(job){records.push(job);return job;}},storage:{automatic:async()=>{archiveStarted.release();await archive.promise;}},renderSnapshot:async()=>{if(++calls===2)await secondRender.promise;return {filename:'fixture.pdf',bytes:1};}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const p=server.address().port;
t.after(async()=>{archive.release();secondRender.release();if(server.listening)await new Promise(r=>server.close(r));});
assert.equal((await post(p,'fixture').response).status,202);await archiveStarted.promise;
assert.equal((await post(p,'fixture').response).status,202);archive.release();await turn();
assert.equal((await post(p,'fixture').response).status,409);
let done=false;const closing=new Promise(r=>server.close(r)).then(()=>{done=true;});await turn();assert.equal(done,false);secondRender.release();await closing;assert.equal(records.filter(r=>r.status==='success').length,2);
});
test('shutdown drains a synchronous renderer failure and preserves the accepted job error',async()=>{
const records=[];const server=createServer({token:'fixture',store:{recordJob:job=>{records.push(job);return job;}},renderSnapshot(){throw new Error('renderer fixture');}});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const response=await post(server.address().port,'fixture').response;assert.equal(response.status,202);await new Promise(r=>server.close(r));assert.deepEqual(records.map(j=>j.status),['running','error']);assert.equal(records[1].jobId,response.body.jobId);assert.equal(records[1].error,'renderer fixture');
});