@stacksjs/scheduler 0.75.701 → 0.75.706

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/schedule.js +1 -1
  2. package/package.json +14 -14
package/dist/schedule.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{closeSync,mkdirSync,openSync,readFileSync,renameSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{runNamedAction}from"@stacksjs/action-runner";import{log,runCommand}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{parse}from"@stacksjs/cron";import{frameworkPath}from"@stacksjs/path";import{job as queuedJob,runJob}from"@stacksjs/queue";import{claimSchedulerSlot}from"./scheduler-claims";import{acquireSchedulerLock}from"./scheduler-lock";function notificationTaskName(...parts){const canonical=JSON.stringify(parts,(_key,value)=>{if(typeof value==="bigint")return`${value}n`;if(typeof value==="function")return`[function ${value.name}]`;if(value&&typeof value==="object"&&!Array.isArray(value))return Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)));return value});return`notification-${createHash("sha256").update(canonical).digest("hex").slice(0,12)}`}const SKIPPED_BY_LOCK=Symbol("skipped-by-lock");function toWindowDate(value,label){const date=value instanceof Date?new Date(value.getTime()):new Date(value);if(Number.isNaN(date.getTime()))throw new Error(`between(): ${label} is not a valid date: ${String(value)}`);return date}export class Schedule{static jobs=new Map;static scheduledKeys=new Map;cronPattern="";intervalMs=null;timezone=null;task;static lockDir=frameworkPath("locks");static stateFile=frameworkPath("runtime/scheduler-state.json");static historyFile=defaultHistoryFile();static activeLocks=new Map;static inFlight=new Map;static inProcessRuns=new Map;shouldPreventOverlap=false;allowOverlap=false;overlapExpiresAfterMinutes=24*60;shouldRunOnOneServer=false;shouldRunInBackground=false;outputPath=null;outputAppend=false;handlesOwnOutput=false;jobName=null;dispatchQueue=null;options={};constructor(task){this.task=task;queueMicrotask(()=>{try{this.start()}catch(error){log.error(`Failed to start scheduled task: ${error}`)}})}get pattern(){return this.cronPattern}cronFields(){const fields=this.cronPattern.trim().split(/\s+/);return fields.length===5?fields:["0","0","*","*","*"]}setTimeOfDay(minute,hour){const[,,dayOfMonth,month,dayOfWeek]=this.cronFields();this.releaseInterval();this.cronPattern=`${minute} ${hour} ${dayOfMonth} ${month} ${dayOfWeek}`;return this}setDays(dayOfMonth,month,dayOfWeek){const[minute,hour]=this.cronFields();this.releaseInterval();this.cronPattern=`${minute} ${hour} ${dayOfMonth} ${month} ${dayOfWeek}`;return this}releaseInterval(){this.intervalMs=null}everySecond(){this.intervalMs=1000;this.cronPattern="@every_second";return this}everyMinute(){return this.setTimeOfDay("*","*")}everyTwoMinutes(){return this.setTimeOfDay("*/2","*")}everyFiveMinutes(){return this.setTimeOfDay("*/5","*")}everyTenMinutes(){return this.setTimeOfDay("*/10","*")}everyThirtyMinutes(){return this.setTimeOfDay("*/30","*")}everyHour(){return this.setTimeOfDay("0","*")}everyDay(){return this.setDays("*","*","*")}hourly(){return this.setTimeOfDay("0","*")}daily(){return this.setDays("*","*","*")}weekly(){return this.setDays("*","*","0")}monthly(){return this.setDays("1","*","*")}yearly(){return this.setDays("1","1","*")}annually(){return this.setDays("1","1","*")}cron(expression){const fields=String(expression).trim().split(/\s+/).filter(Boolean);if(fields.length===6){const[seconds,...rest]=fields;if(rest.every((field)=>field==="*")){const step=seconds==="*"?1:Number(/^\*\/(\d+)$/.exec(seconds)?.[1]);if(Number.isInteger(step)&&step>=1&&step<60&&60%step===0){this.intervalMs=step*1000;this.cronPattern=step===1?"@every_second":`@every_${step}_seconds`;return this}}if(seconds!=="0")throw new Error(`cron(): '${expression}' runs on particular seconds, which the scheduler cannot do. Use '*' or '*/N' (N dividing 60) with every other field '*', or a seconds field of 0`);fields.shift()}if(fields.length!==5)throw new Error(`cron(): '${expression}' is not a cron expression; expected 5 fields, or 6 with leading seconds`);const pattern=fields.join(" ");let next;try{next=parse(pattern,Date.now(),{tz:"UTC"})}catch(error){throw new Error(`cron(): '${expression}' is not a valid cron expression: ${error instanceof Error?error.message:String(error)}`)}if(!next)throw new Error(`cron(): '${expression}' never matches a date`);this.intervalMs=null;this.cronPattern=pattern;return this}dailyAt(time){return this.daily().at(time)}weekdays(){return this.setDays("*","*","1-5")}onDays(days){if(!Array.isArray(days)||days.length===0){throw new Error(`onDays() requires a non-empty array; got ${JSON.stringify(days)}`)}for(const d of days){if(!Number.isInteger(d)||d<0||d>6){throw new Error(`onDays(): each day must be an integer 0-6 (Sun-Sat). Got ${d}`)}}return this.setDays("*","*",days.join(","))}at(time){const parts=time.split(":");if(parts.length!==2||parts[0]===""||parts[1]===""){throw new Error(`Invalid time format "${time}". Expected "HH:MM" (e.g., "14:30")`)}const[hour,minute]=parts.map(Number);if(hour===undefined||minute===undefined||Number.isNaN(hour)||Number.isNaN(minute)||hour<0||hour>23||minute<0||minute>59){throw new Error(`Invalid time "${time}". Hour must be 0-23, minute must be 0-59`)}return this.setTimeOfDay(String(minute),String(hour))}setTimeZone(timezone){this.timezone=timezone;this.options.timezone=timezone;return this}withErrorHandler(handler){this.options.catch=handler;return this}withMaxRuns(runs){this.options.maxRuns=runs;return this}withProtection(callback){this.options.protect=callback||true;return this}allowOverlapping(){this.allowOverlap=true;return this}withName(name){this.options.name=name;return this}withContext(context){this.options.context=context;return this}withInterval(seconds){if(typeof seconds!=="number"||!Number.isFinite(seconds)||seconds<=0)throw new Error(`withInterval() takes a positive number of seconds; got ${String(seconds)}`);this.options.interval=seconds;return this}between(startAt,stopAt){const start=toWindowDate(startAt,"startAt");const stop=toWindowDate(stopAt,"stopAt");if(stop.getTime()<=start.getTime())throw new Error(`between(): stopAt (${stop.toISOString()}) must be after startAt (${start.toISOString()})`);this.options.startAt=start;this.options.stopAt=stop;return this}onQueue(queue){if(this.jobName===null)throw new Error("onQueue() applies to schedule.job(...) only: an action, command or callback has no job to dispatch");if(typeof queue!=="string"||queue.trim()==="")throw new Error(`onQueue() takes a queue name; got ${JSON.stringify(queue)}`);this.dispatchQueue=queue;return this}withoutOverlapping(expiresAfterMinutes){this.shouldPreventOverlap=true;if(expiresAfterMinutes!==undefined)this.overlapExpiresAfterMinutes=expiresAfterMinutes;return this}onOneServer(){this.shouldRunOnOneServer=true;return this}runInBackground(){this.shouldRunInBackground=true;return this}sendOutputTo(path){this.outputPath=path;this.outputAppend=false;return this}appendOutputTo(path){this.outputPath=path;this.outputAppend=true;return this}async runMissed(opts){if(!this.cronPattern||this.intervalMs!==null){log.warn("[scheduler] runMissed() requires a cron-based schedule; interval-based tasks (everySecond) have no concept of missed slots");return 0}const max=opts.max??100;const since=opts.since instanceof Date?opts.since.getTime():opts.since;const now=Date.now();if(since>=now)return 0;const taskName=this.options.name||"unnamed-task";if(!Schedule.isEnabled(taskName)){log.info(`[scheduler] runMissed: ${taskName} is paused, so its missed slots are not run`);return 0}const{startAt,stopAt}=this.options;const inWindow=(slot)=>(!startAt||slot>=startAt)&&(!stopAt||slot<=stopAt);const zone=this.zone();const tz=zone!=="UTC"?{tz:zone}:{};const slotsAfter=(from)=>{const found=[];let cursor=from;while(true){const next=parse(this.cronPattern,cursor,tz);if(!next||next.getTime()>now)return found;if(inWindow(next))found.push(next);cursor=next.getTime()}};let span=60000*(max+1);let from=Math.max(since,now-span);let slots=slotsAfter(from);while(slots.length<=max&&from>since){span*=2;from=Math.max(since,now-span);slots=slotsAfter(from)}if(slots.length>max){const missed=from===since?`${slots.length}`:`more than ${max}`;log.warn(`[scheduler] runMissed: ${missed} missed slots since ${new Date(since).toISOString()}, running the ${max} most recent - older runs dropped`);slots=slots.slice(-max)}const context=this.options.context;const run=this.wrapTask(context===undefined?this.task:()=>this.task(context),true);let fired=0;for(const slot of slots){try{if(!await this.claimSlot(taskName,slot.getTime())){log.info(`[scheduler] runMissed slot ${slot.toISOString()} skipped: another server claimed it`);continue}let result=run();if(result&&typeof result.then==="function")result=await result;if(result===SKIPPED_BY_LOCK){log.info(`[scheduler] runMissed slot ${slot.toISOString()} skipped: ${taskName} is already running`);continue}fired++}catch(err){log.error(`[scheduler] runMissed slot ${slot.toISOString()} failed: ${err instanceof Error?err.message:String(err)}`);if(this.options.catch)this.options.catch(err)}}return fired}static listJobs(){const out=[];const history=Schedule.lastRuns();for(const[name,job]of Schedule.jobs){out.push({name,pattern:job.pattern,timezone:job.timezone,nextRun:job.nextRun?job.nextRun():null,enabled:Schedule.isEnabled(name),lastRun:history[name]})}return out}static lastRuns(){try{const value=JSON.parse(readFileSync(Schedule.historyFile,"utf8"));return value.runs&&typeof value.runs==="object"?value.runs:{}}catch{return{}}}static recordRun(name,run){try{const runs=Schedule.lastRuns();const lastSuccessAt=run.status==="success"?run.finishedAt:runs[name]?.lastSuccessAt;runs[name]={...run,...lastSuccessAt?{lastSuccessAt}:{}};mkdirSync(dirname(Schedule.historyFile),{recursive:true});const temporary=`${Schedule.historyFile}.${process.pid}.tmp`;writeFileSync(temporary,`${JSON.stringify({runs},null,2)}
2
2
  `,{mode:384});renameSync(temporary,Schedule.historyFile)}catch(error){log.debug(`[scheduler] could not record the run of ${name}: ${error instanceof Error?error.message:String(error)}`)}}static async runNow(name,options={}){const job=Schedule.jobs.get(name);if(!job)throw new Error(`Scheduled task "${name}" was not found.`);if(!Schedule.isEnabled(name))throw new Error(`Scheduled task "${name}" is paused.`);const here=options.inProcess?Schedule.inProcessRuns.get(name):undefined;await(here?here():job.run())}static setEnabled(name,enabled){const disabled=Schedule.disabledJobs();if(enabled)disabled.delete(name);else disabled.add(name);mkdirSync(dirname(Schedule.stateFile),{recursive:true});const temporary=`${Schedule.stateFile}.${process.pid}.tmp`;writeFileSync(temporary,`${JSON.stringify({disabled:[...disabled].sort()},null,2)}
3
- `,{mode:384});renameSync(temporary,Schedule.stateFile)}static isEnabled(name){return!Schedule.disabledJobs().has(name)}static isScheduled(name){return Schedule.jobs.has(name)}static disabledJobs(){try{const value=JSON.parse(readFileSync(Schedule.stateFile,"utf8"));return new Set(Array.isArray(value.disabled)?value.disabled.filter((name)=>typeof name==="string"):[])}catch{return new Set}}static listLocks(){return Array.from(Schedule.activeLocks.keys())}async acquireLock(name){if(Schedule.activeLocks.has(name))return false;const expiryMs=this.overlapExpiresAfterMinutes*60*1000;const{dialect,adminDb}=this.shouldRunOnOneServer?await this.oneServerDb(true):{dialect:null,adminDb:null};const handle=await acquireSchedulerLock(name,expiryMs,dialect,adminDb,Schedule.lockDir);if(!handle)return false;Schedule.activeLocks.set(name,handle);return true}async oneServerDb(warn){try{const{db}=await import("@stacksjs/database/runtime");const adminDb=db;const driver=(await import("@stacksjs/env")).env.DB_CONNECTION||"sqlite";const dialect=driver==="postgres"||driver==="mysql"||driver==="sqlite"?driver:null;return{dialect,adminDb}}catch(err){if(warn)log.warn(`[scheduler] onOneServer() couldn't reach DB; falling back to file-only lock (which only serializes within this process): ${err instanceof Error?err.message:String(err)}`);return{dialect:null,adminDb:null}}}async claimSlot(name,slot){if(!this.shouldRunOnOneServer)return true;const{dialect,adminDb}=await this.oneServerDb(false);return claimSchedulerSlot(name,slot,dialect,adminDb)}async releaseLock(name){const handle=Schedule.activeLocks.get(name);if(!handle)return;Schedule.activeLocks.delete(name);await handle.release()}wrapTask(originalTask,inProcess=false){const taskName=this.options.name||"unnamed-task";let wrappedTask=originalTask;if(this.shouldPreventOverlap||this.shouldRunOnOneServer){const self=this;const innerTask=wrappedTask;wrappedTask=()=>(async()=>{const acquired=await self.acquireLock(taskName);if(!acquired){log.info(`Skipping overlapping task: ${taskName}`);return SKIPPED_BY_LOCK}try{const result=innerTask();if(result&&typeof result==="object"&&typeof result.finally==="function"){await result}}finally{try{await self.releaseLock(taskName)}catch(error){log.error(`[scheduler] releasing the lock for ${taskName} failed: ${error instanceof Error?error.message:String(error)}`)}}})()}if(this.shouldRunInBackground&&!inProcess){const buddy=join(process.cwd(),"buddy");const outputPath=this.handlesOwnOutput?null:this.outputPath;const outputAppend=this.outputAppend;wrappedTask=()=>{let output="inherit";if(outputPath){try{output=openSync(outputPath,outputAppend?"a":"w")}catch(err){log.warn(`[scheduler] couldn't open ${outputPath} for background task ${taskName}: ${err instanceof Error?err.message:String(err)}; its output goes to this process instead`)}}const closeOutput=()=>{if(typeof output!=="number")return;try{closeSync(output)}catch{}output="inherit"};const child=spawn(buddy,["schedule:run-one",taskName,"--in-process"],{cwd:process.cwd(),detached:true,stdio:["ignore",output,output]});closeOutput();child.on("error",(error)=>{log.error(`[scheduler] background task ${taskName} failed to start (${buddy}): ${error.message}`)});child.on("exit",(code,signal)=>{if(code!==0&&code!==null)log.error(`[scheduler] background task ${taskName} (pid: ${child.pid}) exited with code ${code}`);else if(signal)log.warn(`[scheduler] background task ${taskName} (pid: ${child.pid}) terminated by signal ${signal}`)});child.unref();log.info(`Task ${taskName} spawned in background (pid: ${child.pid})`)}}return wrappedTask}getNextRunTime(){if(!this.cronPattern||this.intervalMs!==null)return null;const{startAt,stopAt}=this.options;const now=Date.now();const base=startAt&&startAt.getTime()>now?startAt.getTime()-1:now;const next=this.nextCronTime(base);if(next&&stopAt&&next.getTime()>stopAt.getTime())return null;return next}zone(){if(this.timezone)return this.timezone;const app=config.app;return app?.timezone||"UTC"}nextCronTime(base){const zone=this.zone();if(zone==="UTC"){return parse(this.cronPattern,base)}return parse(this.cronPattern,base,{tz:zone})}start(){if(!this.cronPattern&&this.intervalMs===null){return{stop:()=>{},run:async()=>{},nextRun:()=>null}}const dedupeKey=this.options.name?`${this.options.name.toLowerCase().replace(/[^a-z0-9]+/g,"")}::${this.cronPattern||`every:${this.intervalMs}`}`:null;if(dedupeKey){const existing=Schedule.scheduledKeys.get(dedupeKey);if(existing){log.debug(`[scheduler] duplicate schedule for "${this.options.name}" (${this.cronPattern||`every ${this.intervalMs}ms`}) skipped`);return existing}}if(this.shouldRunInBackground&&!this.options.name)throw new Error("runInBackground() needs a named task: add .withName(...) so the background process can find it");const context=this.options.context;const base=context===undefined?this.task:()=>this.task(context);const task=this.wrapTask(base);const taskHere=this.shouldRunInBackground?this.wrapTask(base,true):task;let stopped=false;let running=false;let lastStartedAt=null;let timer=null;let runCount=0;const stop=()=>{stopped=true;if(timer!==null){if(this.intervalMs!==null)clearInterval(timer);else clearTimeout(timer);timer=null}};const nextRun=()=>{return this.getNextRunTime()};const taskName=this.options.name||"unnamed-task";const runTask=async(body,slot)=>{if(!Schedule.isEnabled(taskName)){log.debug(`[scheduler] task ${taskName} is paused`);return}const{startAt,stopAt,interval,protect}=this.options;const now=Date.now();if(stopAt&&now>stopAt.getTime()){log.debug(`[scheduler] task ${taskName} is past its between() window; stopping`);stop();return}if(startAt&&now<startAt.getTime()){log.debug(`[scheduler] task ${taskName} has not reached its between() window`);return}if(this.options.maxRuns&&runCount>=this.options.maxRuns){stop();return}if(protect&&running){log.debug(`[scheduler] task ${taskName} is still running; skipping this tick (withProtection)`);if(typeof protect==="function")protect(job);return}if(slot!==undefined&&running&&!this.allowOverlap){log.info(`[scheduler] task ${taskName} is still running; skipping this tick (allowOverlapping() to run concurrently)`);return}if(interval&&lastStartedAt!==null&&now-lastStartedAt<interval*1000){log.debug(`[scheduler] task ${taskName} ran less than ${interval}s ago; skipping this tick (withInterval)`);return}if(slot!==undefined){let claimed;try{claimed=await this.claimSlot(taskName,slot)}catch(error){reportFailure(error);throw error}if(!claimed){log.info(`[scheduler] task ${taskName} slot ${new Date(slot).toISOString()} skipped: another server claimed it (onOneServer)`);return}}runCount++;running=true;lastStartedAt=now;let settle=()=>{};const tracked=new Promise((resolve)=>{settle=resolve});Schedule.inFlight.set(tracked,taskName);Schedule.recordRun(taskName,{startedAt:new Date(now).toISOString(),status:"running"});let failure;try{const result=body();if(result&&typeof result.then==="function")await result}catch(error){failure=error;reportFailure(error);throw error}finally{running=false;const finished=Date.now();Schedule.recordRun(taskName,{startedAt:new Date(now).toISOString(),finishedAt:new Date(finished).toISOString(),durationMs:finished-now,status:failure===undefined?"success":"failed",error:failure===undefined?undefined:String(failure instanceof Error?failure.message:failure).slice(0,500)});Schedule.inFlight.delete(tracked);settle()}};const reportFailure=(error)=>{if(this.options.catch){this.options.catch(error)}else{log.error(`[scheduler] task ${taskName} failed (no withErrorHandler() installed): ${error instanceof Error?error.message:String(error)}`)}};const executeTask=(slot)=>runTask(task,slot);const job={stop,run:()=>runTask(task),nextRun,pattern:this.intervalMs!==null?`every ${this.intervalMs/1000}s`:this.cronPattern,timezone:this.zone(),name:this.options.name,enabled:Schedule.isEnabled(taskName)};if(this.intervalMs!==null){const intervalMs=this.intervalMs;timer=setInterval(()=>{if(stopped)return;executeTask(Math.floor(Date.now()/intervalMs)*intervalMs).catch(()=>{})},intervalMs);timer.unref?.()}else if(this.cronPattern){const MAX_TIMEOUT=2147483647;const scheduleNext=()=>{if(stopped)return;if(this.options.maxRuns&&runCount>=this.options.maxRuns)return;const nextTime=this.getNextRunTime();if(!nextTime){stop();return}const delay=Math.max(nextTime.getTime()-Date.now(),0);if(delay>MAX_TIMEOUT){timer=setTimeout(()=>{if(stopped)return;scheduleNext()},MAX_TIMEOUT)}else{timer=setTimeout(()=>{if(stopped)return;executeTask(nextTime.getTime()).catch(()=>{});scheduleNext()},delay)}};scheduleNext()}if(this.options.name){Schedule.jobs.set(this.options.name,job);Schedule.inProcessRuns.set(this.options.name,()=>runTask(taskHere))}if(dedupeKey){Schedule.scheduledKeys.set(dedupeKey,job)}log.info(`Scheduled task with pattern: ${this.cronPattern} in timezone: ${this.zone()}`);return job}static job(name){let instance=null;instance=new Schedule(async(context)=>{const queue=instance?.dispatchQueue??null;try{if(queue!==null){log.info(`Dispatching job: ${name} to queue ${queue}`);const pending=queuedJob(name).onQueue(queue);await(context===undefined?pending:pending.withContext(context)).dispatch();return}log.info(`Running job: ${name}`);await runJob(name,context===undefined?{}:{context})}catch(error){log.error(`Job ${name} failed:`,error);throw error}});instance.jobName=name;return instance.withName(name)}static action(name){return new Schedule(async()=>{log.info(`Running action: ${name}`);try{await runNamedAction(name)}catch(error){log.error(`Action ${name} failed:`,error);throw error}}).withName(name)}static command(cmd){let instance=null;const task=async()=>{const outputPath=instance?.outputPath??null;const outputAppend=instance?.outputAppend??false;try{log.info(`Executing command: ${cmd}`);if(outputPath){const{spawn:childSpawn}=await import("node:child_process");const{openSync,closeSync}=await import("node:fs");const flag=outputAppend?"a":"w";const fd=openSync(outputPath,flag);try{await new Promise((resolve,reject)=>{const child=childSpawn(cmd,{shell:true,stdio:["ignore",fd,fd]});child.on("error",reject);child.on("exit",(code)=>{if(code===0)resolve();else reject(new Error(`Command '${cmd}' exited with code ${code}`))})})}finally{closeSync(fd)}return}const result=await runCommand(cmd);if(result.isErr){log.error(result.error);throw result.error}}catch(error){log.error(`Command execution failed: ${error}`);throw error}};instance=new Schedule(task);instance.handlesOwnOutput=true;return instance.withName(`command-${cmd}`)}static notification(recipient,payload,channels,options){return new Schedule(async()=>{try{const{notify}=await import("@stacksjs/notifications");const results=await notify(recipient,payload,channels,options);const failed=results.filter((result)=>!result.success);if(failed.length>0){const reasons=failed.map((result)=>`${result.channel}: ${result.error?.message??"not delivered"}`).join("; ");throw new Error(`Scheduled notification was not delivered on ${failed.length} of ${results.length} channel(s) - ${reasons}`)}}catch(error){log.error("Scheduled notification failed:",error);throw error}}).withName(notificationTaskName(recipient,payload,channels,options))}static async gracefulShutdown(options={}){log.info("Gracefully shutting down scheduled jobs...");for(const[name,job]of Schedule.jobs){log.debug(`Stopping job: ${name}`);job.stop()}Schedule.jobs.clear();Schedule.inProcessRuns.clear();Schedule.scheduledKeys.clear();const running=[...Schedule.inFlight.keys()];if(running.length>0){log.info(`[scheduler] waiting for ${running.length} running job(s) to finish...`);let timer;const deadline=new Promise((resolve)=>{timer=setTimeout(resolve,options.timeoutMs??30000)});await Promise.race([Promise.allSettled(running),deadline]);clearTimeout(timer)}const unfinished=[...new Set(Schedule.inFlight.values())];if(unfinished.length>0)await log.warn(`[scheduler] stopped without waiting for: ${unfinished.join(", ")}`);else await log.info("All jobs have been stopped");return{unfinished}}static stoppingOnSignals=false;static stopOnSignals(options={}){if(Schedule.stoppingOnSignals)return;Schedule.stoppingOnSignals=true;let stopping=false;const stopAndExit=async(signal)=>{if(stopping)return;stopping=true;try{await log.info(`[scheduler] ${signal}: stopping after the running jobs finish`);await Schedule.gracefulShutdown(options)}finally{process.exit(0)}};process.on("SIGTERM",(signal)=>void stopAndExit(signal));process.on("SIGINT",(signal)=>void stopAndExit(signal))}}function defaultHistoryFile(){return process.env.NODE_ENV==="test"?join(tmpdir(),"stacks-scheduler-history-test.json"):frameworkPath("runtime/scheduler-history.json")}export class Queue extends Schedule{}export function sendAt(cronExpression){if(cronExpression instanceof Date){return cronExpression>new Date?cronExpression:null}return parse(cronExpression)}export function timeout(cronExpression){const next=sendAt(cronExpression);if(!next)return-1;return next.getTime()-Date.now()}export const schedule=Schedule;export default Schedule;
3
+ `,{mode:384});renameSync(temporary,Schedule.stateFile)}static isEnabled(name){return!Schedule.disabledJobs().has(name)}static isScheduled(name){return Schedule.jobs.has(name)}static disabledJobs(){try{const value=JSON.parse(readFileSync(Schedule.stateFile,"utf8"));return new Set(Array.isArray(value.disabled)?value.disabled.filter((name)=>typeof name==="string"):[])}catch{return new Set}}static listLocks(){return Array.from(Schedule.activeLocks.keys())}async acquireLock(name){if(Schedule.activeLocks.has(name))return false;const expiryMs=this.overlapExpiresAfterMinutes*60*1000;const{dialect,adminDb}=this.shouldRunOnOneServer?await this.oneServerDb(true):{dialect:null,adminDb:null};const handle=await acquireSchedulerLock(name,expiryMs,dialect,adminDb,Schedule.lockDir);if(!handle)return false;Schedule.activeLocks.set(name,handle);return true}async oneServerDb(warn){try{const{db}=await import("@stacksjs/database/runtime");const adminDb=db;const driver=(await import("@stacksjs/env")).env.DB_CONNECTION||"sqlite";const dialect=driver==="postgres"||driver==="mysql"||driver==="sqlite"?driver:null;return{dialect,adminDb}}catch(err){if(warn)log.warn(`[scheduler] onOneServer() couldn't reach DB; falling back to file-only lock (which only serializes within this process): ${err instanceof Error?err.message:String(err)}`);return{dialect:null,adminDb:null}}}async claimSlot(name,slot){if(!this.shouldRunOnOneServer)return true;const{dialect,adminDb}=await this.oneServerDb(false);return claimSchedulerSlot(name,slot,dialect,adminDb)}async releaseLock(name){const handle=Schedule.activeLocks.get(name);if(!handle)return;Schedule.activeLocks.delete(name);await handle.release()}wrapTask(originalTask,inProcess=false){const taskName=this.options.name||"unnamed-task";let wrappedTask=originalTask;if(this.shouldPreventOverlap||this.shouldRunOnOneServer){const self=this;const innerTask=wrappedTask;wrappedTask=()=>(async()=>{const acquired=await self.acquireLock(taskName);if(!acquired){log.info(`Skipping overlapping task: ${taskName}`);return SKIPPED_BY_LOCK}try{const result=innerTask();if(result&&typeof result==="object"&&typeof result.finally==="function"){await result}}finally{try{await self.releaseLock(taskName)}catch(error){log.error(`[scheduler] releasing the lock for ${taskName} failed: ${error instanceof Error?error.message:String(error)}`)}}})()}if(this.shouldRunInBackground&&!inProcess){const buddy=join(process.cwd(),"buddy");const outputPath=this.handlesOwnOutput?null:this.outputPath;const outputAppend=this.outputAppend;wrappedTask=()=>{let output="inherit";if(outputPath){try{output=openSync(outputPath,outputAppend?"a":"w")}catch(err){log.warn(`[scheduler] couldn't open ${outputPath} for background task ${taskName}: ${err instanceof Error?err.message:String(err)}; its output goes to this process instead`)}}const closeOutput=()=>{if(typeof output!=="number")return;try{closeSync(output)}catch{}output="inherit"};const child=spawn(buddy,["schedule:run-one",taskName,"--in-process"],{cwd:process.cwd(),detached:true,stdio:["ignore",output,output]});closeOutput();child.on("error",(error)=>{log.error(`[scheduler] background task ${taskName} failed to start (${buddy}): ${error.message}`)});child.on("exit",(code,signal)=>{if(code!==0&&code!==null)log.error(`[scheduler] background task ${taskName} (pid: ${child.pid}) exited with code ${code}`);else if(signal)log.warn(`[scheduler] background task ${taskName} (pid: ${child.pid}) terminated by signal ${signal}`)});child.unref();log.info(`Task ${taskName} spawned in background (pid: ${child.pid})`)}}return wrappedTask}getNextRunTime(){if(!this.cronPattern||this.intervalMs!==null)return null;const{startAt,stopAt}=this.options;const now=Date.now();const base=startAt&&startAt.getTime()>now?startAt.getTime()-1:now;const next=this.nextCronTime(base);if(next&&stopAt&&next.getTime()>stopAt.getTime())return null;return next}zone(){if(this.timezone)return this.timezone;const app=config.app;return app?.timezone||"UTC"}nextCronTime(base){const zone=this.zone();if(zone==="UTC"){return parse(this.cronPattern,base)}return parse(this.cronPattern,base,{tz:zone})}start(){if(!this.cronPattern&&this.intervalMs===null){return{stop:()=>{},run:async()=>{},nextRun:()=>null}}const dedupeKey=this.options.name?`${this.options.name.toLowerCase().replace(/[^a-z0-9]+/g,"")}::${this.cronPattern||`every:${this.intervalMs}`}`:null;if(dedupeKey){const existing=Schedule.scheduledKeys.get(dedupeKey);if(existing){log.debug(`[scheduler] duplicate schedule for "${this.options.name}" (${this.cronPattern||`every ${this.intervalMs}ms`}) skipped`);return existing}}if(this.shouldRunInBackground&&!this.options.name)throw new Error("runInBackground() needs a named task: add .withName(...) so the background process can find it");const context=this.options.context;const base=context===undefined?this.task:()=>this.task(context);const task=this.wrapTask(base);const taskHere=this.shouldRunInBackground?this.wrapTask(base,true):task;let stopped=false;let activeRuns=0;let lastStartedAt=null;let timer=null;let runCount=0;const stop=()=>{stopped=true;if(timer!==null){if(this.intervalMs!==null)clearInterval(timer);else clearTimeout(timer);timer=null}};const nextRun=()=>{return this.getNextRunTime()};const taskName=this.options.name||"unnamed-task";const runTask=async(body,slot)=>{if(!Schedule.isEnabled(taskName)){log.debug(`[scheduler] task ${taskName} is paused`);return}const{startAt,stopAt,interval,protect}=this.options;const now=Date.now();if(stopAt&&now>stopAt.getTime()){log.debug(`[scheduler] task ${taskName} is past its between() window; stopping`);stop();return}if(startAt&&now<startAt.getTime()){log.debug(`[scheduler] task ${taskName} has not reached its between() window`);return}if(this.options.maxRuns&&runCount>=this.options.maxRuns){stop();return}if(protect&&activeRuns>0){log.debug(`[scheduler] task ${taskName} is still running; skipping this tick (withProtection)`);if(typeof protect==="function")protect(job);return}if(slot!==undefined&&activeRuns>0&&!this.allowOverlap){log.info(`[scheduler] task ${taskName} is still running; skipping this tick (allowOverlapping() to run concurrently)`);return}if(interval&&lastStartedAt!==null&&now-lastStartedAt<interval*1000){log.debug(`[scheduler] task ${taskName} ran less than ${interval}s ago; skipping this tick (withInterval)`);return}if(slot!==undefined){let claimed;try{claimed=await this.claimSlot(taskName,slot)}catch(error){reportFailure(error);throw error}if(!claimed){log.info(`[scheduler] task ${taskName} slot ${new Date(slot).toISOString()} skipped: another server claimed it (onOneServer)`);return}}runCount++;activeRuns++;lastStartedAt=now;let settle=()=>{};const tracked=new Promise((resolve)=>{settle=resolve});Schedule.inFlight.set(tracked,taskName);Schedule.recordRun(taskName,{startedAt:new Date(now).toISOString(),status:"running"});let failure;try{const result=body();if(result&&typeof result.then==="function")await result}catch(error){failure=error;reportFailure(error);throw error}finally{activeRuns--;const finished=Date.now();Schedule.recordRun(taskName,{startedAt:new Date(now).toISOString(),finishedAt:new Date(finished).toISOString(),durationMs:finished-now,status:failure===undefined?"success":"failed",error:failure===undefined?undefined:String(failure instanceof Error?failure.message:failure).slice(0,500)});Schedule.inFlight.delete(tracked);settle()}};const reportFailure=(error)=>{if(this.options.catch){this.options.catch(error)}else{log.error(`[scheduler] task ${taskName} failed (no withErrorHandler() installed): ${error instanceof Error?error.message:String(error)}`)}};const executeTask=(slot)=>runTask(task,slot);const job={stop,run:()=>runTask(task),nextRun,pattern:this.intervalMs!==null?`every ${this.intervalMs/1000}s`:this.cronPattern,timezone:this.zone(),name:this.options.name,enabled:Schedule.isEnabled(taskName)};if(this.intervalMs!==null){const intervalMs=this.intervalMs;timer=setInterval(()=>{if(stopped)return;executeTask(Math.floor(Date.now()/intervalMs)*intervalMs).catch(()=>{})},intervalMs);timer.unref?.()}else if(this.cronPattern){const MAX_TIMEOUT=2147483647;const scheduleNext=()=>{if(stopped)return;if(this.options.maxRuns&&runCount>=this.options.maxRuns)return;const nextTime=this.getNextRunTime();if(!nextTime){stop();return}const delay=Math.max(nextTime.getTime()-Date.now(),0);if(delay>MAX_TIMEOUT){timer=setTimeout(()=>{if(stopped)return;scheduleNext()},MAX_TIMEOUT)}else{timer=setTimeout(()=>{if(stopped)return;executeTask(nextTime.getTime()).catch(()=>{});scheduleNext()},delay)}};scheduleNext()}if(this.options.name){Schedule.jobs.set(this.options.name,job);Schedule.inProcessRuns.set(this.options.name,()=>runTask(taskHere))}if(dedupeKey){Schedule.scheduledKeys.set(dedupeKey,job)}log.info(`Scheduled task with pattern: ${this.cronPattern} in timezone: ${this.zone()}`);return job}static job(name){let instance=null;instance=new Schedule(async(context)=>{const queue=instance?.dispatchQueue??null;try{if(queue!==null){log.info(`Dispatching job: ${name} to queue ${queue}`);const pending=queuedJob(name).onQueue(queue);await(context===undefined?pending:pending.withContext(context)).dispatch();return}log.info(`Running job: ${name}`);await runJob(name,context===undefined?{}:{context})}catch(error){log.error(`Job ${name} failed:`,error);throw error}});instance.jobName=name;return instance.withName(name)}static action(name){return new Schedule(async()=>{log.info(`Running action: ${name}`);try{await runNamedAction(name)}catch(error){log.error(`Action ${name} failed:`,error);throw error}}).withName(name)}static command(cmd){let instance=null;const task=async()=>{const outputPath=instance?.outputPath??null;const outputAppend=instance?.outputAppend??false;try{log.info(`Executing command: ${cmd}`);if(outputPath){const{spawn:childSpawn}=await import("node:child_process");const{openSync,closeSync}=await import("node:fs");const flag=outputAppend?"a":"w";const fd=openSync(outputPath,flag);try{await new Promise((resolve,reject)=>{const child=childSpawn(cmd,{shell:true,stdio:["ignore",fd,fd]});child.on("error",reject);child.on("exit",(code)=>{if(code===0)resolve();else reject(new Error(`Command '${cmd}' exited with code ${code}`))})})}finally{closeSync(fd)}return}const result=await runCommand(cmd);if(result.isErr){log.error(result.error);throw result.error}}catch(error){log.error(`Command execution failed: ${error}`);throw error}};instance=new Schedule(task);instance.handlesOwnOutput=true;return instance.withName(`command-${cmd}`)}static notification(recipient,payload,channels,options){return new Schedule(async()=>{try{const{notify}=await import("@stacksjs/notifications");const results=await notify(recipient,payload,channels,options);const failed=results.filter((result)=>!result.success);if(failed.length>0){const reasons=failed.map((result)=>`${result.channel}: ${result.error?.message??"not delivered"}`).join("; ");throw new Error(`Scheduled notification was not delivered on ${failed.length} of ${results.length} channel(s) - ${reasons}`)}}catch(error){log.error("Scheduled notification failed:",error);throw error}}).withName(notificationTaskName(recipient,payload,channels,options))}static async gracefulShutdown(options={}){log.info("Gracefully shutting down scheduled jobs...");for(const[name,job]of Schedule.jobs){log.debug(`Stopping job: ${name}`);job.stop()}Schedule.jobs.clear();Schedule.inProcessRuns.clear();Schedule.scheduledKeys.clear();const running=[...Schedule.inFlight.keys()];if(running.length>0){log.info(`[scheduler] waiting for ${running.length} running job(s) to finish...`);let timer;const deadline=new Promise((resolve)=>{timer=setTimeout(resolve,options.timeoutMs??30000)});await Promise.race([Promise.allSettled(running),deadline]);clearTimeout(timer)}const unfinished=[...new Set(Schedule.inFlight.values())];if(unfinished.length>0)await log.warn(`[scheduler] stopped without waiting for: ${unfinished.join(", ")}`);else await log.info("All jobs have been stopped");return{unfinished}}static stoppingOnSignals=false;static stopOnSignals(options={}){if(Schedule.stoppingOnSignals)return;Schedule.stoppingOnSignals=true;let stopping=false;const stopAndExit=async(signal)=>{if(stopping)return;stopping=true;try{await log.info(`[scheduler] ${signal}: stopping after the running jobs finish`);await Schedule.gracefulShutdown(options)}finally{process.exit(0)}};process.on("SIGTERM",(signal)=>void stopAndExit(signal));process.on("SIGINT",(signal)=>void stopAndExit(signal))}}function defaultHistoryFile(){return process.env.NODE_ENV==="test"?join(tmpdir(),"stacks-scheduler-history-test.json"):frameworkPath("runtime/scheduler-history.json")}export class Queue extends Schedule{}export function sendAt(cronExpression){if(cronExpression instanceof Date){return cronExpression>new Date?cronExpression:null}return parse(cronExpression)}export function timeout(cronExpression){const next=sendAt(cronExpression);if(!next)return-1;return next.getTime()-Date.now()}export const schedule=Schedule;export default Schedule;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/scheduler",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.701",
5
+ "version": "0.75.706",
6
6
  "description": "The Stacks scheduler.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,19 +58,19 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/action-runner": "0.75.701",
62
- "@stacksjs/cli": "0.75.701",
63
- "@stacksjs/config": "0.75.701",
64
- "@stacksjs/cron": "0.75.701",
65
- "@stacksjs/database": "0.75.701",
66
- "@stacksjs/env": "0.75.701",
67
- "@stacksjs/error-handling": "0.75.701",
68
- "@stacksjs/logging": "0.75.701",
69
- "@stacksjs/notifications": "0.75.701",
70
- "@stacksjs/path": "0.75.701",
71
- "@stacksjs/queue": "0.75.701",
72
- "@stacksjs/storage": "0.75.701",
73
- "@stacksjs/types": "0.75.701"
61
+ "@stacksjs/action-runner": "0.75.706",
62
+ "@stacksjs/cli": "0.75.706",
63
+ "@stacksjs/config": "0.75.706",
64
+ "@stacksjs/cron": "0.75.706",
65
+ "@stacksjs/database": "0.75.706",
66
+ "@stacksjs/env": "0.75.706",
67
+ "@stacksjs/error-handling": "0.75.706",
68
+ "@stacksjs/logging": "0.75.706",
69
+ "@stacksjs/notifications": "0.75.706",
70
+ "@stacksjs/path": "0.75.706",
71
+ "@stacksjs/queue": "0.75.706",
72
+ "@stacksjs/storage": "0.75.706",
73
+ "@stacksjs/types": "0.75.706"
74
74
  },
75
75
  "devDependencies": {
76
76
  "better-dx": "^0.2.39"