import {randomUUID} from 'node:crypto'; // All jobs own their domain transactions. The scheduler leases due slots only; // running it manually never advances a calendar or bypasses a financial cutoff. export class CentralScheduler{ constructor(db,tasks,{clock=Date.now}={}){this.db=db;this.tasks=tasks;this.clock=clock;this.stopped=false;} async status(){return this.db.query('SELECT task_key,last_slot,succeeded_at,lease_until,last_error FROM pb_scheduler_tasks ORDER BY task_key');} async runDue(){const results=[]; for(const task of this.tasks){ if(this.stopped)break;const now=this.clock(),slot=task.slot(now);if(slot===null)continue; const token=randomUUID(); const claimed=await this.db.transaction(async tx=>{ await tx.query("INSERT INTO pb_scheduler_tasks(task_key,last_slot,succeeded_at,lease_token,lease_until,last_error) VALUES(?,-1,0,'',0,'') ON DUPLICATE KEY UPDATE task_key=VALUES(task_key)",[task.key]); const row=await tx.first('SELECT * FROM pb_scheduler_tasks WHERE task_key=? FOR UPDATE',[task.key]); if(Number(row.last_slot)>=slot||Number(row.lease_until)>now)return false; await tx.query('UPDATE pb_scheduler_tasks SET lease_token=?,lease_until=? WHERE task_key=?',[token,now+300000,task.key]);return true; }); if(!claimed){results.push({task:task.key,state:'not_due_or_running'});continue;} try{ const result=await task.run(slot); if(result?.failed)throw Error('Task requires attention'); const saved=await this.db.query("UPDATE pb_scheduler_tasks SET last_slot=?,succeeded_at=?,lease_token='',lease_until=0,last_error='' WHERE task_key=? AND lease_token=?",[slot,this.clock(),task.key,token]); results.push({task:task.key,state:saved.affectedRows?'completed':'retry_pending'}); }catch{ await this.db.query("UPDATE pb_scheduler_tasks SET lease_token='',lease_until=0,last_error='Task requires attention' WHERE task_key=? AND lease_token=?",[task.key,token]); results.push({task:task.key,state:'retry_pending'}); } }return {tasks:results}; } start({logger=console}={}){ let timer;const run=async()=>{try{const result=await this.runDue();if(result.tasks.some(t=>t.state==='retry_pending'))logger.error('Central scheduler: a task requires attention.');}catch{logger.error('Central scheduler requires attention.');}finally{if(!this.stopped){timer=setTimeout(run,60000);timer.unref();}}}; timer=setTimeout(run,1000);timer.unref();return()=>{this.stopped=true;clearTimeout(timer);}; } }