@stacksjs/scheduler 0.75.548 → 0.75.552
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.
- package/dist/index.js +1 -3
- package/dist/run.js +1 -0
- package/dist/schedule.js +2 -0
- package/dist/scheduler-claims.js +1 -0
- package/dist/scheduler-lock.js +1 -0
- package/dist/types.js +0 -0
- package/package.json +14 -14
package/dist/index.js
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import{ok as Y}from"@stacksjs/error-handling";import{log as C}from"@stacksjs/logging";import{path as M}from"@stacksjs/path";import{schedule as F}from"@stacksjs/scheduler";import{globSync as V}from"@stacksjs/storage";async function jt(){let t=V([M.appPath("Jobs/*.ts")],{absolute:!0});await Z();for(let e of t)try{let r=(await import(e)).default,s=et(e);if(r.enabled===!1||!r.rate)continue;let i=[s,r.name].find((o)=>typeof o==="string"&&F.isScheduled(o));if(i){C.debug(`[scheduler] ${i} is declared in app/Scheduler.ts; ignoring its \`rate\` so it is not scheduled twice`);continue}tt(s,r.rate)}catch(n){C.error(`[scheduler] could not schedule ${e}: ${n instanceof Error?n.message:String(n)}`)}return Y("Schedules ran successfully")}async function Z(){let t=M.appPath("Scheduler.ts");try{let e=await import(t);if(typeof e.default==="function")e.default();else console.warn(`Scheduler file ${t} does not export a default function`)}catch(e){console.warn(`Could not load scheduler file ${t}:`,e)}}function tt(t,e){F.job(t).cron(e)}function et(t){return M.basename(t).replace(/\.ts$/,"")}import{spawn as pt}from"child_process";import{createHash as gt}from"crypto";import{closeSync as wt,mkdirSync as yt,openSync as bt,readFileSync as kt,renameSync as St,writeFileSync as vt}from"fs";import{join as O}from"path";import{runNamedAction as $t}from"@stacksjs/action-runner";import{log as a,runCommand as Tt}from"@stacksjs/cli";import{config as Et}from"@stacksjs/config";import{parse as E}from"@stacksjs/cron";import{job as Nt,runJob as Dt}from"@stacksjs/queue";import{randomUUID as ht}from"crypto";import{createHash as R,randomUUID as nt}from"crypto";import{existsSync as rt,mkdirSync as st,readFileSync as q,statSync as it,unlinkSync as ot,writeFileSync as J}from"fs";import{join as z}from"path";import U from"process";var _="stacks_scheduler";function at(t){let e=Date.now()-t.acquiredAt;if(e<0)return 0;return e}function I(t){let e=t.replace(/[^\w.-]+/g,"_").replace(/^\.+/,"_").slice(0,80),n=R("sha256").update(t).digest("hex").slice(0,12);return`${e}-${n}.lock`}async function B(t,e,n,r,s){let i=s??z(U.cwd(),"storage","framework","locks"),o=z(i,I(t));if(!rt(i))st(i,{recursive:!0});let u=!1,l=null;if(r&&(n==="postgres"||n==="mysql")){if(!await ut(t,n,r))return null;l=async()=>{if(u)return;u=!0,await ct(t,n,r).catch(()=>{})}}let p={token:nt(),acquiredAt:Date.now(),monotonicStart:Math.round(performance.now()),holder:U.pid};try{J(o,JSON.stringify(p),{flag:"wx"})}catch{let g=!1;try{let f=q(o,"utf8"),w=JSON.parse(f);if(at(w)>=e)g=!0}catch{try{let f=it(o);if(Math.max(0,Date.now()-f.mtimeMs)>=e)g=!0}catch{g=!0}}if(!g){if(l)await l();return null}try{J(o,JSON.stringify(p))}catch{if(l)await l();return null}}let h=!1;return{release:async()=>{if(h)return;h=!0;try{if(JSON.parse(q(o,"utf8")).token===p.token)ot(o)}catch{}if(l)await l()}}}function H(t){let e=R("sha256").update(`${_}:${t}`).digest();return{key1:e.readInt32BE(0),key2:e.readInt32BE(4)}}async function ut(t,e,n){if(e==="postgres"){let{key1:i,key2:o}=H(t),u=await n.unsafe(`SELECT pg_try_advisory_lock(${i}, ${o}) AS acquired`);return lt(u,"acquired")}let r=K(t),s=await n.unsafe(`SELECT GET_LOCK('${r}', 0) AS acquired`);return dt(s,"acquired")===1}async function ct(t,e,n){if(e==="postgres"){let{key1:s,key2:i}=H(t);await n.unsafe(`SELECT pg_advisory_unlock(${s}, ${i})`);return}let r=K(t);await n.unsafe(`SELECT RELEASE_LOCK('${r}')`)}function K(t){let e=R("sha256").update(t).digest("hex").slice(0,32);return`${_}_${e}`}function lt(t,e){let n=x(t);if(!n)return!1;let r=n[e];return r===!0||r===1||r==="1"||r==="t"}function dt(t,e){let n=x(t);if(!n)return null;let r=n[e];if(typeof r==="number")return r;if(typeof r==="string"&&/^-?\d+$/.test(r))return Number.parseInt(r,10);return null}function x(t){if(!t)return null;if(Array.isArray(t))return t[0];if(typeof t==="object"&&"rows"in t&&Array.isArray(t.rows))return t.rows[0];return null}var T="scheduler_claims",ft=86400000;function Q(){return`CREATE TABLE IF NOT EXISTS ${T} (task VARCHAR(128) NOT NULL,slot BIGINT NOT NULL,claimant CHAR(36) NOT NULL,PRIMARY KEY (task, slot))`}var L=new WeakMap;function mt(t){let e=L.get(t);if(!e)e=(async()=>{try{await t.unsafe(Q())}catch{await t.unsafe(Q())}})(),L.set(t,e),e.catch(()=>L.delete(t));return e}async function W(t,e,n,r){if(!r||n!=="postgres"&&n!=="mysql")return!0;await mt(r);let s=I(t).replace(/\.lock$/,""),i=Math.trunc(e),o=ht(),u=`('${s}', ${i}, '${o}')`;await r.unsafe(n==="postgres"?`INSERT INTO ${T} (task, slot, claimant) VALUES ${u} ON CONFLICT (task, slot) DO NOTHING`:`INSERT INTO ${T} (task, slot, claimant) VALUES ${u} ON DUPLICATE KEY UPDATE task = task`);let l=x(await r.unsafe(`SELECT claimant FROM ${T} WHERE task = '${s}' AND slot = ${i}`)),p=typeof l?.claimant==="string"&&l.claimant.trim()===o;if(p)await r.unsafe(`DELETE FROM ${T} WHERE task = '${s}' AND slot < ${i-ft}`);return p}function xt(...t){let e=JSON.stringify(t,(n,r)=>{if(typeof r==="bigint")return`${r}n`;if(typeof r==="function")return`[function ${r.name}]`;if(r&&typeof r==="object"&&!Array.isArray(r))return Object.fromEntries(Object.entries(r).sort(([s],[i])=>s.localeCompare(i)));return r});return`notification-${gt("sha256").update(e).digest("hex").slice(0,12)}`}var G=Symbol("skipped-by-lock");function X(t,e){let n=t instanceof Date?new Date(t.getTime()):new Date(t);if(Number.isNaN(n.getTime()))throw Error(`between(): ${e} is not a valid date: ${String(t)}`);return n}class c{static jobs=new Map;static scheduledKeys=new Map;cronPattern="";intervalMs=null;timezone=null;task;static lockDir=O(process.cwd(),"storage","framework","locks");static stateFile=O(process.cwd(),"storage","framework","runtime","scheduler-state.json");static activeLocks=new Map;static inProcessRuns=new Map;shouldPreventOverlap=!1;overlapExpiresAfterMinutes=1440;shouldRunOnOneServer=!1;shouldRunInBackground=!1;outputPath=null;outputAppend=!1;handlesOwnOutput=!1;jobName=null;dispatchQueue=null;options={};constructor(t){this.task=t,queueMicrotask(()=>{try{this.start()}catch(e){a.error(`Failed to start scheduled task: ${e}`)}})}get pattern(){return this.cronPattern}cronFields(){let t=this.cronPattern.trim().split(/\s+/);return t.length===5?t:["0","0","*","*","*"]}setTimeOfDay(t,e){let[,,n,r,s]=this.cronFields();return this.releaseInterval(),this.cronPattern=`${t} ${e} ${n} ${r} ${s}`,this}setDays(t,e,n){let[r,s]=this.cronFields();return this.releaseInterval(),this.cronPattern=`${r} ${s} ${t} ${e} ${n}`,this}releaseInterval(){this.intervalMs=null}everySecond(){return this.intervalMs=1000,this.cronPattern="@every_second",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(t){let e=String(t).trim().split(/\s+/).filter(Boolean);if(e.length===6){let[s,...i]=e;if(i.every((o)=>o==="*")){let o=s==="*"?1:Number(/^\*\/(\d+)$/.exec(s)?.[1]);if(Number.isInteger(o)&&o>=1&&o<60&&60%o===0)return this.intervalMs=o*1000,this.cronPattern=o===1?"@every_second":`@every_${o}_seconds`,this}if(s!=="0")throw Error(`cron(): '${t}' 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`);e.shift()}if(e.length!==5)throw Error(`cron(): '${t}' is not a cron expression; expected 5 fields, or 6 with leading seconds`);let n=e.join(" "),r;try{r=E(n,Date.now(),{tz:"UTC"})}catch(s){throw Error(`cron(): '${t}' is not a valid cron expression: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw Error(`cron(): '${t}' never matches a date`);return this.intervalMs=null,this.cronPattern=n,this}dailyAt(t){return this.daily().at(t)}weekdays(){return this.setDays("*","*","1-5")}onDays(t){if(!Array.isArray(t)||t.length===0)throw Error(`onDays() requires a non-empty array; got ${JSON.stringify(t)}`);for(let e of t)if(!Number.isInteger(e)||e<0||e>6)throw Error(`onDays(): each day must be an integer 0-6 (Sun-Sat). Got ${e}`);return this.setDays("*","*",t.join(","))}at(t){let e=t.split(":");if(e.length!==2||e[0]===""||e[1]==="")throw Error(`Invalid time format "${t}". Expected "HH:MM" (e.g., "14:30")`);let[n,r]=e.map(Number);if(n===void 0||r===void 0||Number.isNaN(n)||Number.isNaN(r)||n<0||n>23||r<0||r>59)throw Error(`Invalid time "${t}". Hour must be 0-23, minute must be 0-59`);return this.setTimeOfDay(String(r),String(n))}setTimeZone(t){return this.timezone=t,this.options.timezone=t,this}withErrorHandler(t){return this.options.catch=t,this}withMaxRuns(t){return this.options.maxRuns=t,this}withProtection(t){return this.options.protect=t||!0,this}withName(t){return this.options.name=t,this}withContext(t){return this.options.context=t,this}withInterval(t){if(typeof t!=="number"||!Number.isFinite(t)||t<=0)throw Error(`withInterval() takes a positive number of seconds; got ${String(t)}`);return this.options.interval=t,this}between(t,e){let n=X(t,"startAt"),r=X(e,"stopAt");if(r.getTime()<=n.getTime())throw Error(`between(): stopAt (${r.toISOString()}) must be after startAt (${n.toISOString()})`);return this.options.startAt=n,this.options.stopAt=r,this}onQueue(t){if(this.jobName===null)throw Error("onQueue() applies to schedule.job(...) only: an action, command or callback has no job to dispatch");if(typeof t!=="string"||t.trim()==="")throw Error(`onQueue() takes a queue name; got ${JSON.stringify(t)}`);return this.dispatchQueue=t,this}withoutOverlapping(t){if(this.shouldPreventOverlap=!0,t!==void 0)this.overlapExpiresAfterMinutes=t;return this}onOneServer(){return this.shouldRunOnOneServer=!0,this}runInBackground(){return this.shouldRunInBackground=!0,this}sendOutputTo(t){return this.outputPath=t,this.outputAppend=!1,this}appendOutputTo(t){return this.outputPath=t,this.outputAppend=!0,this}async runMissed(t){if(!this.cronPattern||this.intervalMs!==null)return a.warn("[scheduler] runMissed() requires a cron-based schedule; interval-based tasks (everySecond) have no concept of missed slots"),0;let e=t.max??100,n=t.since instanceof Date?t.since.getTime():t.since,r=Date.now();if(n>=r)return 0;let s=this.options.name||"unnamed-task";if(!c.isEnabled(s))return a.info(`[scheduler] runMissed: ${s} is paused, so its missed slots are not run`),0;let{startAt:i,stopAt:o}=this.options,u=(d)=>(!i||d>=i)&&(!o||d<=o),l=this.zone(),p=l!=="UTC"?{tz:l}:{},h=(d)=>{let m=[],k=d;while(!0){let y=E(this.cronPattern,k,p);if(!y||y.getTime()>r)return m;if(u(y))m.push(y);k=y.getTime()}},g=60000*(e+1),f=Math.max(n,r-g),w=h(f);while(w.length<=e&&f>n)g*=2,f=Math.max(n,r-g),w=h(f);if(w.length>e){let d=f===n?`${w.length}`:`more than ${e}`;a.warn(`[scheduler] runMissed: ${d} missed slots since ${new Date(n).toISOString()}, running the ${e} most recent - older runs dropped`),w=w.slice(-e)}let b=this.options.context,N=this.wrapTask(b===void 0?this.task:()=>this.task(b),!0),v=0;for(let d of w)try{if(!await this.claimSlot(s,d.getTime())){a.info(`[scheduler] runMissed slot ${d.toISOString()} skipped: another server claimed it`);continue}let m=N();if(m&&typeof m.then==="function")m=await m;if(m===G){a.info(`[scheduler] runMissed slot ${d.toISOString()} skipped: ${s} is already running`);continue}v++}catch(m){if(a.error(`[scheduler] runMissed slot ${d.toISOString()} failed: ${m instanceof Error?m.message:String(m)}`),this.options.catch)this.options.catch(m)}return v}static listJobs(){let t=[];for(let[e,n]of c.jobs)t.push({name:e,pattern:n.pattern,timezone:n.timezone,nextRun:n.nextRun?n.nextRun():null,enabled:c.isEnabled(e)});return t}static async runNow(t,e={}){let n=c.jobs.get(t);if(!n)throw Error(`Scheduled task "${t}" was not found.`);if(!c.isEnabled(t))throw Error(`Scheduled task "${t}" is paused.`);let r=e.inProcess?c.inProcessRuns.get(t):void 0;await(r?r():n.run())}static setEnabled(t,e){let n=c.disabledJobs();if(e)n.delete(t);else n.add(t);let r=O(process.cwd(),"storage","framework","runtime");yt(r,{recursive:!0});let s=`${c.stateFile}.${process.pid}.tmp`;vt(s,`${JSON.stringify({disabled:[...n].sort()},null,2)}
|
|
3
|
-
`,{mode:384}),St(s,c.stateFile)}static isEnabled(t){return!c.disabledJobs().has(t)}static isScheduled(t){return c.jobs.has(t)}static disabledJobs(){try{let t=JSON.parse(kt(c.stateFile,"utf8"));return new Set(Array.isArray(t.disabled)?t.disabled.filter((e)=>typeof e==="string"):[])}catch{return new Set}}static listLocks(){return Array.from(c.activeLocks.keys())}async acquireLock(t){if(c.activeLocks.has(t))return!1;let e=this.overlapExpiresAfterMinutes*60*1000,{dialect:n,adminDb:r}=this.shouldRunOnOneServer?await this.oneServerDb(!0):{dialect:null,adminDb:null},s=await B(t,e,n,r,c.lockDir);if(!s)return!1;return c.activeLocks.set(t,s),!0}async oneServerDb(t){try{let{db:e}=await import("@stacksjs/database/runtime"),n=e,r=(await import("@stacksjs/env")).env.DB_CONNECTION||"sqlite";return{dialect:r==="postgres"||r==="mysql"||r==="sqlite"?r:null,adminDb:n}}catch(e){if(t)a.warn(`[scheduler] onOneServer() couldn't reach DB; falling back to file-only lock (which only serializes within this process): ${e instanceof Error?e.message:String(e)}`);return{dialect:null,adminDb:null}}}async claimSlot(t,e){if(!this.shouldRunOnOneServer)return!0;let{dialect:n,adminDb:r}=await this.oneServerDb(!1);return W(t,e,n,r)}async releaseLock(t){let e=c.activeLocks.get(t);if(!e)return;c.activeLocks.delete(t),await e.release()}wrapTask(t,e=!1){let n=this.options.name||"unnamed-task",r=t;if(this.shouldPreventOverlap||this.shouldRunOnOneServer){let s=this,i=r;r=()=>(async()=>{if(!await s.acquireLock(n))return a.info(`Skipping overlapping task: ${n}`),G;try{let u=i();if(u&&typeof u==="object"&&typeof u.finally==="function")await u}finally{try{await s.releaseLock(n)}catch(u){a.error(`[scheduler] releasing the lock for ${n} failed: ${u instanceof Error?u.message:String(u)}`)}}})()}if(this.shouldRunInBackground&&!e){let s=O(process.cwd(),"buddy"),i=this.handlesOwnOutput?null:this.outputPath,o=this.outputAppend;r=()=>{let u="inherit";if(i)try{u=bt(i,o?"a":"w")}catch(h){a.warn(`[scheduler] couldn't open ${i} for background task ${n}: ${h instanceof Error?h.message:String(h)}; its output goes to this process instead`)}let l=()=>{if(typeof u!=="number")return;try{wt(u)}catch{}u="inherit"},p=pt(s,["schedule:run-one",n,"--in-process"],{cwd:process.cwd(),detached:!0,stdio:["ignore",u,u]});l(),p.on("error",(h)=>{a.error(`[scheduler] background task ${n} failed to start (${s}): ${h.message}`)}),p.on("exit",(h,g)=>{if(h!==0&&h!==null)a.error(`[scheduler] background task ${n} (pid: ${p.pid}) exited with code ${h}`);else if(g)a.warn(`[scheduler] background task ${n} (pid: ${p.pid}) terminated by signal ${g}`)}),p.unref(),a.info(`Task ${n} spawned in background (pid: ${p.pid})`)}}return r}getNextRunTime(){if(!this.cronPattern||this.intervalMs!==null)return null;let{startAt:t,stopAt:e}=this.options,n=Date.now(),r=t&&t.getTime()>n?t.getTime()-1:n,s=this.nextCronTime(r);if(s&&e&&s.getTime()>e.getTime())return null;return s}zone(){if(this.timezone)return this.timezone;return Et.app?.timezone||"UTC"}nextCronTime(t){let e=this.zone();if(e==="UTC")return E(this.cronPattern,t);return E(this.cronPattern,t,{tz:e})}start(){if(!this.cronPattern&&this.intervalMs===null)return{stop:()=>{},run:async()=>{},nextRun:()=>null};let t=this.options.name?`${this.options.name.toLowerCase().replace(/[^a-z0-9]+/g,"")}::${this.cronPattern||`every:${this.intervalMs}`}`:null;if(t){let d=c.scheduledKeys.get(t);if(d)return a.debug(`[scheduler] duplicate schedule for "${this.options.name}" (${this.cronPattern||`every ${this.intervalMs}ms`}) skipped`),d}if(this.shouldRunInBackground&&!this.options.name)throw Error("runInBackground() needs a named task: add .withName(...) so the background process can find it");let e=this.options.context,n=e===void 0?this.task:()=>this.task(e),r=this.wrapTask(n),s=this.shouldRunInBackground?this.wrapTask(n,!0):r,i=!1,o=!1,u=null,l=null,p=0,h=()=>{if(i=!0,l!==null){if(this.intervalMs!==null)clearInterval(l);else clearTimeout(l);l=null}},g=()=>this.getNextRunTime(),f=this.options.name||"unnamed-task",w=async(d,m)=>{if(!c.isEnabled(f)){a.debug(`[scheduler] task ${f} is paused`);return}let{startAt:k,stopAt:y,interval:P,protect:A}=this.options,D=Date.now();if(y&&D>y.getTime()){a.debug(`[scheduler] task ${f} is past its between() window; stopping`),h();return}if(k&&D<k.getTime()){a.debug(`[scheduler] task ${f} has not reached its between() window`);return}if(this.options.maxRuns&&p>=this.options.maxRuns){h();return}if(A&&o){if(a.debug(`[scheduler] task ${f} is still running; skipping this tick (withProtection)`),typeof A==="function")A(v);return}if(P&&u!==null&&D-u<P*1000){a.debug(`[scheduler] task ${f} ran less than ${P}s ago; skipping this tick (withInterval)`);return}if(m!==void 0){let S;try{S=await this.claimSlot(f,m)}catch(j){throw b(j),j}if(!S){a.info(`[scheduler] task ${f} slot ${new Date(m).toISOString()} skipped: another server claimed it (onOneServer)`);return}}p++,o=!0,u=D;try{let S=d();if(S&&typeof S.then==="function")await S}catch(S){throw b(S),S}finally{o=!1}},b=(d)=>{if(this.options.catch)this.options.catch(d);else a.error(`[scheduler] task ${f} failed (no withErrorHandler() installed): ${d instanceof Error?d.message:String(d)}`)},N=(d)=>w(r,d),v={stop:h,run:()=>w(r),nextRun:g,pattern:this.intervalMs!==null?`every ${this.intervalMs/1000}s`:this.cronPattern,timezone:this.zone(),name:this.options.name,enabled:c.isEnabled(f)};if(this.intervalMs!==null){let d=this.intervalMs;l=setInterval(()=>{if(i)return;N(Math.floor(Date.now()/d)*d).catch(()=>{})},d),l.unref?.()}else if(this.cronPattern){let m=()=>{if(i)return;if(this.options.maxRuns&&p>=this.options.maxRuns)return;let k=this.getNextRunTime();if(!k){h();return}let y=Math.max(k.getTime()-Date.now(),0);if(y>2147483647)l=setTimeout(()=>{if(i)return;m()},2147483647);else l=setTimeout(()=>{if(i)return;N(k.getTime()).catch(()=>{}),m()},y)};m()}if(this.options.name)c.jobs.set(this.options.name,v),c.inProcessRuns.set(this.options.name,()=>w(s));if(t)c.scheduledKeys.set(t,v);return a.info(`Scheduled task with pattern: ${this.cronPattern} in timezone: ${this.zone()}`),v}static job(t){let e=null;return e=new c(async(n)=>{let r=e?.dispatchQueue??null;try{if(r!==null){a.info(`Dispatching job: ${t} to queue ${r}`);let s=Nt(t).onQueue(r);await(n===void 0?s:s.withContext(n)).dispatch();return}a.info(`Running job: ${t}`),await Dt(t,n===void 0?{}:{context:n})}catch(s){throw a.error(`Job ${t} failed:`,s),s}}),e.jobName=t,e.withName(t)}static action(t){return new c(async()=>{a.info(`Running action: ${t}`);try{await $t(t)}catch(e){throw a.error(`Action ${t} failed:`,e),e}}).withName(t)}static command(t){let e=null;return e=new c(async()=>{let r=e?.outputPath??null,s=e?.outputAppend??!1;try{if(a.info(`Executing command: ${t}`),r){let{spawn:o}=await import("child_process"),{openSync:u,closeSync:l}=await import("fs"),h=u(r,s?"a":"w");try{await new Promise((g,f)=>{let w=o(t,{shell:!0,stdio:["ignore",h,h]});w.on("error",f),w.on("exit",(b)=>{if(b===0)g();else f(Error(`Command '${t}' exited with code ${b}`))})})}finally{l(h)}return}let i=await Tt(t);if(i.isErr)throw a.error(i.error),i.error}catch(i){throw a.error(`Command execution failed: ${i}`),i}}),e.handlesOwnOutput=!0,e.withName(`command-${t}`)}static notification(t,e,n,r){return new c(async()=>{try{let{notify:s}=await import("@stacksjs/notifications"),i=await s(t,e,n,r),o=i.filter((u)=>!u.success);if(o.length>0){let u=o.map((l)=>`${l.channel}: ${l.error?.message??"not delivered"}`).join("; ");throw Error(`Scheduled notification was not delivered on ${o.length} of ${i.length} channel(s) - ${u}`)}}catch(s){throw a.error("Scheduled notification failed:",s),s}}).withName(xt(t,e,n,r))}static async gracefulShutdown(){a.info("Gracefully shutting down scheduled jobs...");for(let[t,e]of c.jobs)a.info(`Stopping job: ${t}`),e.stop();c.jobs.clear(),c.inProcessRuns.clear(),c.scheduledKeys.clear(),a.info("All jobs have been stopped")}}class Ot extends c{}function Pt(t){if(t instanceof Date)return t>new Date?t:null;return E(t)}function re(t){let e=Pt(t);if(!e)return-1;return e.getTime()-Date.now()}var se=c;export{Ot as Queue,c as Schedule,jt as runScheduler,se as schedule,Pt as sendAt,re as timeout};
|
|
1
|
+
export*from"./run";export*from"./schedule";export*from"./types";
|
package/dist/run.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{schedule}from"@stacksjs/scheduler";import{globSync}from"@stacksjs/storage";export async function runScheduler(){const jobFiles=globSync([path.appPath("Jobs/*.ts")],{absolute:true});await runSchedulerInstance();for(const jobFile of jobFiles){try{const jobModule=await import(jobFile);const job=jobModule.default;const jobName=getJobName(jobFile);if(job.enabled===false||!job.rate)continue;const scheduledAs=[jobName,job.name].find((name)=>typeof name==="string"&&schedule.isScheduled(name));if(scheduledAs){log.debug(`[scheduler] ${scheduledAs} is declared in app/Scheduler.ts; ignoring its \`rate\` so it is not scheduled twice`);continue}executeJobRate(jobName,job.rate)}catch(error){log.error(`[scheduler] could not schedule ${jobFile}: ${error instanceof Error?error.message:String(error)}`)}}return ok("Schedules ran successfully")}async function runSchedulerInstance(){const schedulerFile=path.appPath("Scheduler.ts");try{const scheduleInstance=await import(schedulerFile);if(typeof scheduleInstance.default==="function"){scheduleInstance.default()}else{console.warn(`Scheduler file ${schedulerFile} does not export a default function`)}}catch(error){console.warn(`Could not load scheduler file ${schedulerFile}:`,error)}}function executeJobRate(jobName,rate){schedule.job(jobName).cron(rate)}function getJobName(jobPath){const baseName=path.basename(jobPath);return baseName.replace(/\.ts$/,"")}
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{closeSync,mkdirSync,openSync,readFileSync,renameSync,writeFileSync}from"node:fs";import{join}from"node:path";import{runNamedAction}from"@stacksjs/action-runner";import{log,runCommand}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{parse}from"@stacksjs/cron";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=join(process.cwd(),"storage","framework","locks");static stateFile=join(process.cwd(),"storage","framework","runtime","scheduler-state.json");static activeLocks=new Map;static inProcessRuns=new Map;shouldPreventOverlap=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}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=[];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)})}return out}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);const directory=join(process.cwd(),"storage","framework","runtime");mkdirSync(directory,{recursive:true});const temporary=`${Schedule.stateFile}.${process.pid}.tmp`;writeFileSync(temporary,`${JSON.stringify({disabled:[...disabled].sort()},null,2)}
|
|
2
|
+
`,{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(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;try{const result=body();if(result&&typeof result.then==="function")await result}catch(error){reportFailure(error);throw error}finally{running=false}};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(){log.info("Gracefully shutting down scheduled jobs...");for(const[name,job]of Schedule.jobs){log.info(`Stopping job: ${name}`);job.stop()}Schedule.jobs.clear();Schedule.inProcessRuns.clear();Schedule.scheduledKeys.clear();log.info("All jobs have been stopped")}}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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";import{lockFileName,pluckFirstRow}from"./scheduler-lock";export const SCHEDULER_CLAIMS_TABLE="scheduler_claims";export const SCHEDULER_CLAIM_RETENTION_MS=24*60*60*1000;export function schedulerClaimsTableSql(){return`CREATE TABLE IF NOT EXISTS ${SCHEDULER_CLAIMS_TABLE} (`+"task VARCHAR(128) NOT NULL,"+"slot BIGINT NOT NULL,"+"claimant CHAR(36) NOT NULL,"+"PRIMARY KEY (task, slot)"+")"}const tablesReady=new WeakMap;function ensureClaimsTable(adminDb){let ready=tablesReady.get(adminDb);if(!ready){ready=(async()=>{try{await adminDb.unsafe(schedulerClaimsTableSql())}catch{await adminDb.unsafe(schedulerClaimsTableSql())}})();tablesReady.set(adminDb,ready);ready.catch(()=>tablesReady.delete(adminDb))}return ready}export async function claimSchedulerSlot(taskName,slot,dialect,adminDb){if(!adminDb||dialect!=="postgres"&&dialect!=="mysql")return true;await ensureClaimsTable(adminDb);const task=lockFileName(taskName).replace(/\.lock$/,"");const at=Math.trunc(slot);const claimant=randomUUID();const values=`('${task}', ${at}, '${claimant}')`;await adminDb.unsafe(dialect==="postgres"?`INSERT INTO ${SCHEDULER_CLAIMS_TABLE} (task, slot, claimant) VALUES ${values} ON CONFLICT (task, slot) DO NOTHING`:`INSERT INTO ${SCHEDULER_CLAIMS_TABLE} (task, slot, claimant) VALUES ${values} ON DUPLICATE KEY UPDATE task = task`);const row=pluckFirstRow(await adminDb.unsafe(`SELECT claimant FROM ${SCHEDULER_CLAIMS_TABLE} WHERE task = '${task}' AND slot = ${at}`));const won=typeof row?.claimant==="string"&&row.claimant.trim()===claimant;if(won){await adminDb.unsafe(`DELETE FROM ${SCHEDULER_CLAIMS_TABLE} WHERE task = '${task}' AND slot < ${at-SCHEDULER_CLAIM_RETENTION_MS}`)}return won}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{existsSync,mkdirSync,readFileSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";const KEY_PREFIX="stacks_scheduler";function safeLockAgeMs(body){const delta=Date.now()-body.acquiredAt;if(delta<0)return 0;return delta}export function lockFileName(taskName){const readable=taskName.replace(/[^\w.-]+/g,"_").replace(/^\.+/,"_").slice(0,80);const digest=createHash("sha256").update(taskName).digest("hex").slice(0,12);return`${readable}-${digest}.lock`}export async function acquireSchedulerLock(taskName,expiryMs,dialect,adminDb,lockDir){const resolvedDir=lockDir??join(process.cwd(),"storage","framework","locks");const lockFile=join(resolvedDir,lockFileName(taskName));if(!existsSync(resolvedDir)){mkdirSync(resolvedDir,{recursive:true})}let dbReleased=false;let dbRelease=null;if(adminDb&&(dialect==="postgres"||dialect==="mysql")){const acquired=await tryDbLock(taskName,dialect,adminDb);if(!acquired)return null;dbRelease=async()=>{if(dbReleased)return;dbReleased=true;await releaseDbLock(taskName,dialect,adminDb).catch(()=>{})}}const fileBody={token:randomUUID(),acquiredAt:Date.now(),monotonicStart:Math.round(performance.now()),holder:process.pid};try{writeFileSync(lockFile,JSON.stringify(fileBody),{flag:"wx"})}catch{let stale=false;try{const raw=readFileSync(lockFile,"utf8");const body=JSON.parse(raw);const ageMs=safeLockAgeMs(body);if(ageMs>=expiryMs)stale=true}catch{try{const stats=statSync(lockFile);const ageMs=Math.max(0,Date.now()-stats.mtimeMs);if(ageMs>=expiryMs)stale=true}catch{stale=true}}if(!stale){if(dbRelease)await dbRelease();return null}try{writeFileSync(lockFile,JSON.stringify(fileBody))}catch{if(dbRelease)await dbRelease();return null}}let released=false;return{release:async()=>{if(released)return;released=true;try{const current=JSON.parse(readFileSync(lockFile,"utf8"));if(current.token===fileBody.token)unlinkSync(lockFile)}catch{}if(dbRelease)await dbRelease()}}}function pgKeys(taskName){const hash=createHash("sha256").update(`${KEY_PREFIX}:${taskName}`).digest();return{key1:hash.readInt32BE(0),key2:hash.readInt32BE(4)}}async function tryDbLock(taskName,dialect,adminDb){if(dialect==="postgres"){const{key1,key2}=pgKeys(taskName);const result=await adminDb.unsafe(`SELECT pg_try_advisory_lock(${key1}, ${key2}) AS acquired`);return extractFirstBool(result,"acquired")}const lockName=lockNameForMysql(taskName);const result=await adminDb.unsafe(`SELECT GET_LOCK('${lockName}', 0) AS acquired`);return extractFirstInt(result,"acquired")===1}async function releaseDbLock(taskName,dialect,adminDb){if(dialect==="postgres"){const{key1,key2}=pgKeys(taskName);await adminDb.unsafe(`SELECT pg_advisory_unlock(${key1}, ${key2})`);return}const lockName=lockNameForMysql(taskName);await adminDb.unsafe(`SELECT RELEASE_LOCK('${lockName}')`)}function lockNameForMysql(taskName){const hashed=createHash("sha256").update(taskName).digest("hex").slice(0,32);return`${KEY_PREFIX}_${hashed}`}function extractFirstBool(result,column){const row=pluckFirstRow(result);if(!row)return false;const value=row[column];return value===true||value===1||value==="1"||value==="t"}function extractFirstInt(result,column){const row=pluckFirstRow(result);if(!row)return null;const value=row[column];if(typeof value==="number")return value;if(typeof value==="string"&&/^-?\d+$/.test(value))return Number.parseInt(value,10);return null}export function pluckFirstRow(result){if(!result)return null;if(Array.isArray(result))return result[0];if(typeof result==="object"&&"rows"in result&&Array.isArray(result.rows))return result.rows[0];return null}
|
package/dist/types.js
ADDED
|
File without changes
|
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.
|
|
5
|
+
"version": "0.75.552",
|
|
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.
|
|
62
|
-
"@stacksjs/cli": "0.75.
|
|
63
|
-
"@stacksjs/config": "0.75.
|
|
64
|
-
"@stacksjs/cron": "0.75.
|
|
65
|
-
"@stacksjs/database": "0.75.
|
|
66
|
-
"@stacksjs/env": "0.75.
|
|
67
|
-
"@stacksjs/error-handling": "0.75.
|
|
68
|
-
"@stacksjs/logging": "0.75.
|
|
69
|
-
"@stacksjs/notifications": "0.75.
|
|
70
|
-
"@stacksjs/path": "0.75.
|
|
71
|
-
"@stacksjs/queue": "0.75.
|
|
72
|
-
"@stacksjs/storage": "0.75.
|
|
73
|
-
"@stacksjs/types": "0.75.
|
|
61
|
+
"@stacksjs/action-runner": "0.75.552",
|
|
62
|
+
"@stacksjs/cli": "0.75.552",
|
|
63
|
+
"@stacksjs/config": "0.75.552",
|
|
64
|
+
"@stacksjs/cron": "0.75.552",
|
|
65
|
+
"@stacksjs/database": "0.75.552",
|
|
66
|
+
"@stacksjs/env": "0.75.552",
|
|
67
|
+
"@stacksjs/error-handling": "0.75.552",
|
|
68
|
+
"@stacksjs/logging": "0.75.552",
|
|
69
|
+
"@stacksjs/notifications": "0.75.552",
|
|
70
|
+
"@stacksjs/path": "0.75.552",
|
|
71
|
+
"@stacksjs/queue": "0.75.552",
|
|
72
|
+
"@stacksjs/storage": "0.75.552",
|
|
73
|
+
"@stacksjs/types": "0.75.552"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"better-dx": "^0.2.24"
|