feat: integrate native BPM task processing and strict Excel test rules
This commit is contained in:
commit
8cb6a32876
444 files changed
+17045
-3182
No files matched your search
@@ -0,0 +1,6 @@
|
||||
'use strict';
|
||||
const {createBackup}=require('../src/platform/backup/snapshot.cjs');
|
||||
const {verifyBackup}=require('../src/platform/backup/manifest.cjs');
|
||||
const {restoreBackup}=require('../src/platform/backup/restore.cjs');
|
||||
async function main(args){const command=args.shift(),allowed={create:['destination','state','output'],verify:['source'],restore:['source','destination']}[command];if(!allowed)throw Object.assign(Error('invalid command'),{code:'BACKUP_USAGE'});const options={};while(args.length){const key=args.shift();if(!key.startsWith('--')||!allowed.includes(key.slice(2))||Object.hasOwn(options,key.slice(2))||!args.length||args[0].startsWith('--'))throw Object.assign(Error('invalid option'),{code:'BACKUP_USAGE'});options[key.slice(2)]=args.shift();}if((command!=='create'&&!options.source)||(command!=='verify'&&!options.destination))throw Object.assign(Error('missing option'),{code:'BACKUP_USAGE'});if(command==='create')await createBackup({stateDir:options.state,outputDir:options.output,destination:options.destination});else if(command==='verify')verifyBackup(options.source);else await restoreBackup(options);process.stdout.write(JSON.stringify({ok:true,operation:command})+'\n');}
|
||||
main(process.argv.slice(2)).catch(error=>{const code=/^(?:BACKUP_[A-Z_]+|ORDER_INSTANCE_OWNED)$/.test(error.code||'')?error.code:'BACKUP_FAILED';process.stderr.write(JSON.stringify({ok:false,code,message:'操作未完成。请检查服务已停止、备份完整性、目标为空及 Windows 身份兼容性。'})+'\n');process.exitCode=1;});
|
||||
@@ -1,7 +1,7 @@
|
||||
// Regression/import entry point for offline captures. Never contacts BPM.
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { renderSnapshot } = require('../src/exporter.cjs');
|
||||
const { renderSnapshot } = require('../src/modules/pdf/exporter.cjs');
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
// Offline admin preparation only. This module never loads the application,
|
||||
// network providers, scheduler, or mail sending service.
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const {execFileSync}=require('node:child_process');
|
||||
const {BpmVault}=require('../src/platform/security/vault.cjs');
|
||||
const {RuleStore}=require('../src/modules/order-rules/store.cjs');
|
||||
const {MailStore}=require('../src/modules/mail/store.cjs');
|
||||
const {readSourceWorkbook}=require('../src/modules/order-rules/source-workbook.cjs');
|
||||
const {buildPreparationPlan,applyPreparationPlan,publicPlan}=require('../src/modules/order-rules/test-preparation.cjs');
|
||||
const fail=code=>{throw Object.assign(Error(code),{code});};
|
||||
const databases=[['order-rules','rules.sqlite'],['mail','mail.sqlite']];
|
||||
function temporaryDirectory(){return fs.mkdtempSync(path.join(require('node:os').tmpdir(),'order-preparation-'));}
|
||||
function removeTemporaryDirectory(directory){if(path.dirname(path.resolve(directory))!==path.resolve(require('node:os').tmpdir())||!path.basename(directory).startsWith('order-preparation-'))fail('PREPARATION_TEMP_PATH');fs.rmSync(directory,{recursive:true,force:true});}
|
||||
function snapshotDatabases(stateDir){
|
||||
const read=()=>databases.flatMap(([directory,name])=>[name,name+'-wal'].map(filename=>{
|
||||
const relative=path.join(directory,filename),file=path.join(stateDir,relative);let before;
|
||||
try{before=fs.statSync(file,{bigint:true});}catch(error){if(error.code==='ENOENT'&&filename.endsWith('-wal'))return {relative,bytes:null,identity:null};throw error;}
|
||||
const bytes=fs.readFileSync(file),after=fs.statSync(file,{bigint:true}),identity=s=>[s.dev,s.ino,s.size,s.mtimeNs,s.ctimeNs].join(':');
|
||||
if(identity(before)!==identity(after))fail('PREPARATION_SOURCE_CHANGED');return {relative,bytes,identity:identity(after)};
|
||||
}));
|
||||
// Never open the source with SQLite: readOnly WAL connections can create or
|
||||
// update SHM. Only an unchanged double capture is eligible for local replay.
|
||||
let captured;
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
try{const before=read(),after=read();if(before.every((value,index)=>value.identity===after[index].identity&&(value.bytes===null?after[index].bytes===null:value.bytes.equals(after[index].bytes)))){captured=after;break;}}catch(error){if(error.code!=='PREPARATION_SOURCE_CHANGED'&&error.code!=='ENOENT')throw error;}
|
||||
}
|
||||
if(!captured)fail('PREPARATION_SOURCE_CHANGED');
|
||||
const root=temporaryDirectory();try{for(const {relative,bytes} of captured)if(bytes!==null){const file=path.join(root,relative);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,bytes,{flag:'wx',mode:0o600});}return root;}catch(error){removeTemporaryDirectory(root);throw error;}
|
||||
}
|
||||
function parseArgs(args){const options={apply:false};while(args.length){const arg=args.shift();if(arg==='--apply'){if(options.apply)throw Error('PREPARATION_USAGE');options.apply=true;continue;}const key={'--source-file':'sourceFile','--state-dir':'stateDir','--backup':'backup'}[arg];if(!key||options[key]||!args.length||args[0].startsWith('--'))throw Error('PREPARATION_USAGE');options[key]=args.shift();}if(!options.sourceFile)throw Error('PREPARATION_SOURCE_REQUIRED');if(options.apply&&!options.backup)throw Error('PREPARATION_BACKUP_REQUIRED');return options;}
|
||||
function existingVault(directory){
|
||||
const vault=Object.create(BpmVault.prototype);vault.stateDir=path.resolve(directory);
|
||||
// Bypass the constructor and ensureKey's directory/key creation: preview may
|
||||
// only read an existing vault, including when the key is missing or invalid.
|
||||
vault.ensureKey=function(){if(this.key)return this.key;const keyFile=process.platform==='win32'?require('../src/platform/backup/keys.cjs').keyPath(this.stateDir):path.join(this.stateDir,'.keys',crypto.createHash('sha256').update(this.stateDir.toLowerCase()).digest('hex')+'.key');const bytes=fs.readFileSync(keyFile);this.key=process.platform==='win32'?Buffer.from(execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))'],{input:bytes.toString('base64'),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim(),'base64'):bytes;if(this.key.length!==32){this.key.fill(0);this.key=null;throw Error('PREPARATION_KEY_INVALID');}return this.key;};return vault;
|
||||
}
|
||||
function openStores(stateDir,{readOnly=true}={}){
|
||||
const opened=[];let snapshotRoot;
|
||||
try{
|
||||
const databaseRoot=readOnly?(snapshotRoot=snapshotDatabases(stateDir)):stateDir;
|
||||
const store=Object.create(RuleStore.prototype);store.db=new DatabaseSync(path.join(databaseRoot,'order-rules','rules.sqlite'),{readOnly});opened.push(store);store.vault=existingVault(path.join(stateDir,'order-rules','secrets'));store.clock=()=>new Date();store.desktopRoot=path.join(require('node:os').homedir(),'Desktop');store.schedule=()=>({times:['11:00','17:00'],weekends:false});store.calendar=()=>[];store.capabilities={liveTodo:false,pdfExport:false,automaticArchive:false};
|
||||
const mailStore=Object.create(MailStore.prototype);mailStore.db=new DatabaseSync(path.join(databaseRoot,'mail','mail.sqlite'),{readOnly});opened.push(mailStore);mailStore.vault=existingVault(path.join(stateDir,'mail','secrets'));
|
||||
if(readOnly)for(const value of opened)if(value.db.prepare('PRAGMA quick_check').all().some(row=>Object.values(row)[0]!=='ok'))fail('PREPARATION_SOURCE_SNAPSHOT_INVALID');
|
||||
// Read an existing schema directly. Opening constructors here would run
|
||||
// recovery/migrations and could rewrite old sending records during preview.
|
||||
return {store,mailStore,close(){for(const value of opened.reverse()){value.db.close();value.vault?.destroy();}if(snapshotRoot){removeTemporaryDirectory(snapshotRoot);snapshotRoot=null;}}};
|
||||
}catch(error){for(const value of opened.reverse()){try{value.db.close();}catch{}value.vault?.destroy();}if(snapshotRoot)removeTemporaryDirectory(snapshotRoot);throw error;}
|
||||
}
|
||||
function assertBackupCurrent(manifest,stateDir,backupDir){
|
||||
const {inventory,fileHash,inside,verifyBackup}=require('../src/platform/backup/manifest.cjs');
|
||||
if(!backupDir)fail('PREPARATION_BACKUP_INCOMPLETE');
|
||||
const verified=verifyBackup(backupDir);if(JSON.stringify(verified)!==JSON.stringify(manifest))fail('PREPARATION_BACKUP_MANIFEST_CHANGED');
|
||||
const canonical=file=>fs.realpathSync(file).toLowerCase();if(canonical(manifest.source.stateDir)!==canonical(stateDir))throw Error('PREPARATION_BACKUP_STATE_MISMATCH');
|
||||
const outputDir=require('../src/platform/backup/snapshot.cjs').defaults(stateDir).outputDir;
|
||||
if(path.resolve(outputDir).toLowerCase()!==path.resolve(manifest.source.outputDir).toLowerCase())fail('PREPARATION_BACKUP_OUTPUT_MISMATCH');
|
||||
const current=inventory(stateDir),entries=new Map(manifest.files.map(file=>[file.path,file])),directories=new Set(manifest.directories),runtime=new Set(['supervisor/control.key','supervisor/control.sock']);
|
||||
const excluded=relative=>runtime.has(relative)||inside(outputDir,path.join(stateDir,relative))||/\.sqlite-shm$/.test(relative);
|
||||
const databaseFiles=current.files.filter(file=>file.path.endsWith('.sqlite')&&!excluded(file.path));
|
||||
for(const [directory,name] of databases)if(!databaseFiles.some(file=>file.path===directory+'/'+name)||!entries.has('state/'+directory+'/'+name))fail('PREPARATION_BACKUP_INCOMPLETE');
|
||||
for(const directory of current.directories)if(!excluded(directory)&&!directories.has('state/'+directory))fail('PREPARATION_BACKUP_INCOMPLETE');
|
||||
for(const file of current.files){
|
||||
if(excluded(file.path)||file.path.endsWith('.sqlite-wal'))continue;
|
||||
const entry=entries.get('state/'+file.path);if(!entry)fail('PREPARATION_BACKUP_INCOMPLETE');
|
||||
// Official backup validation replays committed WAL pages into its copy.
|
||||
// Compare database contents after the same normalization on both copies.
|
||||
if(!file.path.endsWith('.sqlite')&&(file.sha256!==entry.sha256||file.size!==entry.size))fail('PREPARATION_BACKUP_STALE');
|
||||
}
|
||||
// A full state listing alone is insufficient: Windows vault keys live outside
|
||||
// state. Every existing key must be present, identical and DPAPI-readable.
|
||||
if(process.platform==='win32'){
|
||||
const {keyPath,unprotect}=require('../src/platform/backup/keys.cjs');
|
||||
for(const directory of current.directories){
|
||||
if(excluded(directory))continue;const key=keyPath(path.join(stateDir,directory));if(!fs.existsSync(key))continue;
|
||||
const binding=manifest.vaults.find(vault=>vault.path===directory);
|
||||
if(!binding||binding.keyFile!=='keys/'+path.basename(key)||!entries.has(binding.keyFile))fail('PREPARATION_BACKUP_KEY_MISSING');
|
||||
const bytes=fs.readFileSync(path.join(backupDir,binding.keyFile));if(!bytes.equals(fs.readFileSync(key)))fail('PREPARATION_BACKUP_KEY_MISMATCH');unprotect(bytes);
|
||||
}
|
||||
}
|
||||
// Both source and bundle remain untouched. The caller holds the exclusive
|
||||
// offline instance lock while these current-state copies are compared.
|
||||
const validationRoot=temporaryDirectory();try{
|
||||
const sourceCopy=path.join(validationRoot,'current'),backupCopy=path.join(validationRoot,'backup'),validate=require('../src/platform/backup/restore.cjs').validateDatabases;
|
||||
fs.cpSync(stateDir,sourceCopy,{recursive:true,filter:file=>!excluded(path.relative(stateDir,file).split(path.sep).join('/'))});
|
||||
fs.cpSync(path.join(backupDir,'state'),backupCopy,{recursive:true,filter:file=>!file.endsWith('.sqlite-shm')});
|
||||
validate(sourceCopy,manifest.vaults);validate(backupCopy,manifest.vaults);
|
||||
for(const file of databaseFiles)if(fileHash(path.join(sourceCopy,file.path))!==fileHash(path.join(backupCopy,file.path)))fail('PREPARATION_BACKUP_STALE');
|
||||
}finally{removeTemporaryDirectory(validationRoot);}
|
||||
}
|
||||
async function main(args){
|
||||
const options=parseArgs([...args]),stateDir=path.resolve(options.stateDir||require('../src/platform/backup/snapshot.cjs').defaults().stateDir),source=readSourceWorkbook(options.sourceFile);let lock,opened;
|
||||
try{
|
||||
if(options.apply){const manifest=require('../src/platform/backup/manifest.cjs').verifyBackup(options.backup);lock=await require('../src/platform/backup/snapshot.cjs').lockOffline(stateDir);assertBackupCurrent(manifest,stateDir,options.backup);}
|
||||
opened=openStores(stateDir,{readOnly:!options.apply});const plan=buildPreparationPlan({...opened,source});
|
||||
if(!options.apply)return {mode:'dry-run',...publicPlan(plan)};
|
||||
const result=applyPreparationPlan({...opened,plan,actor:{username:'offline-admin',role:'admin'}});return {mode:'applied',run:result.run,automaticProcessing:false,automaticSending:false,source:plan.source};
|
||||
}finally{opened?.close();await lock?.release();}
|
||||
}
|
||||
if(require.main===module)main(process.argv.slice(2)).then(result=>process.stdout.write(JSON.stringify(result,null,2)+'\n')).catch(error=>{process.stderr.write(JSON.stringify({ok:false,code:/^(?:PREPARATION_|ORDER_|BACKUP_)/.test(error.code||error.message)?error.code||error.message:'PREPARATION_FAILED',message:'Preparation stopped; no automatic processing or sending was enabled.'})+'\n');process.exitCode=1;});
|
||||
module.exports={parseArgs,existingVault,openStores,assertBackupCurrent,main};
|
||||
@@ -1,43 +0,0 @@
|
||||
// Explicit, loopback-only demonstration space. Never opens BPM or sends messages.
|
||||
const crypto=require('node:crypto');
|
||||
const fs=require('node:fs');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');
|
||||
const {WorkspaceStore}=require('../src/workspace-store.cjs');
|
||||
const {createDashboard}=require('../src/dashboard.cjs');
|
||||
|
||||
async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776}={}) {
|
||||
fs.mkdirSync(stateDir,{recursive:true});
|
||||
const store=new Store(path.join(stateDir,'accounts'));
|
||||
if(!store.users().length) {
|
||||
store.bootstrap('preview',crypto.randomBytes(32).toString('hex'));
|
||||
store.addUser({username:'colleague',password:crypto.randomBytes(32).toString('hex'),role:'operator'},'演示初始化');
|
||||
}
|
||||
const admin=store.users().find(user=>user.role==='admin');
|
||||
if(!admin)throw Error('演示空间缺少管理员,请检查独立演示数据目录。');
|
||||
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
|
||||
try {
|
||||
const snapshot=workspace.snapshot(store.users());
|
||||
if(!snapshot.exceptions.length) {
|
||||
for(const item of [
|
||||
{title:'演示:BPM 连接等待人工登录',component:'bpm',priority:'high',description:'这是虚构的续登待办,用于体验认领、转交和验证。没有检查或使用真实 BPM 登录态。',owner:''},
|
||||
{title:'演示:归档目录待确认',component:'archive',priority:'normal',description:'这是虚构的接入任务。可转交给演示同事,并查看责任流转记录。',owner:'colleague'},
|
||||
{title:'演示:PDF 排版等待核验',component:'pdf',priority:'normal',description:'这是虚构的人工核验任务。提交验证后填写核验依据即可体验关闭流程。',owner:admin.username}
|
||||
])workspace.createException(item,admin,store.users());
|
||||
}
|
||||
if(!snapshot.connections.length)workspace.createConnection({name:'演示 BPM 连接',owner:admin.username},admin,store.users());
|
||||
const server=createDashboard({store,workspace,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
|
||||
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});
|
||||
let closed=false;
|
||||
return {server,store,workspace,async close(){if(closed)return;closed=true;await new Promise(resolve=>server.close(resolve));workspace.close();}};
|
||||
} catch(error) { workspace.close();throw error; }
|
||||
}
|
||||
|
||||
if(require.main===module)startPreview().then(runtime=>{
|
||||
console.log(`订单通知中心演示空间:http://127.0.0.1:${runtime.server.address().port}\n页面点击“进入演示空间”,数据与正式空间独立。\n此服务仅监听本机,不访问 BPM,不发送通知。`);
|
||||
const stop=()=>runtime.close().then(()=>process.exit(0));
|
||||
process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
||||
}).catch(error=>{console.error('预览启动失败:'+error.message);process.exitCode=1;});
|
||||
|
||||
module.exports={startPreview};
|
||||
+4
-4
@@ -1,16 +1,16 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{ServiceSupervisor}=require('../src/service-supervisor.cjs'),{defaultStateDir,requestControl,readSupervisor,canConfirmStopped}=require('../src/service-control.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{ServiceSupervisor}=require('../src/platform/service/supervisor.cjs'),{defaultStateDir,requestControl,readSupervisor,canConfirmStopped}=require('../src/platform/service/control.cjs');
|
||||
const root=path.resolve(__dirname,'..'),pause=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function ports(){let config={};try{config=JSON.parse(fs.readFileSync(path.join(root,'config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}const result=[config.port||18765,config.dashboard?.port??18766];if(result.some(p=>!Number.isInteger(p)||p<1024||p>65535)||result[0]===result[1])throw Error('服务端口配置无效。');return result;}
|
||||
async function waitRunning(stateDir,previousInstance){const end=Date.now()+130000;let last;
|
||||
while(Date.now()<end){try{last=(await requestControl({stateDir})).state;if(last.status==='running'&&(!previousInstance||last.childInstanceId!==previousInstance))return last;if(last.status==='cooldown')throw Object.assign(Error('重复启动失败,服务已进入冷却;请查看本机守护日志。'),{fatal:true});}catch(e){if(e.fatal)throw e;}await pause(1000);}throw Error('启动尚未就绪,请运行 npm run service:status 查看状态。');
|
||||
while(Date.now()<end){try{last=(await requestControl({stateDir})).state;if(last.status==='running'&&(!previousInstance||last.childInstanceId!==previousInstance))return last;if(last.status==='failed')throw Object.assign(Error(({port_conflict:'配置端口已被其他程序占用,请修改配置或释放端口后重试。',config_invalid:'服务端口配置无效,请修正 config.json 后重试。'})[last.reason]||'业务进程重启失败,请查看本机守护日志。'),{fatal:true});if(last.status==='cooldown')throw Object.assign(Error('重复启动失败,服务已进入冷却;请查看本机守护日志。'),{fatal:true});}catch(e){if(e.fatal)throw e;}await pause(1000);}throw Error('启动尚未就绪,请运行 npm run service:status 查看状态。');
|
||||
}
|
||||
async function main(action=process.argv[2]||'start'){
|
||||
const stateDir=defaultStateDir();
|
||||
if(action==='run'){
|
||||
const guard=new ServiceSupervisor({stateDir,ports:ports()});await guard.start();const stop=()=>guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return;
|
||||
const guard=new ServiceSupervisor({stateDir,portsProvider:ports});await guard.start();const stop=()=>guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return;
|
||||
}
|
||||
if(action==='install'||action==='uninstall'){const startup=require('../src/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;}
|
||||
if(action==='install'||action==='uninstall'){const startup=require('../src/platform/service/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;}
|
||||
if(action==='status'){let live;try{live=await requestControl({stateDir});}catch{}const saved=readSupervisor(stateDir);console.log(JSON.stringify({supervisorResponding:!!live,state:live?.state||saved.state,autostartEnabled:!!(saved.autostart?.enabled&&fs.existsSync(saved.autostart.linkPath)),events:saved.events},null,2));return;}
|
||||
if(action==='stop'){
|
||||
let expected;try{expected=(await requestControl({stateDir,action:'stop'})).state;}catch(e){if(['ENOENT','ECONNREFUSED'].includes(e.code)){console.log('服务守护未运行。');return;}throw e;}
|
||||
|
||||
Reference in new issue
Block a user