Files
bpq_gui/forwarding-scheduler.mjs
T

32 lines
2.8 KiB
JavaScript

import {readFile,writeFile,rename} from 'node:fs/promises';
import path from 'node:path';
export class ForwardingScheduler {
constructor(config,dir,client,{clock=Date.now}={}){
this.client=client;this.clock=clock;this.file=path.join(dir,'forwarding-schedule.state.json');this.jobs={};this.busy=false;
this.schedules=(config.forwardingSchedules||[]).map(s=>{
if(!client.routes.some(r=>r.id===s.route)||!Number.isInteger(s.intervalSeconds)||s.intervalSeconds<300||s.intervalSeconds>86400||typeof s.enabled!=='boolean')throw Error('Programmazione forwarding non valida');
if(s.hours){const h=s.hours;if(!Number.isInteger(h.start)||!Number.isInteger(h.end)||h.start<0||h.end>24||h.start>=h.end)throw Error('Orari forwarding non validi');new Intl.DateTimeFormat('en',{timeZone:h.timeZone}).format();}
return {...s,intervalMs:s.intervalSeconds*1000};
});
if(new Set(this.schedules.map(s=>s.route)).size!==this.schedules.length)throw Error('Programmazione forwarding duplicata');
this.init=this.restore();this.timer=setInterval(()=>this.tick().catch(()=>{}),5000);this.timer.unref();
}
allowed(schedule,now){if(!schedule.hours)return true;const h=schedule.hours,hour=Number(new Intl.DateTimeFormat('en-GB',{timeZone:h.timeZone,hour:'2-digit',hourCycle:'h23'}).format(new Date(now)));return hour>=h.start&&hour<h.end;}
boundary(schedule,now){let next=(Math.floor(now/schedule.intervalMs)+1)*schedule.intervalMs;for(let i=0;i<600&& !this.allowed(schedule,next);i++)next+=schedule.intervalMs;return next;}
async restore(){try{this.jobs=JSON.parse(await readFile(this.file,'utf8'));}catch{}
const now=this.clock();for(const s of this.schedules){const old=this.jobs[s.route];if(!old||old.intervalSeconds!==s.intervalSeconds||old.nextAt<now-300000)this.jobs[s.route]={intervalSeconds:s.intervalSeconds,nextAt:this.boundary(s,now)};else if(!this.allowed(s,old.nextAt))old.nextAt=this.boundary(s,old.nextAt);}
}
async persist(){await writeFile(this.file+'.tmp',JSON.stringify(this.jobs));await rename(this.file+'.tmp',this.file);}
snapshot(){return this.schedules.map(s=>({...s,...this.jobs[s.route],nextAt:s.enabled?new Date(this.jobs[s.route]?.nextAt||this.boundary(s,this.clock())).toISOString():null,enabled:s.enabled}));}
async tick(){await this.init;if(this.busy)return;this.busy=true;
try{for(const s of this.schedules){const j=this.jobs[s.route],now=this.clock();if(!s.enabled||now<j.nextAt)continue;
// Persist the next boundary before dispatch: a restart must not replay a call.
j.nextAt=this.boundary(s,now);if(!this.allowed(s,now)){await this.persist();continue;}j.lastAttemptAt=new Date(now).toISOString();j.error=null;await this.persist();
try{await this.client.startRoute(s.route);j.lastRequestedAt=new Date(now).toISOString();}
catch(error){j.error=error.message;}
await this.persist();
}}finally{this.busy=false;}
}
}