feat: unify BPM health and guard session recovery with state machines
This commit is contained in:
1 parent
97e06328c3
commit
42d19c707d
23 files changed
+681
-90
No files matched your search
@@ -1,4 +1,5 @@
|
||||
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
|
||||
const {connectionSnapshot}=require('./connection-status.cjs');
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
function secureBpmTransport(request,trustedProxy=false){
|
||||
if(request.socket.encrypted)return true;
|
||||
@@ -23,6 +24,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
|
||||
const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account);
|
||||
if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。');
|
||||
const connection=workspace.getConnection(id);authorizeConnection(connection,user);
|
||||
const describe=value=>connectionSnapshot(value,{manager:bpmSessions,monitor:bpmLifecycle?.monitor});
|
||||
if(action==='delete'){
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body);
|
||||
if(connection.status!=='disabled')fail(409,'请先停用连接再删除。');
|
||||
@@ -33,7 +35,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以启用或停用连接。');
|
||||
if(!body||Array.isArray(body)||Object.keys(body).some(k=>k!=='version'))fail(400,'请提供当前连接版本。');
|
||||
const input=action==='disable'&&!Object.keys(body).length?{version:connection.version||0}:body;
|
||||
reply(200,await bpmLifecycle.change(id,action==='enable',input,user));return true;
|
||||
reply(200,describe(await bpmLifecycle.change(id,action==='enable',input,user)));return true;
|
||||
}
|
||||
if(connection.status==='disabled')fail(409,'此连接已停用。');
|
||||
if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。');
|
||||
@@ -54,7 +56,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
|
||||
try{const result=await managerCall(()=>bpmSessions.ensure(workspace.getConnection(id),principal));checked=workspace.updateConnectionSession(id,result,user);}
|
||||
catch(error){if(error.status!==409)throw error;checked=workspace.getConnection(id);}
|
||||
}
|
||||
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:checked}:{})});return true;
|
||||
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:describe(checked)}:{})});return true;
|
||||
}
|
||||
if(action==='fill-account'){
|
||||
const value=await managerCall(()=>bpmSessions.fillAccount(connection,principal));reply(200,{filled:value.filled===true,message:typeof value.message==='string'?value.message:''});return true;
|
||||
@@ -65,7 +67,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
|
||||
response.writeHead(200,{'Content-Type':'image/jpeg'});response.end(bytes);return true;
|
||||
}
|
||||
if(action==='save' || action==='check'){
|
||||
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,workspace.updateConnectionSession(id,result,user));return true;
|
||||
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,describe(workspace.updateConnectionSession(id,result,user)));return true;
|
||||
}
|
||||
const value=await managerCall(()=>bpmSessions[action](action==='open'?connection:id,principal,body));
|
||||
if(action==='open')reply(200,{active:value.active===true,viewport:{width:value.viewport?.width,height:value.viewport?.height},expiresAt:value.expiresAt,host:value.host});
|
||||
|
||||
@@ -3,6 +3,7 @@ const crypto=require('node:crypto');
|
||||
const {dayPolicy}=require('../../shared/schedule.cjs');
|
||||
const {normalizeArrival}=require('./list-client.cjs');
|
||||
const {BpmSignalRClient}=require('./signalr-client.cjs');
|
||||
const {ListenerState}=require('./listener-state.cjs');
|
||||
function todoArrival(row){
|
||||
if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502});
|
||||
return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),...(row.revision==null?{}:{revision:row.revision}),processVersion:row.processVersion||'',recordKey:String(row.taskId)};
|
||||
@@ -18,7 +19,7 @@ class BpmArrivalMonitor{
|
||||
sourceSuccess(entry,kind){if(!entry||!this.active(entry))return;const source=this.source(entry,kind);Object.assign(source,{status:'healthy',failures:0,nextAttempt:0,lastSuccessAt:new Date(this.clock()).toISOString(),message:null});if(['todo','inform'].every(k=>this.source(entry,k).status==='healthy'))entry.lastSyncAt=new Date(this.clock()).toISOString();}
|
||||
sourceFailure(entry,kind,error){if(!entry||!this.active(entry))return;const source=this.source(entry,kind),delay=this.sourceRetryMs[Math.min(source.failures++,this.sourceRetryMs.length-1)];Object.assign(source,{status:'error',lastFailureAt:new Date(this.clock()).toISOString(),nextAttempt:this.clock()+delay,message:error?.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);}
|
||||
deliveryState(id){return this.scanner.store.deliveries?.summary(id)||{status:'healthy',pending:0};}
|
||||
snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))};
|
||||
snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,sessionEpoch:e.epoch??null,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))};
|
||||
let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)};
|
||||
}
|
||||
updateInterval(entry,config){if(entry.intervalMinutes===config.intervalMinutes)return;entry.intervalMinutes=config.intervalMinutes;entry.nextReconcile=(entry.lastReconcileAt??this.clock())+config.intervalMinutes*60000;}
|
||||
@@ -30,8 +31,10 @@ class BpmArrivalMonitor{
|
||||
if(!config.enabled)return;
|
||||
for(const c of connections){
|
||||
if(c.status==='disabled'||c.status==='disconnected'&&!c.lastConnectedAt)continue;
|
||||
let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,status:'connecting',nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,lastReconcileAt:this.clock(),intervalMinutes:config.intervalMinutes,sources:{},failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);}
|
||||
let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,lifecycle:new ListenerState(),get status(){return this.lifecycle.state;},nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,lastReconcileAt:this.clock(),intervalMinutes:config.intervalMinutes,sources:{},failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);}
|
||||
this.updateInterval(entry,config);
|
||||
const session=this.manager.sessionSnapshot?.(c.id);
|
||||
if(['login_required','busy'].includes(entry.status)&&session?.phase==='idle'&&session.authentication==='valid')entry.nextRetry=0;
|
||||
if(this.allowed())this.publishPending(c.id,()=>this.active(entry)&&this.allowed()&&entry.epoch===(this.manager.epoch?.(c.id)||0)).catch(()=>{});
|
||||
if(entry.handle&&entry.epoch!==(this.manager.epoch?.(c.id)||0)){await this.stopConnection(c.id);continue;}
|
||||
if(!entry.handle&&!entry.connecting&&this.clock()>=entry.nextRetry)this.connect(entry,c);
|
||||
@@ -39,21 +42,21 @@ class BpmArrivalMonitor{
|
||||
else if(entry.dirty.size&&!entry.sync&&!entry.debounce)this.queue(entry,[]);
|
||||
}
|
||||
}
|
||||
retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;entry.status=status;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
|
||||
retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;if(!entry.lifecycle.transition(({polling:'NETWORK_FAILED',login_required:'AUTH_REQUIRED',busy:'BUSY'})[status]))return;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
|
||||
connect(entry,connection){
|
||||
const attempt=++entry.attempt;let closed=false;entry.status=entry.failures?'reconnecting':'connecting';
|
||||
const ticket=entry.lifecycle.begin();if(ticket===null)return;const attempt=++entry.attempt;let closed=false;
|
||||
entry.connecting=(async()=>{
|
||||
if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
|
||||
const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry))return;
|
||||
const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry)||!entry.lifecycle.current(ticket))return;
|
||||
if(result.status!=='connected'){this.retry(entry,result.status==='login_required'?'login_required':'polling',5*60000);return;}
|
||||
entry.epoch=this.manager.epoch?.(entry.id)||0;const handle=await this.manager.run(entry.id,async()=>{
|
||||
this.manager.authorize(connection,this.principal);if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
|
||||
const saved=await this.manager.vault().read(entry.id);
|
||||
return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);}}});
|
||||
return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||!entry.lifecycle.current(ticket)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.lifecycle.current(ticket)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);}}});
|
||||
});
|
||||
if(!handle)return;if(!this.active(entry)||closed){await handle.stop();return;}
|
||||
entry.handle=handle;entry.connectedAt=this.clock();entry.status='listening';entry.nextRetry=Infinity;entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']);
|
||||
})().catch(error=>{if(!this.active(entry))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;});
|
||||
if(!handle)return;if(!this.active(entry)||closed||!entry.lifecycle.transition('CONNECTED',ticket)){await handle.stop();return;}
|
||||
entry.handle=handle;entry.connectedAt=this.clock();entry.nextRetry=Infinity;entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']);
|
||||
})().catch(error=>{if(!this.active(entry)||!entry.lifecycle.current(ticket))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;});
|
||||
}
|
||||
dueKinds(entry){return [...entry.dirty].filter(kind=>this.clock()>=this.source(entry,kind).nextAttempt);}
|
||||
queue(entry,kinds){if(!this.active(entry))return;for(const kind of kinds)entry.dirty.add(kind);if(entry.sync||entry.debounce||!this.dueKinds(entry).length||!this.allowed()||this.manager.sessions.has(entry.id))return;
|
||||
@@ -97,7 +100,7 @@ class BpmArrivalMonitor{
|
||||
catch{const delay=this.sourceRetryMs[Math.min(item.attempts,this.sourceRetryMs.length-1)];this.scanner.store.deliveries.failed(item.id,this.clock()+delay);}
|
||||
}}).finally(()=>{if(this.deliveryPending.get(id)===task)this.deliveryPending.delete(id);});this.deliveryPending.set(id,task);return task;
|
||||
}
|
||||
async stopConnection(id){const entry=this.entries.get(id);if(entry){this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);}await Promise.allSettled([entry?.handle?.stop(),entry?.connecting,entry?.sync,this.todoPending.get(id),this.deliveryPending.get(id)]);}
|
||||
async stopConnection(id){const entry=this.entries.get(id);if(entry){entry.lifecycle.transition('STOP');this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);}await Promise.allSettled([entry?.handle?.stop(),entry?.connecting,entry?.sync,this.todoPending.get(id),this.deliveryPending.get(id)]);}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await Promise.all([...this.entries.keys()].map(id=>this.stopConnection(id)));await Promise.allSettled([...this.todoPending.values(),...this.deliveryPending.values()]);}
|
||||
}
|
||||
module.exports={BpmArrivalMonitor,todoArrival};
|
||||
@@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
const time=value=>typeof value==='string'&&Number.isFinite(Date.parse(value))?Date.parse(value):null;
|
||||
const view=(status,reason,message,checkedAt=null)=>({status,color:status==='healthy'?'green':status==='error'?'red':'yellow',label:status==='healthy'?'健康':status==='error'?'异常':'警告',reason,message,checkedAt});
|
||||
// A pure projection of observations. It must never authenticate, scan, retry or mutate custody.
|
||||
function projectConnectionStatus(connection,{now=Date.now(),config={},sessionFreshMs=300000,sessionEpoch}={}){
|
||||
const health=connection.health||{},monitoring=connection.monitoring||{},activity=connection.sessionActivity||{};
|
||||
const interval=Number.isFinite(config.intervalMinutes)&&config.intervalMinutes>0?config.intervalMinutes:5;
|
||||
const sourceFreshMs=Math.max(60000,interval*120000+30000);
|
||||
const sessionWindow=Math.max(60000,sessionFreshMs*2+30000);
|
||||
const fresh=(at,window)=>{const value=time(at);return value!==null&&value<=now&&now-value<=window;};
|
||||
const paused=view('paused','DISABLED','连接已停用');
|
||||
if(connection.status==='disabled'||['paused','stopped'].includes(activity.phase))return {account:paused,sync:{...paused}};
|
||||
|
||||
const savedAt=time(connection.checkedAt),observed=health.portal,observedAt=time(observed?.checkedAt);
|
||||
const useObserved=observedAt!==null&&(savedAt===null||observedAt>=savedAt);
|
||||
const session=useObserved?observed:{status:connection.status==='login_required'?'login_required':connection.status==='error'?'error':connection.status==='connected'&&connection.checks?.portal?.ok===true?'healthy':'unknown',checkedAt:connection.checkedAt||null};
|
||||
let account;
|
||||
if(session.status==='login_required')account=view('error','AUTH_REQUIRED','登录已失效,请重新登录',session.checkedAt);
|
||||
else if(session.status==='error'||session.status==='forbidden')account=view('pending','SESSION_UNAVAILABLE','暂时无法核实登录,请检查网络或连接',session.checkedAt);
|
||||
else if(session.status!=='healthy')account=view('pending','CHECK_PENDING','账号等待检查',session.checkedAt);
|
||||
else if(!fresh(session.checkedAt,sessionWindow))account=view('pending','SESSION_STALE','最近登录验证已过期,等待后台检查',session.checkedAt);
|
||||
else account=view('healthy','SESSION_VALID','登录会话有效',session.checkedAt);
|
||||
if(activity.phase==='renewing')account=view('pending','RENEWING','正在自动恢复登录会话',session.checkedAt);
|
||||
else if(activity.phase==='manual'&&account.status!=='healthy')account=view('pending','MANUAL_LOGIN','等待人工完成登录验证',session.checkedAt);
|
||||
else if(activity.authentication==='expired'&&activity.retryAt>now)account=view('pending','RENEWAL_COOLDOWN','自动续登冷却中,请等待或更新托管账号',session.checkedAt);
|
||||
else if(activity.phase==='checking'&&account.reason==='CHECK_PENDING')account=view('pending','CHECKING','正在检查登录会话',session.checkedAt);
|
||||
|
||||
const sync=()=>{
|
||||
if(config.enabled===false||monitoring.status==='paused')return view('paused','SYNC_PAUSED','自动同步已暂停');
|
||||
if(activity.phase==='manual')return view('pending','MANUAL_LOGIN','人工登录窗口使用中,同步暂缓');
|
||||
if(activity.phase==='renewing'||account.reason==='RENEWAL_COOLDOWN')return view('pending',account.reason,account.message);
|
||||
if(Number.isInteger(sessionEpoch)&&Number.isInteger(monitoring.sessionEpoch)&&sessionEpoch!==monitoring.sessionEpoch)return view('pending','SESSION_CHANGED','登录会话已更新,等待新会话完成监听和读取');
|
||||
const failures=[],warnings=[];
|
||||
const delivery=monitoring.delivery||{};
|
||||
if(['error','failed','retrying'].includes(delivery.status))failures.push(view('error','DELIVERY_FAILED','执行线索投递失败,账号会话单独核验',delivery.lastFailureAt||null));
|
||||
else if(delivery.pending>0)warnings.push(view('pending','DELIVERY_PENDING','执行线索等待本地投递'));
|
||||
for(const [kind,label]of [['todo','待办'],['inform','通知']]){
|
||||
const source=monitoring.sources?.[kind]||{},probe=health[kind];
|
||||
// A newer successful full read supersedes an older permission probe.
|
||||
if(probe?.status==='forbidden'&&(time(source.lastSuccessAt)===null||time(probe.checkedAt)===null||time(probe.checkedAt)>=time(source.lastSuccessAt)))failures.push(view('error','READ_FORBIDDEN',label+'接口无读取权限',probe.checkedAt||null));
|
||||
if(probe?.status==='error'&&(time(source.lastSuccessAt)===null||time(probe.checkedAt)===null||time(probe.checkedAt)>=time(source.lastSuccessAt)))warnings.push(view('pending','READ_UNAVAILABLE',label+'接口暂不可用,等待读取核验',probe.checkedAt||null));
|
||||
const unresolvedFailure=time(source.lastFailureAt)!==null&&(time(source.lastSuccessAt)===null||time(source.lastFailureAt)>=time(source.lastSuccessAt));
|
||||
if(['error','failed','forbidden','login_required'].includes(source.status)||source.status==='running'&&unresolvedFailure)failures.push(view('error','SOURCE_FAILED',label+'读取失败,等待核实或重试',source.lastFailureAt||null));
|
||||
else if(!source.lastSuccessAt)warnings.push(view('pending','SOURCE_PENDING',label+'等待首次完整读取'));
|
||||
else if(!fresh(source.lastSuccessAt,sourceFreshMs))warnings.push(view('pending','SOURCE_STALE',label+'读取结果已超过对账周期',source.lastSuccessAt));
|
||||
}
|
||||
if(account.reason==='AUTH_REQUIRED'||monitoring.status==='login_required'&&account.status!=='healthy')failures.push(view('error','AUTH_REQUIRED','同步需要恢复 BPM 登录'));
|
||||
if(['error','failed'].includes(monitoring.status))failures.push(view('error','LISTENER_FAILED','到达监听不可用',monitoring.lastFailureAt||null));
|
||||
else if(monitoring.status!=='listening')warnings.push(view('pending','LISTENER_PENDING',({polling:'推送暂不可用,正在轮询',connecting:'到达监听正在连接',reconnecting:'到达监听正在重连',busy:'人工登录期间同步暂缓',login_required:'登录会话已恢复,等待监听重连'})[monitoring.status]||'到达监听等待就绪'));
|
||||
return failures[0]||warnings[0]||view('healthy','SYNC_HEALTHY','监听、待办和通知读取正常',monitoring.lastSyncAt||monitoring.sources?.todo?.lastSuccessAt||null);
|
||||
};
|
||||
return {account,sync:sync()};
|
||||
}
|
||||
function connectionSnapshot(connection,{manager,monitor,config,now,sessionFreshMs}={}){
|
||||
const health=manager?.health?.snapshot(connection.id)||connection.health||{};
|
||||
const monitoring=monitor?.snapshot(connection.id)||connection.monitoring||{status:connection.status==='disabled'?'paused':'waiting'};
|
||||
const sessionActivity=manager?.sessionSnapshot?.(connection.id)||connection.sessionActivity;
|
||||
const snapshot={...connection,health,monitoring,...(sessionActivity?{sessionActivity}:{})};
|
||||
let settings={},configUnavailable=false;
|
||||
try{settings=(typeof config==='function'?config():config)||monitor?.scanner?.store?.config?.()||{};}catch{configUnavailable=true;}
|
||||
const connectionState=projectConnectionStatus(snapshot,{config:settings,now,sessionFreshMs:sessionFreshMs??manager?.health?.freshMs,sessionEpoch:manager?.epoch?.(connection.id)});
|
||||
if(configUnavailable&&connection.status!=='disabled')connectionState.sync=view('pending','SYNC_STATE_UNAVAILABLE','暂时无法读取同步配置,等待后台核验');
|
||||
return {...snapshot,connectionState};
|
||||
}
|
||||
module.exports={projectConnectionStatus,connectionSnapshot};
|
||||
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const transitions={
|
||||
connecting:{CONNECTED:'listening',NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'},
|
||||
reconnecting:{CONNECTED:'listening',NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'},
|
||||
listening:{NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'}
|
||||
};
|
||||
class ListenerState{
|
||||
constructor(){this.state='waiting';this.revision=0;}
|
||||
begin(){if(!['waiting','polling','login_required','busy'].includes(this.state))return null;this.state=this.state==='waiting'?'connecting':'reconnecting';return ++this.revision;}
|
||||
current(ticket){return ticket===this.revision&&['connecting','reconnecting','listening'].includes(this.state);}
|
||||
transition(event,ticket){
|
||||
if(event==='STOP'){this.state='stopped';this.revision++;return true;}
|
||||
if(ticket!==undefined&&!this.current(ticket))return false;
|
||||
const next=transitions[this.state]?.[event];if(!next)return false;
|
||||
this.state=next;if(event!=='CONNECTED')this.revision++;return true;
|
||||
}
|
||||
}
|
||||
module.exports={ListenerState};
|
||||
@@ -6,6 +6,7 @@ const { BpmVault } = require('../../platform/security/vault.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs');
|
||||
const { BpmListClient } = require('./list-client.cjs');
|
||||
const {BpmConnectionHealth}=require('./connection-health.cjs');
|
||||
const {SessionState}=require('./session-state.cjs');
|
||||
const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' };
|
||||
const { LOGIN_FORMS, fillSavedForm, automaticSubmitForm } = require('./login-form.cjs');
|
||||
const TTL = 10 * 60 * 1000;
|
||||
@@ -40,6 +41,7 @@ class BpmSessionManager {
|
||||
this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions()));
|
||||
this.probe = probe || this.defaultProbe.bind(this);
|
||||
this.accessClient=accessClient;this.health=new BpmConnectionHealth();this.accessChecks=new Map();this.sessionEpochs=new Map();
|
||||
this.sessionState=new SessionState();this.ensureFlights=new Map();
|
||||
this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.revokedSessionHashes=new Set(); this.stopped = false;
|
||||
}
|
||||
allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } }
|
||||
@@ -63,7 +65,9 @@ class BpmSessionManager {
|
||||
// A password rotation retains valid cookies. Only an actual account change revokes
|
||||
// authentication; first custody can reuse a user's already saved manual login.
|
||||
await this.vault().write('account:'+connection.id,stored);
|
||||
this.sessionState.clearCooldown(connection.id);
|
||||
if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) {
|
||||
this.sessionState.lifecycle(connection.id,'replace');
|
||||
this.health.clear(connection.id);this.sessionEpochs.set(connection.id,this.epoch(connection.id)+1);
|
||||
try{await this.vault().remove(connection.id);await this.closeLease(connection.id);}
|
||||
catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;}
|
||||
@@ -72,7 +76,7 @@ class BpmSessionManager {
|
||||
});
|
||||
}
|
||||
async clearAccount(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); });
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id);this.sessionState.clearCooldown(connection.id); return this.accountMetadata(null); });
|
||||
}
|
||||
async fillSavedAccount(lease) {
|
||||
const stored=await this.vault().read('account:'+lease.id);
|
||||
@@ -83,71 +87,107 @@ class BpmSessionManager {
|
||||
async fillAccount(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); });
|
||||
}
|
||||
async automaticSubmit(lease,stored,submit=false) {
|
||||
async automaticSubmit(lease,stored,submit=false,ticket) {
|
||||
if(this.stopped||this.disabled.has(lease.id))throw error('此连接已停止自动登录。',409);
|
||||
if(submit&&!this.sessionState.consume(ticket))throw error('自动续登许可已失效,请稍后重新检查。',409);
|
||||
return automaticSubmitForm(lease,stored,submit,this.loginForms);
|
||||
}
|
||||
|
||||
async persistLease(lease) {
|
||||
async persistLease(lease,ticket=lease.stateTicket) {
|
||||
if(ticket)this.sessionState.assert(ticket);
|
||||
await this.captureSessions(lease);
|
||||
const storageState=await lease.context.storageState({indexedDB:true});
|
||||
if(ticket)this.sessionState.assert(ticket);
|
||||
await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage});
|
||||
if(ticket)this.sessionState.assert(ticket);
|
||||
this.sessionEpochs.set(lease.id,this.epoch(lease.id)+1);
|
||||
}
|
||||
canPersistVerified(result) {
|
||||
return result.status==='connected' && result.checks.portal.ok;
|
||||
}
|
||||
epoch(id){return this.sessionEpochs.get(id)||0;}
|
||||
observe(id,source,cause){this.health.observe(id,source,cause?cause.status===401?'login_required':cause.status===403?'forbidden':'error':'healthy');}
|
||||
sessionSnapshot(id){return this.sessionState.snapshot(id);}
|
||||
assertGeneration(id,generation){if(this.stopped||this.disabled.has(id)||this.sessionSnapshot(id).generation!==generation)throw error('BPM 会话状态已变化,请刷新后重试。',409);}
|
||||
observe(id,source,cause){
|
||||
if(this.stopped||this.disabled.has(id))return;
|
||||
this.health.observe(id,source,cause?cause.status===401?'login_required':cause.status===403?'forbidden':'error':'healthy');
|
||||
if(!cause||cause.status===401||source==='portal')this.sessionState.observe(id,!cause?'valid':cause.status===401?'expired':'unavailable');
|
||||
}
|
||||
recordSessionResult(id,result){this.observe(id,'portal',result.status==='connected'?null:{status:result.status==='login_required'?401:502});}
|
||||
async checkAccess(connection,principal){
|
||||
this.authorize(connection,principal);const id=connection.id;
|
||||
if(this.accessChecks.has(id)){const result=await this.accessChecks.get(id);this.authorize(connection,principal);return result;}
|
||||
this.authorize(connection,principal);const id=connection.id,generation=this.sessionSnapshot(id).generation;
|
||||
const shared=this.accessChecks.get(id);
|
||||
if(shared){const result=await shared;this.authorize(connection,principal);this.assertGeneration(id,generation);return result;}
|
||||
const task=this.run(id,async()=>{
|
||||
this.authorize(connection,principal);if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用。',409);
|
||||
const saved=await this.vault().read(connection.id),result=await this.accessClient.check(saved?.storageState);this.authorize(connection,principal);
|
||||
this.health.observe(connection.id,'portal',result.status==='connected'?'healthy':result.status==='login_required'?'login_required':'error');
|
||||
this.health.observe(connection.id,'todo',result.todo||'unknown');
|
||||
if(result.storageState&&result.status==='connected')await this.vault().write(connection.id,{...saved,storageState:result.storageState});
|
||||
return {status:result.status,identity:connection.identity||'',checkedAt:result.checkedAt,checks:result.checks};
|
||||
});this.accessChecks.set(id,task);try{return await task;}finally{if(this.accessChecks.get(id)===task)this.accessChecks.delete(id);}
|
||||
this.authorize(connection,principal);this.assertGeneration(id,generation);
|
||||
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
|
||||
const ticket=this.sessionState.begin(id,'checking');
|
||||
try{
|
||||
const saved=await this.vault().read(id),result=await this.accessClient.check(saved?.storageState);
|
||||
this.authorize(connection,principal);this.sessionState.assert(ticket);
|
||||
if(result.storageState&&result.status==='connected')await this.vault().write(id,{...saved,storageState:result.storageState});
|
||||
this.authorize(connection,principal);this.sessionState.assert(ticket);
|
||||
this.recordSessionResult(id,result);this.health.observe(id,'todo',result.todo||'unknown');
|
||||
this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');
|
||||
return {status:result.status,identity:connection.identity||'',checkedAt:result.checkedAt,checks:result.checks};
|
||||
}finally{this.sessionState.abort(ticket);}
|
||||
});
|
||||
this.accessChecks.set(id,task);try{return await task;}finally{if(this.accessChecks.get(id)===task)this.accessChecks.delete(id);}
|
||||
}
|
||||
async ensure(connection,principal) {
|
||||
if(this.accessClient){
|
||||
this.authorize(connection,principal);
|
||||
if(this.health.recent(connection.id))return {status:'connected',identity:connection.identity||'',checkedAt:this.health.snapshot(connection.id).portal.checkedAt,checks:{portal:{ok:true,message:'最近业务请求已验证登录。'}}};
|
||||
const result=await this.checkAccess(connection,principal);if(result.status!=='login_required')return result;
|
||||
async ensure(connection,principal){
|
||||
this.authorize(connection,principal);const id=connection.id,generation=this.sessionSnapshot(id).generation;
|
||||
let flight=this.ensureFlights.get(id);
|
||||
if(!flight||flight.generation!==generation){
|
||||
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
|
||||
flight={generation,promise:this.recoverSession(connection,principal,generation)};this.ensureFlights.set(id,flight);
|
||||
flight.promise.finally(()=>{if(this.ensureFlights.get(id)===flight)this.ensureFlights.delete(id);}).catch(()=>{});
|
||||
}
|
||||
return this.ensureBrowser(connection,principal);
|
||||
const result=await flight.promise;this.authorize(connection,principal);this.assertGeneration(id,generation);return result;
|
||||
}
|
||||
async ensureBrowser(connection,principal) {
|
||||
async recoverSession(connection,principal,generation){
|
||||
if(this.accessClient){
|
||||
if(this.health.recent(connection.id)){this.sessionState.observe(connection.id,'valid');return {status:'connected',identity:connection.identity||'',checkedAt:this.health.snapshot(connection.id).portal.checkedAt,checks:{portal:{ok:true,message:'最近业务请求已验证登录。'}}};}
|
||||
const result=await this.checkAccess(connection,principal);this.assertGeneration(connection.id,generation);
|
||||
if(result.status!=='login_required')return result;
|
||||
}
|
||||
this.assertGeneration(connection.id,generation);return this.ensureBrowser(connection,principal,generation);
|
||||
}
|
||||
async ensureBrowser(connection,principal,generation=this.sessionSnapshot(connection.id).generation){
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409);
|
||||
const lease=await this.create(connection,principal);
|
||||
try {
|
||||
let result=await this.verify(lease);
|
||||
this.authorize(connection,principal);
|
||||
if (this.canPersistVerified(result)) await this.persistLease(lease);
|
||||
if (result.status==='connected') return result;
|
||||
// Network failures and a healthy portal never justify submitting credentials again.
|
||||
if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result;
|
||||
const stored=await this.vault().read('account:'+connection.id);
|
||||
if (!stored) return result;
|
||||
const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; };
|
||||
if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。');
|
||||
await this.readOnlyGoto(lease,this.urls.main);
|
||||
if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。');
|
||||
if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。');
|
||||
// Persist before a request to avoid repeated retries after a crash or failed password.
|
||||
await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()});
|
||||
if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。');
|
||||
await this.settleNavigation(lease);
|
||||
result=await this.verify(lease);this.authorize(connection,principal);
|
||||
if (this.canPersistVerified(result)) {
|
||||
await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored);
|
||||
} else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
|
||||
const id=connection.id;this.authorize(connection,principal);this.assertGeneration(id,generation);
|
||||
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
|
||||
let ticket=this.sessionState.begin(id,'checking');
|
||||
try{
|
||||
const lease=await this.create(connection,principal);let result=await this.verify(lease);
|
||||
this.authorize(connection,principal);this.sessionState.assert(ticket);
|
||||
if(this.canPersistVerified(result))await this.persistLease(lease,ticket);
|
||||
this.recordSessionResult(id,result);this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');
|
||||
if(result.status!=='login_required'||result.checks.portal.message!=='请在此入口完成登录。'||lease.blocked)return result;
|
||||
const stored=await this.vault().read('account:'+id);this.authorize(connection,principal);this.assertGeneration(id,generation);
|
||||
if(!stored)return result;
|
||||
const manual=message=>{if(!result.checks.portal.ok)result.checks.portal.message=message;return result;};
|
||||
const retryAt=Date.parse(stored.nextAttemptAt);
|
||||
if(retryAt>Date.now()){this.sessionState.defer(id,retryAt);return manual('自动登录暂缓,请稍后重试或更新托管账号。');}
|
||||
ticket=this.sessionState.begin(id,'renewing');
|
||||
await this.readOnlyGoto(lease,this.urls.main);this.authorize(connection,principal);this.sessionState.assert(ticket);
|
||||
if(lease.blocked||!this.allowed(lease.page.url())||!await this.automaticSubmit(lease,stored)){
|
||||
this.sessionState.finish(ticket,'expired','manual_required');return manual('需要人工完成验证码或登录验证。');
|
||||
}
|
||||
const nextAttempt=Date.now()+15*60*1000;
|
||||
await this.vault().write('account:'+id,{...stored,nextAttemptAt:new Date(nextAttempt).toISOString()});
|
||||
this.authorize(connection,principal);this.sessionState.reserve(ticket,nextAttempt);
|
||||
if(!await this.automaticSubmit(lease,stored,true,ticket)){
|
||||
this.sessionState.finish(ticket,'expired','manual_required');return manual('需要人工完成登录验证。');
|
||||
}
|
||||
await this.settleNavigation(lease);result=await this.verify(lease);
|
||||
this.authorize(connection,principal);this.sessionState.assert(ticket);
|
||||
if(this.canPersistVerified(result)){
|
||||
await this.persistLease(lease,ticket);delete stored.nextAttemptAt;await this.vault().write('account:'+id,stored);
|
||||
}else if(!result.checks.portal.ok)result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
|
||||
this.authorize(connection,principal);this.sessionState.assert(ticket);this.recordSessionResult(id,result);
|
||||
this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable',result.status==='connected'?null:'manual_required');
|
||||
return result;
|
||||
} finally { await this.closeLease(connection.id); }
|
||||
}finally{this.sessionState.abort(ticket);await this.closeLease(id);}
|
||||
});
|
||||
}
|
||||
async scanArrivals(connection,principal) {
|
||||
@@ -235,7 +275,7 @@ class BpmSessionManager {
|
||||
}
|
||||
invalidateBrowser(browser,pending) {
|
||||
if(this.browserPromise===pending)this.browserPromise=null;
|
||||
for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);lease.context?.close().catch(()=>{});}
|
||||
for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);this.sessionState.abort(lease.stateTicket);lease.context?.close().catch(()=>{});}
|
||||
}
|
||||
async create(connection, principal) {
|
||||
this.authorize(connection,principal);
|
||||
@@ -330,9 +370,14 @@ class BpmSessionManager {
|
||||
async open(connection, principal) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal);
|
||||
this.authorize(connection,principal);
|
||||
return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host };
|
||||
let ticket;
|
||||
try{
|
||||
if(!this.sessions.has(connection.id))ticket=this.sessionState.begin(connection.id,'manual');
|
||||
const lease=this.sessions.has(connection.id)?await this.getLease(connection.id,principal,true):await this.create(connection,principal);
|
||||
if(ticket)lease.stateTicket=ticket;
|
||||
this.authorize(connection,principal);if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);
|
||||
return {active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host};
|
||||
}catch(cause){this.sessionState.abort(ticket);throw cause;}
|
||||
});
|
||||
}
|
||||
async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); }
|
||||
@@ -426,8 +471,10 @@ class BpmSessionManager {
|
||||
this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true);
|
||||
const result=await this.verify(lease);
|
||||
this.authorize(connection,principal);
|
||||
if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);
|
||||
// Failed verification never replaces a previously working credential snapshot.
|
||||
if (this.canPersistVerified(result)) await this.persistLease(lease);
|
||||
this.authorize(connection,principal);if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);this.recordSessionResult(connection.id,result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
@@ -436,14 +483,20 @@ class BpmSessionManager {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
const transient=!this.sessions.has(connection.id);
|
||||
const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true);
|
||||
try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; }
|
||||
finally { if (transient) await this.closeLease(connection.id); }
|
||||
const ticket=transient?this.sessionState.begin(connection.id,'checking'):null;
|
||||
try {
|
||||
const lease=transient?await this.create(connection,principal):await this.getLease(connection.id,principal,true),guard=ticket||lease.stateTicket;
|
||||
const result=await this.verify(lease);this.authorize(connection,principal);if(guard)this.sessionState.assert(guard);
|
||||
if(this.canPersistVerified(result))await this.persistLease(lease,guard);
|
||||
this.authorize(connection,principal);if(guard)this.sessionState.assert(guard);this.recordSessionResult(connection.id,result);
|
||||
if(ticket)this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');return result;
|
||||
} finally {this.sessionState.abort(ticket);if(transient)await this.closeLease(connection.id);}
|
||||
});
|
||||
}
|
||||
async closeLease(id) {
|
||||
const lease=this.sessions.get(id); if (!lease) return;
|
||||
clearTimeout(lease.timer); this.sessions.delete(id);
|
||||
if(lease.stateTicket)this.sessionState.finish(lease.stateTicket,this.sessionSnapshot(id).authentication);
|
||||
await lease.context?.close().catch(()=>{});
|
||||
}
|
||||
async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); }
|
||||
@@ -453,12 +506,14 @@ class BpmSessionManager {
|
||||
for(const hash of revoked)this.revokedSessionHashes.add(hash);
|
||||
await Promise.all([...this.sessions.values()].filter(lease=>revoked.has(crypto.createHash('sha256').update(lease.sessionId).digest('hex'))).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id))));
|
||||
}
|
||||
async suspend(id) { this.disabled.add(id);this.health.clear(id);await this.sessions.get(id)?.context?.close().catch(()=>{}); await this.run(id,()=>this.closeLease(id)); }
|
||||
async resume(id) { await this.run(id,async()=>{this.disabled.delete(id);this.health.clear(id);}); }
|
||||
async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
|
||||
async suspend(id) { this.disabled.add(id);this.sessionState.lifecycle(id,'pause');this.health.clear(id);await this.sessions.get(id)?.context?.close().catch(()=>{}); await this.run(id,()=>this.closeLease(id)); }
|
||||
async resume(id) { await this.run(id,async()=>{this.disabled.delete(id);this.sessionState.lifecycle(id,'resume');this.health.clear(id);}); }
|
||||
async disable(id) { this.disabled.add(id);this.sessionState.lifecycle(id,'stop');this.health.clear(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
|
||||
async shutdown() {
|
||||
this.stopped=true;
|
||||
for(const id of this.sessionState.values.keys())this.sessionState.lifecycle(id,'stop');
|
||||
await Promise.allSettled([...this.operations.values()]);
|
||||
await Promise.allSettled([...this.ensureFlights.values()].map(flight=>flight.promise));
|
||||
await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id)));
|
||||
if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{});
|
||||
this._vault?.destroy();
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
const conflict=()=>Object.assign(new Error('BPM 会话状态已变化,请刷新后重试。'),{status:409});
|
||||
const phases=new Set(['checking','renewing','manual']);
|
||||
const authentication=new Set(['unknown','valid','expired','unavailable']);
|
||||
class SessionState{
|
||||
constructor({clock=()=>Date.now()}={}){this.clock=clock;this.values=new Map();}
|
||||
value(id){if(!this.values.has(id))this.values.set(id,{phase:'idle',authentication:'unknown',generation:0,revision:0,reason:null,retryAt:null});return this.values.get(id);}
|
||||
snapshot(id){const {phase,authentication,generation,revision,reason,retryAt}=this.value(id);return {phase,authentication,generation,revision,reason,retryAt};}
|
||||
begin(id,phase){
|
||||
const state=this.value(id);
|
||||
if(!phases.has(phase)||state.phase!=='idle')throw conflict();
|
||||
if(phase==='renewing'&&(state.authentication!=='expired'||state.retryAt>this.clock()))throw conflict();
|
||||
state.phase=phase;state.revision++;state.reserved=false;state.consumed=false;
|
||||
return Object.freeze({id,generation:state.generation,revision:state.revision,phase});
|
||||
}
|
||||
current(ticket){if(!ticket)return false;const state=this.value(ticket.id);return state.generation===ticket.generation&&state.revision===ticket.revision&&state.phase===ticket.phase;}
|
||||
assert(ticket){if(!this.current(ticket))throw conflict();}
|
||||
reserve(ticket,retryAt){this.assert(ticket);const state=this.value(ticket.id);if(state.phase!=='renewing'||state.reserved||!Number.isFinite(retryAt)||retryAt<=this.clock())throw conflict();state.retryAt=retryAt;state.reason='cooldown';state.reserved=true;}
|
||||
consume(ticket){if(!this.current(ticket))return false;const state=this.value(ticket.id);if(state.phase!=='renewing'||!state.reserved||state.consumed)return false;state.consumed=true;return true;}
|
||||
finish(ticket,result,reason=null){
|
||||
if(!this.current(ticket))return false;
|
||||
if(!authentication.has(result))throw conflict();
|
||||
const state=this.value(ticket.id);state.phase='idle';state.authentication=result;state.reason=reason;state.revision++;
|
||||
if(result==='valid')state.retryAt=null;
|
||||
return true;
|
||||
}
|
||||
abort(ticket){if(this.current(ticket)){const state=this.value(ticket.id);state.phase='idle';state.revision++;}}
|
||||
observe(id,result){const state=this.value(id);if(['paused','stopped'].includes(state.phase)||!authentication.has(result))return false;state.authentication=result;if(result==='valid'){state.retryAt=null;state.reason=null;}return true;}
|
||||
defer(id,retryAt,reason='cooldown'){const state=this.value(id);if(state.phase!=='idle'||!Number.isFinite(retryAt))throw conflict();state.retryAt=retryAt;state.reason=reason;}
|
||||
clearCooldown(id){const state=this.value(id);if(!['paused','stopped'].includes(state.phase)){state.retryAt=null;state.reason=null;}}
|
||||
lifecycle(id,event){
|
||||
const state=this.value(id);
|
||||
if(!['pause','resume','replace','stop'].includes(event)||state.phase==='stopped')return false;
|
||||
state.generation++;state.revision++;state.phase=event==='pause'?'paused':event==='stop'?'stopped':'idle';state.authentication='unknown';state.retryAt=null;state.reason=event;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
module.exports={SessionState};
|
||||
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../../shared/redact.cjs');
|
||||
const {monitorEventLoopDelay}=require('node:perf_hooks');
|
||||
const {connectionSnapshot}=require('../bpm/connection-status.cjs');
|
||||
function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;}
|
||||
const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null;
|
||||
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
|
||||
@@ -23,11 +24,16 @@ class RuntimeHealth {
|
||||
}
|
||||
collect(){
|
||||
const groups=[],safe=(key,title,link,read)=>{try{const items=read();groups.push({key,title,link,status:groupStatus(items),items});}catch{groups.push({key,title,link,status:'unknown',items:[],message:'暂时无法读取此模块状态,请到对应页面核实。'});}};
|
||||
let connections=[];
|
||||
let connections=[],connectionViews=[];
|
||||
safe('bpm','BPM 连接','#bpm',()=>{connections=this.sources.workspace?.snapshot().connections||[];return connections.map(c=>{
|
||||
const checkedAt=timestamp(c.checkedAt),status=c.status==='disabled'?'disabled':c.status==='connected'?'healthy':['error','login_required'].includes(c.status)?'error':'pending';
|
||||
return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,detail:status==='error'?'上次验证失败或需要重新登录。':status==='healthy'?'上次已验证登录;连接由后台托管检查。':'尚未验证或已停用。',...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:status==='error'?checkedAt:null})};
|
||||
const config=()=>this.sources.monitor?.scanner?.store?.config?.()||this.sources.scanner?.store.status().config||{};
|
||||
const snapshot=connectionSnapshot(c,{manager:this.sources.bpmSessions,monitor:this.sources.monitor,config,now:this.clock()});connectionViews.push(snapshot);
|
||||
const account=snapshot.connectionState.account,checkedAt=timestamp(account.checkedAt),status=account.status;
|
||||
return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,reason:account.reason,detail:account.message,...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:['AUTH_REQUIRED','SESSION_UNAVAILABLE'].includes(account.reason)?checkedAt:null})};
|
||||
});});
|
||||
safe('bpm-sync','BPM 同步','#bpm',()=>connectionViews.map(c=>{
|
||||
const sync=c.connectionState.sync;return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status:sync.status,reason:sync.reason,checkedAt:timestamp(sync.checkedAt),detail:sync.message};
|
||||
}));
|
||||
safe('scan','BPM 扫描','#records',()=>{
|
||||
const {config={},runs=[]}=this.sources.scanner?.store.status()||{};
|
||||
for(const r of runs)this.remember('scan',r.connectionId+':'+(r.kind||'inform'),{successAt:r.status==='success'?r.finishedAt:null,failureAt:['error','interrupted'].includes(r.status)?r.finishedAt:null});
|
||||
@@ -63,7 +69,7 @@ class RuntimeHealth {
|
||||
return groups;
|
||||
}
|
||||
snapshot(user){
|
||||
const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','scan','listener','handoff','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};});
|
||||
const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','bpm-sync','scan','listener','handoff','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};});
|
||||
let saved;try{saved=readSupervisor(this.stateDir);}catch{saved={state:null,events:[],autostart:null};}
|
||||
const s=saved.state,managed=Boolean(this.instanceId&&s?.childInstanceId===this.instanceId),fresh=managed&&now-Date.parse(s.updatedAt)<45000;
|
||||
const guard=managed?{status:fresh?s.status:'stale',heartbeatAt:s.heartbeatAt,updatedAt:s.updatedAt,restartCount:s.restartCount,childStartedAt:s.childStartedAt,reason:s.reason,nextRestartAt:s.nextRestartAt,events:saved.events.map(e=>({at:e.at,kind:e.kind,code:e.detail.code,delayMs:e.detail.delayMs,reason:e.detail.reason}))}:{status:'unmanaged',restartCount:0,events:[]};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// This router is called only after dashboard authentication and same-origin validation.
|
||||
const {connectionSnapshot}=require('../bpm/connection-status.cjs');
|
||||
async function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions,bpmMonitor,bpmLifecycle,orderRules}){
|
||||
if(!workspace)return false;
|
||||
const members=()=>store.users();
|
||||
if(route==='/api/workspace'||route.startsWith('/api/exceptions'))workspace.syncBusinessIssues?.(orderRules?.all('business-issues')||[],members());
|
||||
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>({...c,health:bpmSessions?.health?.snapshot(c.id)||{},monitoring:bpmMonitor?.snapshot(c.id)||{status:c.status==='disabled'?'paused':'waiting'}}));reply(200,snapshot);return true;}
|
||||
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>connectionSnapshot(c,{manager:bpmSessions,monitor:bpmMonitor}));reply(200,snapshot);return true;}
|
||||
if(method!=='POST')return false;
|
||||
if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;}
|
||||
if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;}
|
||||
|
||||
Reference in new issue
Block a user