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({...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