feat: show application version and check Gitea releases

This commit is contained in:
abaishu0730 committed 2026-10-27 14:27:37 +08:00
1 parent dcea4a063f
commit f161322532
11 files changed
+273 -7

No files matched your search

+3 -1
View File
@@ -28,6 +28,8 @@ const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs')
const { BpmOrderProvider } = require('../modules/bpm/order-provider.cjs');
const { OrderArchiveProvider } = require('../modules/storage/order-archive.cjs');
const { OrderExecutionCoordinator } = require('../modules/order-execution/coordinator.cjs');
const { createUpdateChecker } = require('../modules/system-update/checker.cjs');
const appVersion=require('../../package.json').version;
async function closeServer(server){
if(!server)return;
@@ -104,7 +106,7 @@ async function main(options = {}) {
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,renderSnapshot:options.renderSnapshot});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true,updateChecker:createUpdateChecker({currentVersion:appVersion})});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();bpmMonitor.start();
health.start();
orderExecution.start();
+1 -1
View File
@@ -27,7 +27,7 @@ function createServer(options) {
const supplied = Buffer.from(String(request.headers['x-order-token'] || ''));
const expected = Buffer.from(options.token);
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:require('../../package.json').version,busy});
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:'未知操作。'});
+5 -1
View File
@@ -16,7 +16,7 @@ const {createAuth}=require('../modules/dashboard/auth.cjs');
const {prepareRequest,readBody}=require('./request.cjs');
const {BpmConnectionLifecycle}=require('../modules/bpm/connection-lifecycle.cjs');
function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false}) {
function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false,updateChecker}) {
const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null;
const auth=createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle});
let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;}
@@ -36,6 +36,10 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
const authResult=await auth.authenticate({request,response,route,body,reply,fail,encryptedTransport});
if(authResult.handled)return;
const {user,token}=authResult;
if(route==='/api/update' && request.method==='GET') {
const result=await (updateChecker|| (async()=>({status:'unavailable',currentVersion:require('../../package.json').version,latest:null})))();
return reply(200,result);
}
if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));}
if(await require('../modules/dashboard/maintenance.cjs').maintenanceApi({store,outputDir,user,route,method:request.method,reply,response}))return;
if(route==='/api/order-rules'&&request.method==='GET'&&url.searchParams.get('view')==='summary')workspace?.syncBusinessIssues?.(orderRules?.all('business-issues')||[],store.users());
+81
View File
@@ -0,0 +1,81 @@
'use strict';
const REPOSITORY_URL='https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation';
const RELEASES_API_URL='https://git.simgreek.com/api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest';
const VERSION_PATTERN=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const MAX_RESPONSE_BYTES=256*1024;
function versionParts(value){
const match=typeof value==='string'&&value.length<=200&&VERSION_PATTERN.exec(value.trim());
if(!match)return null;
const pre=match[4]?match[4].split('.'):[];
if(pre.some(part=>/^0\d+$/.test(part)))return null;
return {major:BigInt(match[1]),minor:BigInt(match[2]),patch:BigInt(match[3]),pre};
}
function compareIdentifiers(a,b){
const an=/^\d+$/.test(a),bn=/^\d+$/.test(b);
if(an&&bn)return BigInt(a)>BigInt(b)?1:BigInt(a)<BigInt(b)?-1:0;
if(an!==bn)return an?-1:1;
return a>b?1:a<b?-1:0;
}
function compareVersions(left,right){
const a=versionParts(left),b=versionParts(right);
if(!a||!b)throw new Error('版本必须是 x.y.z 格式。');
for(const key of ['major','minor','patch'])if(a[key]!==b[key])return a[key]>b[key]?1:-1;
if(!a.pre.length&&!b.pre.length)return 0;
if(!a.pre.length)return 1;
if(!b.pre.length)return -1;
for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){
if(i>=a.pre.length)return -1;
if(i>=b.pre.length)return 1;
const result=compareIdentifiers(a.pre[i],b.pre[i]);
if(result)return result>0?1:-1;
}
return 0;
}
function safeReleaseUrl(value,repositoryUrl=REPOSITORY_URL){
try{
const url=new URL(value),base=new URL(repositoryUrl);
if(url.username||url.password||url.origin!==base.origin||!url.pathname.startsWith(base.pathname+'/releases/'))return '';
return url.href;
}catch{return '';}
}
function parseRelease(release,currentVersion,{repositoryUrl=REPOSITORY_URL}={}){
const base={currentVersion,latest:null};
if(!release||typeof release!=='object'||Array.isArray(release)||typeof release.tag_name!=='string')return {...base,status:'unavailable'};
const version=release.tag_name.trim().replace(/^v/i,''),parts=versionParts(version);
if(!parts)return {...base,status:'unavailable'};
if(release.draft===true||release.prerelease===true||parts.pre.length)return {...base,status:'none'};
if(compareVersions(version,currentVersion)<=0)return {...base,status:'current'};
const publishedAt=release.published_at?new Date(release.published_at):null;
return {status:'update-available',currentVersion,latest:{version,name:String(release.name||release.tag_name||version).slice(0,200),notes:String(release.body||'').slice(0,20000),url:safeReleaseUrl(release.html_url,repositoryUrl),publishedAt:publishedAt&&!Number.isNaN(publishedAt.getTime())?publishedAt.toISOString():null}};
}
async function readRelease(response){
const reader=response.body?.getReader();
if(!reader)throw Error('发行版本响应为空。');
const chunks=[];let bytes=0;
try{
while(true){
const {value,done}=await reader.read();if(done)break;
bytes+=value.byteLength;if(bytes>MAX_RESPONSE_BYTES)throw Error('发行版本响应过大。');
chunks.push(Buffer.from(value));
}
return JSON.parse(Buffer.concat(chunks,bytes).toString('utf8'));
}catch(error){await reader.cancel().catch(()=>{});throw error;}
finally{reader.releaseLock();}
}
function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=RELEASES_API_URL,repositoryUrl=REPOSITORY_URL,timeoutMs=5000}={}){
if(!versionParts(currentVersion))throw new Error('当前版本必须是 x.y.z 格式。');
return async function checkForUpdate(){
const base={currentVersion,latest:null};
if(typeof fetchImpl!=='function')return {...base,status:'unavailable'};
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutMs);
try{
const response=await fetchImpl(apiUrl,{headers:{Accept:'application/json'},redirect:'error',credentials:'omit',signal:controller.signal});
if(!response.ok){await response.body?.cancel();return {...base,status:response.status===404?'none':'unavailable'};}
return parseRelease(await readRelease(response),currentVersion,{repositoryUrl});
}catch{return {...base,status:'unavailable'};}
finally{clearTimeout(timer);}
};
}
module.exports={REPOSITORY_URL,RELEASES_API_URL,compareVersions,parseRelease,createUpdateChecker};