feat: unify BPM health and guard session recovery with state machines

This commit is contained in:
阿白叔 committed 2026-10-24 14:49:15 +08:00
1 parent 97e06328c3
commit 42d19c707d
23 files changed
+681 -90

No files matched your search

+9 -6
View File
@@ -1,7 +1,7 @@
'use strict';
window.BpmLogin=(()=>{
let active=null,releasing=null,releasePending=Promise.resolve();
const statuses={disconnected:['未连接','secondary'],unchecked:['待检查','yellow'],login_required:['待登录','yellow'],connected:['已连接','green'],disabled:['已停用','secondary'],error:['检查失败','red']};
const observation=(c,kind)=>c.connectionState?.[kind]||{status:'pending',message:'等待后台更新状态'};
function dispose(options={}){const previous=active||releasing;active=null;if(previous){releasing=previous;releasePending=previous.dispose(options);releasePending.finally(()=>{if(releasing===previous)releasing=null;});}return releasePending;}
async function mount(container,{api,esc,formatDate,notify,user,isActive=()=>true}){
await dispose();
@@ -12,7 +12,7 @@ window.BpmLogin=(()=>{
const $=selector=>container.querySelector(selector);
const authorized=c=>user.role==='admin'||(user.role==='operator'&&c.owner===user.username);
const route=(id,action)=>`/connections/${encodeURIComponent(id)}/${action}`;
const status=c=>{const [label,color]=statuses[c.status]||statuses.error;return `<span class="badge bg-${color}-lt">${label}</span>`;};
const status=(c,kind='account')=>{const state=observation(c,kind),[color,label]=({healthy:['green','健康'],error:['red','异常'],pending:['yellow','警告'],paused:['yellow','已暂停']})[state.status]||['yellow','待确认'];return `<span class="bpm-account-status bpm-status-${color}"><span class="bpm-status-light" aria-hidden="true"></span>${kind==='account'?'账号':'同步'} · ${label}</span>`;};
function feedback(message,type='danger'){if(!live())return;const el=$('[data-bpm-feedback]');if(el){el.hidden=false;el.className=`alert alert-${type}`;el.textContent=message;}notify(message,type);}
function release(r,{unload=false}={}){
r.closed=true;clearTimeout(r.timer);r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
@@ -28,7 +28,7 @@ window.BpmLogin=(()=>{
if(!valid(r)||r.busy)return;
r.queue=r.queue.then(()=>{if(valid(r)&&!r.failed)return api(route(r.id,'login/input'),action);}).catch(()=>{if(valid(r)){r.failed=true;feedback('输入未送达,请关闭后重新打开登录窗口。');}});
}
function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();}
function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id,connectionState:saved.connectionState||null}:c);drawCards();}
function rememberAccount(id,result){const metadata={configured:result.configured===true,username:typeof result.username==='string'?result.username:'',updatedAt:result.updatedAt||null};accounts.set(id,metadata);return metadata;}
function loadAccount(id){
if(accounts.has(id))return Promise.resolve(accounts.get(id));
@@ -84,14 +84,15 @@ window.BpmLogin=(()=>{
return row(label,info.status||'待确认',info.lastSuccessAt)+row(label+'最近失败',info.lastFailureAt?'失败':'无',info.lastFailureAt)+row(label+'重试时间',info.retryAt?formatDate(info.retryAt):'无');
};
const delivery=monitoring.delivery||{};
return row('登录会话',portal?(Date.now()-Date.parse(portal.checkedAt)>300000?'上次检查'+(state[portal.status]||'待确认'):state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)
return '<p class="small mb-2">'+esc(observation(c,'account').message)+'</p><div class="bpm-sync-summary mb-2"><span data-sync-status>'+status(c,'sync')+'</span><span class="small">'+esc(observation(c,'sync').message)+'</span></div><details class="bpm-status-details"><summary>状态详情</summary>'+row('登录会话',portal?(state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)
+(c.sessionActivity?row('会话操作',({idle:'空闲',checking:'检查中',renewing:'自动续登中',manual:'人工登录中',paused:'已暂停',stopped:'已停止'})[c.sessionActivity.phase]||'待确认')+(Number.isFinite(c.sessionActivity.retryAt)?row('续登重试',formatDate(new Date(c.sessionActivity.retryAt).toISOString())):''):'')
+row('订单接口',state[health.todo?.status]||'尚未检查',health.todo?.checkedAt)
+row('到达监听',monitor[monitoring.status]||'等待就绪',monitoring.lastSyncAt)
+source('todo','待办源读取')+source('inform','通知源读取')
+row('下一完整对账',monitoring.nextReconcileAt?formatDate(monitoring.nextReconcileAt):'未排队')
+row('本地执行器投递',(delivery.status||'尚无投递')+' · 待交付 '+(delivery.pending||0),delivery.lastSuccessAt)
+row('投递重试',delivery.retryAt?formatDate(delivery.retryAt):'无')
+(delivery.message?row('投递说明',delivery.message):'');
+(delivery.message?row('投递说明',delivery.message):'')+'</details>';
}
async function refreshStatus(){
if(!live())return;
@@ -99,7 +100,7 @@ window.BpmLogin=(()=>{
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return;
const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version,c.owner]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version,c.owner]));connections=rows;
if(changed&&!remote&&!container.querySelector('[data-account-form]')&&!window.PageLifecycle?.dirty())drawCards();
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health)health.innerHTML=observations(c);}
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health){const expanded=health.querySelector('details')?.open;health.innerHTML=observations(c);if(expanded)health.querySelector('details').open=true;}}
}catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);}
}
function ownerForm(c){
@@ -108,8 +109,10 @@ window.BpmLogin=(()=>{
}
function drawCards(){
if(!live())return;
const expanded=new Set([...container.querySelectorAll('[data-connection-health]')].filter(el=>el.querySelector('details')?.open).map(el=>el.dataset.connectionHealth));
container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());
$('#bpm-list').innerHTML=connections.length?connections.map(c=>`<article class="card mb-3"><div class="card-header"><span class="connection-avatar" aria-hidden="true">B</span><div class="flex-fill"><h3 class="card-title mb-1">${esc(c.name)}</h3><span class="text-secondary small">负责人 ${esc(c.owner||'未分配')}</span></div><span data-connection-status="${esc(c.id)}">${status(c)}</span></div><div class="card-body"><div class="connection-url"><span class="text-secondary">新版门户</span><span>bpmn.skyworthdigital.com</span></div>${c.identity?`<div class="small mt-2">登录账号 ${esc(c.identity)}</div>`:''}${c.checkedAt?`<div class="small text-secondary mt-2">上次检查 ${esc(formatDate(c.checkedAt))}</div>`:''}<div class="bpm-checks mt-3" data-connection-health="${esc(c.id)}">${observations(c)}</div></div>${c.status!=='disabled'&&authorized(c)?`<div class="card-footer d-flex gap-2 flex-wrap">${data.capabilities?.remoteLogin?`<button class="btn btn-primary" data-login="${esc(c.id)}" ${remote?'disabled':''}>远程登录</button><button class="btn" data-check="${esc(c.id)}" ${remote?'disabled':''}>检查连接</button>`:'<span class="text-secondary small">远程登录未启用</span>'}<button class="btn" data-account="${esc(c.id)}" ${remote?'disabled':''}>${accounts.get(c.id)?.configured?'管理账号':'开启自动续登'}</button>${user.role==='admin'?`<button class="btn btn-outline-danger ms-auto" data-disable="${esc(c.id)}" ${remote?'disabled':''}>停用连接</button>`:''}</div><div class="bpm-account-summary small text-secondary" data-account-summary="${esc(c.id)}">${esc(accountSummary(c))}</div><div class="bpm-account-panel" data-account-panel hidden></div>`:c.status==='disabled'&&user.role==='admin'?`<div class="card-footer d-flex gap-2"><button class="btn btn-primary" data-enable="${esc(c.id)}" ${remote?'disabled':''}>启用连接</button><span class="small text-secondary align-self-center">账号、会话和历史保留</span><button class="btn btn-outline-danger ms-auto" data-delete="${esc(c.id)}" ${remote?'disabled':''}>删除</button></div>`:''}${ownerForm(c)}</article>`).join(''):'<div class="card"><div class="workspace-empty"><h3>还没有 BPM 连接</h3><p class="text-secondary mb-0">请管理员添加连接并指定负责人。</p></div></div>';
container.querySelectorAll('[data-connection-health]').forEach(el=>{if(expanded.has(el.dataset.connectionHealth))el.querySelector('details').open=true;});
container.querySelectorAll('[data-owner-transfer]').forEach(form=>form.onsubmit=async event=>{
event.preventDefault();if(remote||mutationBusy)return;
const c=connections.find(c=>c.id===form.dataset.ownerTransfer),button=form.querySelector('button');