@stacksjs/queue 0.75.514 → 0.75.518

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/action.js CHANGED
@@ -1 +1 @@
1
- import{resolveQueueDriver}from"./driver";import{assertEnvelopeSerializable,createEnvelope,serializeEnvelope}from"./envelope";import{runNamedAction}from"./action-runner";let testingModule,databaseModule;function getQueueDriver(){return resolveQueueDriver()}export class Job{name;description;action;handle;queue;rate;tries;timeout;backoff;backoffConfig;enabled;constructor(options){this.name=options.name;this.description=options.description;this.handle=options.handle;this.queue=options.queue;this.rate=options.rate;this.action=options.action;this.tries=options.tries;this.timeout=options.timeout;this.backoff=options.backoff;this.backoffConfig=options.backoffConfig;this.enabled=options.enabled}async dispatch(...[payload]){const{isFaked,getFakeQueue}=await(testingModule??=import("./testing").catch((error)=>{testingModule=void 0;throw error}));if(isFaked()){getFakeQueue()?.dispatch(this.name||"UnknownJob",payload,{queue:this.queue,tries:this.tries,timeout:this.timeout});return}const driver=getQueueDriver();if(driver==="sync")return this.dispatchNow(...[payload]);if(driver==="redis")return this.dispatchToRedis(payload);if(driver==="database")return this.dispatchToDatabase(payload);if(driver==="sqs"||driver==="memory"||driver==="beanstalkd")throw Error(`[queue] Driver "${driver}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`);throw Error(`[queue] Unknown QUEUE_DRIVER "${driver}". Allowed values: redis, database, sync.`)}async dispatchIf(condition,...[payload]){if(condition)return this.dispatch(...[payload])}async dispatchUnless(condition,...[payload]){if(!condition)return this.dispatch(...[payload])}async dispatchAfter(delaySeconds,...[payload]){const driver=getQueueDriver();if(driver==="redis")return this.dispatchToRedis(payload,{delay:delaySeconds});if(driver==="database")return this.dispatchToDatabase(payload,{delay:delaySeconds});await new Promise((resolve)=>setTimeout(resolve,delaySeconds*1000));return await this.dispatchNow(...[payload])}async dispatchNow(...[payload]){if(typeof this.handle==="function")await this.handle(payload);else if(typeof this.action==="string")await runNamedAction(this.action);else if(typeof this.action==="function")await this.action();else throw Error(`Job ${this.name} does not have a valid handler`)}async dispatchToDatabase(payload,opts){const now=Math.floor(Date.now()/1000),availableAt=opts?.delay?now+opts.delay:now,envelope=createEnvelope(this.name??this.constructor.name,payload,{queue:this.queue??"default",tries:typeof this.tries==="number"?this.tries:void 0,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:void 0}),payloadJson=serializeEnvelope(envelope),{db}=await(databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=void 0;throw error}));await db.insertInto("jobs").values({queue:this.queue||"default",payload:payloadJson,attempts:0,reserved_at:null,available_at:availableAt,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}async dispatchToRedis(payload,opts){const envelope=createEnvelope(this.name??this.constructor.name,payload,{queue:this.queue??"default",tries:typeof this.tries==="number"?this.tries:void 0,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:void 0});assertEnvelopeSerializable(envelope);const{sharedRedisQueue}=await import("./drivers/redis"),{queue:queueConfig}=await import("@stacksjs/config"),redisConfig=queueConfig?.connections?.redis;if(!redisConfig)throw Error("Redis queue connection is not configured. Check config/queue.ts");await sharedRedisQueue(this.queue||"default",redisConfig).add(envelope,{delay:opts?.delay,maxTries:typeof this.tries==="number"?this.tries:void 0,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:void 0})}}
1
+ import{resolveQueueDriver}from"./driver";import{assertEnvelopeSerializable,createEnvelope,serializeEnvelope}from"./envelope";import{runNamedAction}from"./action-runner";let testingModule;let databaseModule;function getQueueDriver(){return resolveQueueDriver()}export class Job{name;description;action;handle;queue;rate;tries;timeout;backoff;backoffConfig;enabled;constructor(options){this.name=options.name;this.description=options.description;this.handle=options.handle;this.queue=options.queue;this.rate=options.rate;this.action=options.action;this.tries=options.tries;this.timeout=options.timeout;this.backoff=options.backoff;this.backoffConfig=options.backoffConfig;this.enabled=options.enabled}async dispatch(...[payload]){const{isFaked,getFakeQueue}=await(testingModule??=import("./testing").catch((error)=>{testingModule=undefined;throw error}));if(isFaked()){getFakeQueue()?.dispatch(this.name||"UnknownJob",payload,{queue:this.queue,tries:this.tries,timeout:this.timeout});return}const driver=getQueueDriver();if(driver==="sync"){return this.dispatchNow(...[payload])}if(driver==="redis"){return this.dispatchToRedis(payload)}if(driver==="database"){return this.dispatchToDatabase(payload)}if(driver==="sqs"||driver==="memory"||driver==="beanstalkd"){throw new Error(`[queue] Driver "${driver}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`)}throw new Error(`[queue] Unknown QUEUE_DRIVER "${driver}". Allowed values: redis, database, sync.`)}async dispatchIf(condition,...[payload]){if(condition){return this.dispatch(...[payload])}}async dispatchUnless(condition,...[payload]){if(!condition){return this.dispatch(...[payload])}}async dispatchAfter(delaySeconds,...[payload]){const driver=getQueueDriver();if(driver==="redis"){return this.dispatchToRedis(payload,{delay:delaySeconds})}if(driver==="database"){return this.dispatchToDatabase(payload,{delay:delaySeconds})}await new Promise((resolve)=>setTimeout(resolve,delaySeconds*1000));return await this.dispatchNow(...[payload])}async dispatchNow(...[payload]){if(typeof this.handle==="function"){await this.handle(payload)}else if(typeof this.action==="string"){await runNamedAction(this.action)}else if(typeof this.action==="function"){await this.action()}else{throw new Error(`Job ${this.name} does not have a valid handler`)}}async dispatchToDatabase(payload,opts){const now=Math.floor(Date.now()/1000);const availableAt=opts?.delay?now+opts.delay:now;const envelope=createEnvelope(this.name??this.constructor.name,payload,{queue:this.queue??"default",tries:typeof this.tries==="number"?this.tries:undefined,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:undefined});const payloadJson=serializeEnvelope(envelope);const{db}=await(databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=undefined;throw error}));await db.insertInto("jobs").values({queue:this.queue||"default",payload:payloadJson,attempts:0,reserved_at:null,available_at:availableAt,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}async dispatchToRedis(payload,opts){const envelope=createEnvelope(this.name??this.constructor.name,payload,{queue:this.queue??"default",tries:typeof this.tries==="number"?this.tries:undefined,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:undefined});assertEnvelopeSerializable(envelope);const{sharedRedisQueue}=await import("./drivers/redis");const{queue:queueConfig}=await import("@stacksjs/config");const redisConfig=queueConfig?.connections?.redis;if(!redisConfig){throw new Error("Redis queue connection is not configured. Check config/queue.ts")}const queue=sharedRedisQueue(this.queue||"default",redisConfig);await queue.add(envelope,{delay:opts?.delay,maxTries:typeof this.tries==="number"?this.tries:undefined,timeout:this.timeout,backoff:Array.isArray(this.backoff)||typeof this.backoff==="number"?this.backoff:undefined})}}
@@ -1 +1 @@
1
- export function batchMembershipId(payload){if(!payload||typeof payload!=="object")return;const data=payload;if(data._batchTerminalHandler===!0)return;return typeof data._batchId==="string"&&data._batchId?data._batchId:void 0}export function batchMemberPayload(payload,batchId,index){return{...payload??{},_batchId:batchId,_batchIndex:index,_batchTerminalHandler:!1}}export function batchTerminalPayload(payload,batchId){return{...payload??{},_batchId:batchId,_batchTerminalHandler:!0}}
1
+ export function batchMembershipId(payload){if(!payload||typeof payload!=="object")return;const data=payload;if(data._batchTerminalHandler===true)return;return typeof data._batchId==="string"&&data._batchId?data._batchId:undefined}export function batchMemberPayload(payload,batchId,index){return{...payload??{},_batchId:batchId,_batchIndex:index,_batchTerminalHandler:false}}export function batchTerminalPayload(payload,batchId){return{...payload??{},_batchId:batchId,_batchTerminalHandler:true}}
package/dist/batch.js CHANGED
@@ -1 +1 @@
1
- import{batchMemberPayload,batchTerminalPayload}from"./batch-payload";import{RedisClient}from"bun";import{log}from"@stacksjs/logging";import{env as envVars}from"@stacksjs/env";import{updatedRowCount}from"./utils";function getQueueDriver(){return envVars.QUEUE_DRIVER||"sync"}export class PendingBatch{jobs;options={thenCallbacks:[],catchCallbacks:[],finallyCallbacks:[],progressCallbacks:[]};constructor(jobs){this.jobs=jobs.map((j)=>("job"in j)?j:{job:j})}name(name){this.options.name=name;return this}onQueue(queue){this.options.queue=queue;return this}allowFailures(){this.options.allowFailures=!0;return this}then(callback){this.options.thenCallbacks.push(callback);return this}catch(callback){this.options.catchCallbacks.push(callback);return this}finally(callback){this.options.finallyCallbacks.push(callback);return this}progress(callback){this.options.progressCallbacks.push(callback);return this}thenHandler(handler){this.options.thenHandler=handler;return this}catchHandler(handler){this.options.catchHandler=handler;return this}finallyHandler(handler){this.options.finallyHandler=handler;return this}async dispatch(){const batchId=crypto.randomUUID(),totalJobs=this.jobs.length;if(totalJobs===0)throw Error("Cannot dispatch an empty batch");const driver=getQueueDriver();await storeBatchRecord({id:batchId,name:this.options.name||"",total_jobs:totalJobs,pending_jobs:totalJobs,failed_jobs:0,failed_job_ids:"[]",options:JSON.stringify({queue:this.options.queue,allowFailures:this.options.allowFailures||!1}),cancelled_at:null,created_at:new Date().toISOString().slice(0,19).replace("T"," "),finished_at:null,then_handler:this.options.thenHandler?JSON.stringify(this.options.thenHandler):null,catch_handler:this.options.catchHandler?JSON.stringify(this.options.catchHandler):null,finally_handler:this.options.finallyHandler?JSON.stringify(this.options.finallyHandler):null});registerBatchCallbacks(batchId,this.options);try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:added",{jobId:batchId,data:{name:this.options.name,totalJobs}})}catch{}for(let i=0;i<this.jobs.length;i++){const entry=this.jobs[i];if(!entry)continue;const{job,payload}=entry,jobPayload=batchMemberPayload(payload,batchId,i);if(this.options.queue&&!job.queue)job.queue=this.options.queue;if(driver==="sync")try{await job.dispatchNow(jobPayload);await recordBatchJobCompletion(batchId)}catch(error){await recordBatchJobFailure(batchId,`${batchId}:${i}`,error)}else await job.dispatch(jobPayload)}log.info(`[Batch] Dispatched batch "${this.options.name||batchId}" with ${totalJobs} jobs`);return new DispatchedBatch(batchId)}getJobs(){return[...this.jobs]}getOptions(){return this.options}}export class DispatchedBatch{id;constructor(id){this.id=id}async fresh(){return getBatchRecord(this.id)}async getName(){return(await this.fresh())?.name||""}async totalJobs(){return(await this.fresh())?.total_jobs||0}async pendingJobs(){return(await this.fresh())?.pending_jobs||0}async failedJobs(){return(await this.fresh())?.failed_jobs||0}async completedJobs(){const record=await this.fresh();if(!record)return 0;return record.total_jobs-record.pending_jobs}async progress(){const record=await this.fresh();if(!record||record.total_jobs===0)return 0;const completed=record.total_jobs-record.pending_jobs;return Math.round(completed/record.total_jobs*100)}async finished(){return(await this.fresh())?.finished_at!==null}async cancelled(){return(await this.fresh())?.cancelled_at!==null}async hasFailures(){return((await this.fresh())?.failed_jobs||0)>0}async failedJobIds(){const record=await this.fresh();if(!record)return[];try{return JSON.parse(record.failed_job_ids||"[]")}catch{return[]}}async cancel(){if(getQueueDriver()==="redis")await cancelBatchInRedis(this.id);else await cancelBatchInDatabase(this.id);log.info(`[Batch] Cancelled batch ${this.id}`);const callbacks=getBatchCallbacks(this.id);if(callbacks)for(const cb of callbacks.finallyCallbacks)try{await cb(this)}catch(e){log.error(`[Batch] Error in finally callback for batch ${this.id}:`,e)}}async add(jobs){const record=await this.fresh();if(!record)throw Error(`Batch ${this.id} not found`);if(record.cancelled_at)throw Error(`Batch ${this.id} has been cancelled`);if(record.finished_at)throw Error(`Batch ${this.id} has already finished`);const batchableJobs=jobs.map((j)=>("job"in j)?j:{job:j});if(!await incrementBatchCounters(this.id,batchableJobs.length))throw Error(`Batch ${this.id} was cancelled, finished or deleted before the jobs could be added`);const options=JSON.parse(record.options||"{}");for(let i=0;i<batchableJobs.length;i++){const entry=batchableJobs[i];if(!entry)continue;const{job,payload}=entry,jobPayload=batchMemberPayload(payload,this.id,record.total_jobs+i);if(options.queue&&!job.queue)job.queue=options.queue;await job.dispatch(jobPayload)}log.info(`[Batch] Added ${batchableJobs.length} jobs to batch ${this.id}`)}async delete(){await deleteBatchRecord(this.id);removeBatchCallbacks(this.id)}}export class Batch{static create(jobs){return new PendingBatch(jobs)}static async find(id){if(!await getBatchRecord(id))return null;return new DispatchedBatch(id)}static async all(){return(await getAllBatchRecords()).map((r)=>new DispatchedBatch(r.id))}static async prune(olderThanHours=24){return pruneBatchRecords(olderThanHours)}}const batchCallbackRegistry=new Map;function registerBatchCallbacks(batchId,options){batchCallbackRegistry.set(batchId,options)}export function getBatchCallbacks(batchId){return batchCallbackRegistry.get(batchId)}function removeBatchCallbacks(batchId){batchCallbackRegistry.delete(batchId)}async function storeBatchRecord(record){if(getQueueDriver()==="redis")await storeBatchInRedis(record);else await storeBatchInDatabase(record)}async function getBatchRecord(id){if(getQueueDriver()==="redis")return getBatchFromRedis(id);return getBatchFromDatabase(id)}async function getAllBatchRecords(){if(getQueueDriver()==="redis")return getAllBatchesFromRedis();return getAllBatchesFromDatabase()}async function updateBatchRecord(id,updates){if(getQueueDriver()==="redis")await updateBatchInRedis(id,updates);else await updateBatchInDatabase(id,updates)}async function incrementBatchCounters(id,delta){if(delta===0)return!0;if(getQueueDriver()==="redis")try{const client=await connectBatchRedis(),key=`${REDIS_BATCH_PREFIX}${id}`;await client.hincrby(key,"total_jobs",delta);await client.hincrby(key,"pending_jobs",delta);client.close();return!0}catch{}const{db,sql}=await import("@stacksjs/database/runtime"),result=await db.updateTable("job_batches").set(batchCounterIncrements(sql,delta)).where("id","=",id).whereNull("cancelled_at").whereNull("finished_at").executeTakeFirst();return updatedRowCount(result)>0}export function batchCounterIncrements(sql,delta){return{total_jobs:sql`total_jobs + ${delta}`,pending_jobs:sql`pending_jobs + ${delta}`}}async function deleteBatchRecord(id){if(getQueueDriver()==="redis")await deleteBatchFromRedis(id);else await deleteBatchFromDatabase(id)}async function pruneBatchRecords(olderThanHours){if(getQueueDriver()==="redis")return pruneBatchesFromRedis(olderThanHours);return pruneBatchesFromDatabase(olderThanHours)}function hasPersistentHandlers(record){return!!(record.then_handler||record.catch_handler||record.finally_handler)}async function storeBatchInDatabase(record){const{db}=await import("@stacksjs/database/runtime"),columns={id:record.id,name:record.name,total_jobs:record.total_jobs,pending_jobs:record.pending_jobs,failed_jobs:record.failed_jobs,failed_job_ids:record.failed_job_ids,options:record.options,cancelled_at:record.cancelled_at,created_at:record.created_at,finished_at:record.finished_at};if(!hasPersistentHandlers(record)){await db.insertInto("job_batches").values(columns).execute();return}try{await db.insertInto("job_batches").values({...columns,then_handler:record.then_handler??null,catch_handler:record.catch_handler??null,finally_handler:record.finally_handler??null}).execute()}catch(error){log.warn(`[Batch] Could not persist terminal handlers for batch ${record.id}: ${error?.message}. The job_batches table predates the then_handler/catch_handler/finally_handler columns; recreate it to enable handlers that survive a worker restart.`);await db.insertInto("job_batches").values(columns).execute()}}async function getBatchFromDatabase(id){const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom("job_batches").where("id","=",id).selectAll().executeTakeFirst()||null}async function getAllBatchesFromDatabase(){const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom("job_batches").selectAll().orderBy("created_at","desc").execute()}async function updateBatchInDatabase(id,updates){const{db}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set(updates).where("id","=",id).execute()}async function deleteBatchFromDatabase(id){const{db}=await import("@stacksjs/database/runtime");await db.deleteFrom("job_batches").where("id","=",id).execute()}async function cancelBatchInDatabase(id){await updateBatchInDatabase(id,{cancelled_at:new Date().toISOString().slice(0,19).replace("T"," "),finished_at:new Date().toISOString().slice(0,19).replace("T"," ")})}async function pruneBatchesFromDatabase(olderThanHours){const{db}=await import("@stacksjs/database/runtime"),cutoff=new Date(Date.now()-olderThanHours*60*60*1000).toISOString().slice(0,19).replace("T"," "),result=await db.deleteFrom("job_batches").whereNotNull("finished_at").where("finished_at","<",cutoff).executeTakeFirst();return Number(result?.numDeletedRows??0)}const REDIS_BATCH_PREFIX="stacks:batch:",REDIS_BATCH_INDEX="stacks:batches";async function getRedisClient(){const{sharedRedisQueue}=await import("./drivers/redis"),{queue:queueConfig}=await import("@stacksjs/config"),redisConfig=queueConfig?.connections?.redis;if(!redisConfig)throw Error("Redis queue connection is not configured");return sharedRedisQueue("__batches__",redisConfig)}async function batchRedisUrl(){const{queue:queueConfig}=await import("@stacksjs/config"),redisConfig=queueConfig?.connections?.redis?.redis;if(redisConfig?.url)return redisConfig.url;const auth=redisConfig?.password?`:${encodeURIComponent(redisConfig.password)}@`:"",db=redisConfig?.db?`/${redisConfig.db}`:"";return`redis://${auth}${redisConfig?.host||"localhost"}:${redisConfig?.port||6379}${db}`}async function connectBatchRedis(){const client=new RedisClient(await batchRedisUrl());await client.connect();return client}export function batchRecordToHash(record){return{id:record.id,name:record.name,total_jobs:String(record.total_jobs),pending_jobs:String(record.pending_jobs),failed_jobs:String(record.failed_jobs),failed_job_ids:record.failed_job_ids,options:record.options,cancelled_at:record.cancelled_at||"",created_at:record.created_at,finished_at:record.finished_at||"",then_handler:record.then_handler||"",catch_handler:record.catch_handler||"",finally_handler:record.finally_handler||""}}async function storeBatchInRedis(record){try{const client=await connectBatchRedis();await client.hset(`${REDIS_BATCH_PREFIX}${record.id}`,batchRecordToHash(record));await client.sadd(REDIS_BATCH_INDEX,record.id);client.close()}catch{await storeBatchInDatabase(record)}}export function batchRecordFromHash(data){if(!data?.id)return null;return{id:data.id,name:data.name??"",total_jobs:Number(data.total_jobs),pending_jobs:Number(data.pending_jobs),failed_jobs:Number(data.failed_jobs),failed_job_ids:data.failed_job_ids??"",options:data.options??"",cancelled_at:data.cancelled_at||null,created_at:data.created_at??"",finished_at:data.finished_at||null,then_handler:data.then_handler||null,catch_handler:data.catch_handler||null,finally_handler:data.finally_handler||null}}async function getBatchFromRedis(id){try{const client=await connectBatchRedis(),key=`${REDIS_BATCH_PREFIX}${id}`,data=await client.hgetall(key);client.close();return batchRecordFromHash(data)}catch{return getBatchFromDatabase(id)}}async function getAllBatchesFromRedis(){try{const client=await connectBatchRedis(),ids=await client.smembers(REDIS_BATCH_INDEX),batches=[];for(const id of ids){const record=batchRecordFromHash(await client.hgetall(`${REDIS_BATCH_PREFIX}${id}`));if(record)batches.push(record)}client.close();return batches}catch{return getAllBatchesFromDatabase()}}async function updateBatchInRedis(id,updates){try{const client=await connectBatchRedis(),key=`${REDIS_BATCH_PREFIX}${id}`,hashUpdates={};for(const[k,v]of Object.entries(updates))hashUpdates[k]=v===null?"":String(v);await client.hset(key,hashUpdates);client.close()}catch{await updateBatchInDatabase(id,updates)}}async function decrementBatchInRedis(id,failed,allowFailures){const client=await connectBatchRedis();try{const key=`${REDIS_BATCH_PREFIX}${id}`,decrementedPending=await client.hincrby(key,"pending_jobs",-1),pending=Math.max(decrementedPending,0);if(decrementedPending<0)await client.hset(key,{pending_jobs:"0"});if(failed)await client.hincrby(key,"failed_jobs",1);const shouldFinish=!(await client.hgetall(key)).finished_at&&(!failed||allowFailures?pending===0:!0),finishedAt=new Date().toISOString().slice(0,19).replace("T"," "),completed=shouldFinish&&await client.hsetnx(key,"terminal_claimed","1");if(completed)await client.hset(key,{finished_at:finishedAt});if(completed&&failed&&!allowFailures)await client.hset(key,{cancelled_at:finishedAt});return completed}finally{client.close()}}async function deleteBatchFromRedis(id){try{const client=await connectBatchRedis();await client.del(`${REDIS_BATCH_PREFIX}${id}`);await client.srem(REDIS_BATCH_INDEX,id);client.close()}catch{await deleteBatchFromDatabase(id)}}async function cancelBatchInRedis(id){const now=new Date().toISOString().slice(0,19).replace("T"," ");await updateBatchInRedis(id,{cancelled_at:now,finished_at:now})}async function pruneBatchesFromRedis(olderThanHours){try{const batches=await getAllBatchesFromRedis(),cutoff=Date.now()-olderThanHours*60*60*1000;let pruned=0;for(const batch of batches)if(batch.finished_at){if(new Date(batch.finished_at).getTime()<cutoff){await deleteBatchFromRedis(batch.id);pruned++}}return pruned}catch{return pruneBatchesFromDatabase(olderThanHours)}}function parsePersistentHandler(raw){if(!raw)return null;try{const parsed=JSON.parse(raw);if(parsed&&(parsed.kind==="job"||parsed.kind==="module"))return parsed;log.warn(`[Batch] handler JSON has unknown kind '${parsed?.kind}' - skipping`);return null}catch(err){log.warn(`[Batch] failed to parse persistent handler: ${err.message}`);return null}}async function firePersistentHandler(handler,batchId){try{if(handler.kind==="job"){const{Jobs}=await import("./job");await Jobs.dispatch(handler.name,batchTerminalPayload(handler.payload,batchId));return}const mod=await import(handler.module).catch((err)=>{log.warn(`[Batch] persistent handler module not found: ${handler.module} (${err.message})`);return null});if(!mod)return;const fn=mod[handler.export];if(typeof fn!=="function"){log.warn(`[Batch] persistent handler export '${handler.export}' is not a function on ${handler.module}`);return}await fn(handler.payload,batchId)}catch(err){log.error(`[Batch] persistent handler threw for batch ${batchId}:`,err)}}export async function recordBatchJobCompletion(batchId){const driver=getQueueDriver();let completed=!1;if(driver==="redis")completed=await decrementBatchInRedis(batchId,!1,!1);else{const{db,sql}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set({pending_jobs:sql`GREATEST(pending_jobs - 1, 0)`}).where("id","=",batchId).where("pending_jobs",">",0).execute();const finishedAt=new Date().toISOString().slice(0,19).replace("T"," "),completeResult=await db.updateTable("job_batches").set({finished_at:finishedAt}).where("id","=",batchId).where("pending_jobs","=",0).whereNull("finished_at").executeTakeFirst();completed=updatedRowCount(completeResult)>0}const callbacks=getBatchCallbacks(batchId),dispatched=new DispatchedBatch(batchId);if(callbacks)for(const cb of callbacks.progressCallbacks)try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in progress callback for batch ${batchId}:`,e)}if(completed){try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:completed",{jobId:batchId})}catch{}const freshRecord=await getBatchRecord(batchId);if(!freshRecord){removeBatchCallbacks(batchId);log.info(`[Batch] Batch ${batchId} finished (record vanished)`);return}const opts=JSON.parse(freshRecord.options||"{}"),succeeded=!((freshRecord.failed_jobs||0)>0)||opts.allowFailures;if(callbacks){if(succeeded)for(const cb of callbacks.thenCallbacks)try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in then callback for batch ${batchId}:`,e)}for(const cb of callbacks.finallyCallbacks)try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in finally callback for batch ${batchId}:`,e)}removeBatchCallbacks(batchId)}if(succeeded){const thenHandler=parsePersistentHandler(freshRecord.then_handler);if(thenHandler)await firePersistentHandler(thenHandler,batchId)}else{const catchHandler=parsePersistentHandler(freshRecord.catch_handler);if(catchHandler)await firePersistentHandler(catchHandler,batchId)}const finallyHandler=parsePersistentHandler(freshRecord.finally_handler);if(finallyHandler)await firePersistentHandler(finallyHandler,batchId);log.info(`[Batch] Batch ${batchId} finished`)}}export async function recordBatchJobFailure(batchId,jobId,error){const record=await getBatchRecord(batchId);if(!record)return;const opts=JSON.parse(record.options||"{}"),dispatched=new DispatchedBatch(batchId),callbacks=getBatchCallbacks(batchId);let completed=!1;if(getQueueDriver()==="redis"){completed=await decrementBatchInRedis(batchId,!0,!!opts.allowFailures);const fresh=await getBatchRecord(batchId);if(fresh){let failedIds=[];try{failedIds=JSON.parse(fresh.failed_job_ids||"[]")}catch{failedIds=[]}failedIds.push(jobId);await updateBatchInRedis(batchId,{failed_job_ids:JSON.stringify(failedIds)})}if(callbacks)for(const cb of callbacks.catchCallbacks)try{await cb(dispatched,error)}catch(e){log.error(`[Batch] Error in catch callback for batch ${batchId}:`,e)}try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:failed",{jobId:batchId,error})}catch{}}else{const{db,sql}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set({pending_jobs:sql`GREATEST(pending_jobs - 1, 0)`,failed_jobs:sql`failed_jobs + 1`}).where("id","=",batchId).where("pending_jobs",">",0).execute();try{const fresh=await getBatchRecord(batchId);if(fresh){let failedIds=[];try{failedIds=JSON.parse(fresh.failed_job_ids||"[]")}catch{failedIds=[]}failedIds.push(jobId);await updateBatchRecord(batchId,{failed_job_ids:JSON.stringify(failedIds)})}}catch{}if(callbacks)for(const cb of callbacks.catchCallbacks)try{await cb(dispatched,error)}catch(e){log.error(`[Batch] Error in catch callback for batch ${batchId}:`,e)}try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:failed",{jobId:batchId,error})}catch{}const finishedAt=new Date().toISOString().slice(0,19).replace("T"," ");let finalize=db.updateTable("job_batches").set(opts.allowFailures?{finished_at:finishedAt}:{finished_at:finishedAt,cancelled_at:finishedAt}).where("id","=",batchId).whereNull("finished_at");if(opts.allowFailures)finalize=finalize.where("pending_jobs","=",0);const finalizeResult=await finalize.executeTakeFirst();completed=updatedRowCount(finalizeResult)>0}if(!completed)return;const succeeded=!!opts.allowFailures;if(callbacks){if(succeeded)for(const cb of callbacks.thenCallbacks)try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in then callback for batch ${batchId}:`,e)}for(const cb of callbacks.finallyCallbacks)try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in finally callback for batch ${batchId}:`,e)}removeBatchCallbacks(batchId)}const freshRecord=await getBatchRecord(batchId);if(freshRecord){if(succeeded){const thenHandler=parsePersistentHandler(freshRecord.then_handler);if(thenHandler)await firePersistentHandler(thenHandler,batchId)}else{const catchHandler=parsePersistentHandler(freshRecord.catch_handler);if(catchHandler)await firePersistentHandler(catchHandler,batchId)}const finallyHandler=parsePersistentHandler(freshRecord.finally_handler);if(finallyHandler)await firePersistentHandler(finallyHandler,batchId)}log.info(`[Batch] Batch ${batchId} finished with failure(s)`)}export async function isBatchCancelled(batchId){return(await getBatchRecord(batchId))?.cancelled_at!==null}
1
+ import{batchMemberPayload,batchTerminalPayload}from"./batch-payload";import{RedisClient}from"bun";import{log}from"@stacksjs/logging";import{env as envVars}from"@stacksjs/env";import{updatedRowCount}from"./utils";function getQueueDriver(){return envVars.QUEUE_DRIVER||"sync"}export class PendingBatch{jobs;options={thenCallbacks:[],catchCallbacks:[],finallyCallbacks:[],progressCallbacks:[]};constructor(jobs){this.jobs=jobs.map((j)=>("job"in j)?j:{job:j})}name(name){this.options.name=name;return this}onQueue(queue){this.options.queue=queue;return this}allowFailures(){this.options.allowFailures=true;return this}then(callback){this.options.thenCallbacks.push(callback);return this}catch(callback){this.options.catchCallbacks.push(callback);return this}finally(callback){this.options.finallyCallbacks.push(callback);return this}progress(callback){this.options.progressCallbacks.push(callback);return this}thenHandler(handler){this.options.thenHandler=handler;return this}catchHandler(handler){this.options.catchHandler=handler;return this}finallyHandler(handler){this.options.finallyHandler=handler;return this}async dispatch(){const batchId=crypto.randomUUID();const totalJobs=this.jobs.length;if(totalJobs===0){throw new Error("Cannot dispatch an empty batch")}const driver=getQueueDriver();await storeBatchRecord({id:batchId,name:this.options.name||"",total_jobs:totalJobs,pending_jobs:totalJobs,failed_jobs:0,failed_job_ids:"[]",options:JSON.stringify({queue:this.options.queue,allowFailures:this.options.allowFailures||false}),cancelled_at:null,created_at:new Date().toISOString().slice(0,19).replace("T"," "),finished_at:null,then_handler:this.options.thenHandler?JSON.stringify(this.options.thenHandler):null,catch_handler:this.options.catchHandler?JSON.stringify(this.options.catchHandler):null,finally_handler:this.options.finallyHandler?JSON.stringify(this.options.finallyHandler):null});registerBatchCallbacks(batchId,this.options);try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:added",{jobId:batchId,data:{name:this.options.name,totalJobs}})}catch{}for(let i=0;i<this.jobs.length;i++){const entry=this.jobs[i];if(!entry)continue;const{job,payload}=entry;const jobPayload=batchMemberPayload(payload,batchId,i);if(this.options.queue&&!job.queue){job.queue=this.options.queue}if(driver==="sync"){try{await job.dispatchNow(jobPayload);await recordBatchJobCompletion(batchId)}catch(error){await recordBatchJobFailure(batchId,`${batchId}:${i}`,error)}}else{await job.dispatch(jobPayload)}}log.info(`[Batch] Dispatched batch "${this.options.name||batchId}" with ${totalJobs} jobs`);return new DispatchedBatch(batchId)}getJobs(){return[...this.jobs]}getOptions(){return this.options}}export class DispatchedBatch{id;constructor(id){this.id=id}async fresh(){return getBatchRecord(this.id)}async getName(){const record=await this.fresh();return record?.name||""}async totalJobs(){const record=await this.fresh();return record?.total_jobs||0}async pendingJobs(){const record=await this.fresh();return record?.pending_jobs||0}async failedJobs(){const record=await this.fresh();return record?.failed_jobs||0}async completedJobs(){const record=await this.fresh();if(!record)return 0;return record.total_jobs-record.pending_jobs}async progress(){const record=await this.fresh();if(!record||record.total_jobs===0)return 0;const completed=record.total_jobs-record.pending_jobs;return Math.round(completed/record.total_jobs*100)}async finished(){const record=await this.fresh();return record?.finished_at!==null}async cancelled(){const record=await this.fresh();return record?.cancelled_at!==null}async hasFailures(){const record=await this.fresh();return(record?.failed_jobs||0)>0}async failedJobIds(){const record=await this.fresh();if(!record)return[];try{return JSON.parse(record.failed_job_ids||"[]")}catch{return[]}}async cancel(){const driver=getQueueDriver();if(driver==="redis"){await cancelBatchInRedis(this.id)}else{await cancelBatchInDatabase(this.id)}log.info(`[Batch] Cancelled batch ${this.id}`);const callbacks=getBatchCallbacks(this.id);if(callbacks){for(const cb of callbacks.finallyCallbacks){try{await cb(this)}catch(e){log.error(`[Batch] Error in finally callback for batch ${this.id}:`,e)}}}}async add(jobs){const record=await this.fresh();if(!record)throw new Error(`Batch ${this.id} not found`);if(record.cancelled_at)throw new Error(`Batch ${this.id} has been cancelled`);if(record.finished_at)throw new Error(`Batch ${this.id} has already finished`);const batchableJobs=jobs.map((j)=>("job"in j)?j:{job:j});const grew=await incrementBatchCounters(this.id,batchableJobs.length);if(!grew)throw new Error(`Batch ${this.id} was cancelled, finished or deleted before the jobs could be added`);const options=JSON.parse(record.options||"{}");for(let i=0;i<batchableJobs.length;i++){const entry=batchableJobs[i];if(!entry)continue;const{job,payload}=entry;const jobPayload=batchMemberPayload(payload,this.id,record.total_jobs+i);if(options.queue&&!job.queue){job.queue=options.queue}await job.dispatch(jobPayload)}log.info(`[Batch] Added ${batchableJobs.length} jobs to batch ${this.id}`)}async delete(){await deleteBatchRecord(this.id);removeBatchCallbacks(this.id)}}export class Batch{static create(jobs){return new PendingBatch(jobs)}static async find(id){const record=await getBatchRecord(id);if(!record)return null;return new DispatchedBatch(id)}static async all(){const records=await getAllBatchRecords();return records.map((r)=>new DispatchedBatch(r.id))}static async prune(olderThanHours=24){return pruneBatchRecords(olderThanHours)}}const batchCallbackRegistry=new Map;function registerBatchCallbacks(batchId,options){batchCallbackRegistry.set(batchId,options)}export function getBatchCallbacks(batchId){return batchCallbackRegistry.get(batchId)}function removeBatchCallbacks(batchId){batchCallbackRegistry.delete(batchId)}async function storeBatchRecord(record){const driver=getQueueDriver();if(driver==="redis"){await storeBatchInRedis(record)}else{await storeBatchInDatabase(record)}}async function getBatchRecord(id){const driver=getQueueDriver();if(driver==="redis"){return getBatchFromRedis(id)}return getBatchFromDatabase(id)}async function getAllBatchRecords(){const driver=getQueueDriver();if(driver==="redis"){return getAllBatchesFromRedis()}return getAllBatchesFromDatabase()}async function updateBatchRecord(id,updates){const driver=getQueueDriver();if(driver==="redis"){await updateBatchInRedis(id,updates)}else{await updateBatchInDatabase(id,updates)}}async function incrementBatchCounters(id,delta){if(delta===0)return true;if(getQueueDriver()==="redis"){try{const client=await connectBatchRedis();const key=`${REDIS_BATCH_PREFIX}${id}`;await client.hincrby(key,"total_jobs",delta);await client.hincrby(key,"pending_jobs",delta);client.close();return true}catch{}}const{db,sql}=await import("@stacksjs/database/runtime");const result=await db.updateTable("job_batches").set(batchCounterIncrements(sql,delta)).where("id","=",id).whereNull("cancelled_at").whereNull("finished_at").executeTakeFirst();return updatedRowCount(result)>0}export function batchCounterIncrements(sql,delta){return{total_jobs:sql`total_jobs + ${delta}`,pending_jobs:sql`pending_jobs + ${delta}`}}async function deleteBatchRecord(id){const driver=getQueueDriver();if(driver==="redis"){await deleteBatchFromRedis(id)}else{await deleteBatchFromDatabase(id)}}async function pruneBatchRecords(olderThanHours){const driver=getQueueDriver();if(driver==="redis"){return pruneBatchesFromRedis(olderThanHours)}return pruneBatchesFromDatabase(olderThanHours)}function hasPersistentHandlers(record){return!!(record.then_handler||record.catch_handler||record.finally_handler)}async function storeBatchInDatabase(record){const{db}=await import("@stacksjs/database/runtime");const columns={id:record.id,name:record.name,total_jobs:record.total_jobs,pending_jobs:record.pending_jobs,failed_jobs:record.failed_jobs,failed_job_ids:record.failed_job_ids,options:record.options,cancelled_at:record.cancelled_at,created_at:record.created_at,finished_at:record.finished_at};if(!hasPersistentHandlers(record)){await db.insertInto("job_batches").values(columns).execute();return}try{await db.insertInto("job_batches").values({...columns,then_handler:record.then_handler??null,catch_handler:record.catch_handler??null,finally_handler:record.finally_handler??null}).execute()}catch(error){log.warn(`[Batch] Could not persist terminal handlers for batch ${record.id}: ${error?.message}. The job_batches table predates the then_handler/catch_handler/finally_handler columns; recreate it to enable handlers that survive a worker restart.`);await db.insertInto("job_batches").values(columns).execute()}}async function getBatchFromDatabase(id){const{db}=await import("@stacksjs/database/runtime");const result=await db.selectFrom("job_batches").where("id","=",id).selectAll().executeTakeFirst();return result||null}async function getAllBatchesFromDatabase(){const{db}=await import("@stacksjs/database/runtime");const results=await db.selectFrom("job_batches").selectAll().orderBy("created_at","desc").execute();return results}async function updateBatchInDatabase(id,updates){const{db}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set(updates).where("id","=",id).execute()}async function deleteBatchFromDatabase(id){const{db}=await import("@stacksjs/database/runtime");await db.deleteFrom("job_batches").where("id","=",id).execute()}async function cancelBatchInDatabase(id){await updateBatchInDatabase(id,{cancelled_at:new Date().toISOString().slice(0,19).replace("T"," "),finished_at:new Date().toISOString().slice(0,19).replace("T"," ")})}async function pruneBatchesFromDatabase(olderThanHours){const{db}=await import("@stacksjs/database/runtime");const cutoff=new Date(Date.now()-olderThanHours*60*60*1000).toISOString().slice(0,19).replace("T"," ");const result=await db.deleteFrom("job_batches").whereNotNull("finished_at").where("finished_at","<",cutoff).executeTakeFirst();return Number(result?.numDeletedRows??0)}const REDIS_BATCH_PREFIX="stacks:batch:";const REDIS_BATCH_INDEX="stacks:batches";async function getRedisClient(){const{sharedRedisQueue}=await import("./drivers/redis");const{queue:queueConfig}=await import("@stacksjs/config");const redisConfig=queueConfig?.connections?.redis;if(!redisConfig)throw new Error("Redis queue connection is not configured");return sharedRedisQueue("__batches__",redisConfig)}async function batchRedisUrl(){const{queue:queueConfig}=await import("@stacksjs/config");const redisConfig=queueConfig?.connections?.redis?.redis;if(redisConfig?.url)return redisConfig.url;const auth=redisConfig?.password?`:${encodeURIComponent(redisConfig.password)}@`:"";const db=redisConfig?.db?`/${redisConfig.db}`:"";return`redis://${auth}${redisConfig?.host||"localhost"}:${redisConfig?.port||6379}${db}`}async function connectBatchRedis(){const client=new RedisClient(await batchRedisUrl());await client.connect();return client}export function batchRecordToHash(record){return{id:record.id,name:record.name,total_jobs:String(record.total_jobs),pending_jobs:String(record.pending_jobs),failed_jobs:String(record.failed_jobs),failed_job_ids:record.failed_job_ids,options:record.options,cancelled_at:record.cancelled_at||"",created_at:record.created_at,finished_at:record.finished_at||"",then_handler:record.then_handler||"",catch_handler:record.catch_handler||"",finally_handler:record.finally_handler||""}}async function storeBatchInRedis(record){try{const client=await connectBatchRedis();await client.hset(`${REDIS_BATCH_PREFIX}${record.id}`,batchRecordToHash(record));await client.sadd(REDIS_BATCH_INDEX,record.id);client.close()}catch{await storeBatchInDatabase(record)}}export function batchRecordFromHash(data){if(!data?.id)return null;return{id:data.id,name:data.name??"",total_jobs:Number(data.total_jobs),pending_jobs:Number(data.pending_jobs),failed_jobs:Number(data.failed_jobs),failed_job_ids:data.failed_job_ids??"",options:data.options??"",cancelled_at:data.cancelled_at||null,created_at:data.created_at??"",finished_at:data.finished_at||null,then_handler:data.then_handler||null,catch_handler:data.catch_handler||null,finally_handler:data.finally_handler||null}}async function getBatchFromRedis(id){try{const client=await connectBatchRedis();const key=`${REDIS_BATCH_PREFIX}${id}`;const data=await client.hgetall(key);client.close();return batchRecordFromHash(data)}catch{return getBatchFromDatabase(id)}}async function getAllBatchesFromRedis(){try{const client=await connectBatchRedis();const ids=await client.smembers(REDIS_BATCH_INDEX);const batches=[];for(const id of ids){const record=batchRecordFromHash(await client.hgetall(`${REDIS_BATCH_PREFIX}${id}`));if(record)batches.push(record)}client.close();return batches}catch{return getAllBatchesFromDatabase()}}async function updateBatchInRedis(id,updates){try{const client=await connectBatchRedis();const key=`${REDIS_BATCH_PREFIX}${id}`;const hashUpdates={};for(const[k,v]of Object.entries(updates)){hashUpdates[k]=v===null?"":String(v)}await client.hset(key,hashUpdates);client.close()}catch{await updateBatchInDatabase(id,updates)}}async function decrementBatchInRedis(id,failed,allowFailures){const client=await connectBatchRedis();try{const key=`${REDIS_BATCH_PREFIX}${id}`;const decrementedPending=await client.hincrby(key,"pending_jobs",-1);const pending=Math.max(decrementedPending,0);if(decrementedPending<0)await client.hset(key,{pending_jobs:"0"});if(failed)await client.hincrby(key,"failed_jobs",1);const data=await client.hgetall(key);const shouldFinish=!data.finished_at&&(!failed||allowFailures?pending===0:true);const finishedAt=new Date().toISOString().slice(0,19).replace("T"," ");const completed=shouldFinish&&await client.hsetnx(key,"terminal_claimed","1");if(completed)await client.hset(key,{finished_at:finishedAt});if(completed&&failed&&!allowFailures)await client.hset(key,{cancelled_at:finishedAt});return completed}finally{client.close()}}async function deleteBatchFromRedis(id){try{const client=await connectBatchRedis();await client.del(`${REDIS_BATCH_PREFIX}${id}`);await client.srem(REDIS_BATCH_INDEX,id);client.close()}catch{await deleteBatchFromDatabase(id)}}async function cancelBatchInRedis(id){const now=new Date().toISOString().slice(0,19).replace("T"," ");await updateBatchInRedis(id,{cancelled_at:now,finished_at:now})}async function pruneBatchesFromRedis(olderThanHours){try{const batches=await getAllBatchesFromRedis();const cutoff=Date.now()-olderThanHours*60*60*1000;let pruned=0;for(const batch of batches){if(batch.finished_at){const finishedTime=new Date(batch.finished_at).getTime();if(finishedTime<cutoff){await deleteBatchFromRedis(batch.id);pruned++}}}return pruned}catch{return pruneBatchesFromDatabase(olderThanHours)}}function parsePersistentHandler(raw){if(!raw)return null;try{const parsed=JSON.parse(raw);if(parsed&&(parsed.kind==="job"||parsed.kind==="module"))return parsed;log.warn(`[Batch] handler JSON has unknown kind '${parsed?.kind}' - skipping`);return null}catch(err){log.warn(`[Batch] failed to parse persistent handler: ${err.message}`);return null}}async function firePersistentHandler(handler,batchId){try{if(handler.kind==="job"){const{Jobs}=await import("./job");await Jobs.dispatch(handler.name,batchTerminalPayload(handler.payload,batchId));return}const mod=await import(handler.module).catch((err)=>{log.warn(`[Batch] persistent handler module not found: ${handler.module} (${err.message})`);return null});if(!mod)return;const fn=mod[handler.export];if(typeof fn!=="function"){log.warn(`[Batch] persistent handler export '${handler.export}' is not a function on ${handler.module}`);return}await fn(handler.payload,batchId)}catch(err){log.error(`[Batch] persistent handler threw for batch ${batchId}:`,err)}}export async function recordBatchJobCompletion(batchId){const driver=getQueueDriver();let completed=false;if(driver==="redis"){completed=await decrementBatchInRedis(batchId,false,false)}else{const{db,sql}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set({pending_jobs:sql`GREATEST(pending_jobs - 1, 0)`}).where("id","=",batchId).where("pending_jobs",">",0).execute();const finishedAt=new Date().toISOString().slice(0,19).replace("T"," ");const completeResult=await db.updateTable("job_batches").set({finished_at:finishedAt}).where("id","=",batchId).where("pending_jobs","=",0).whereNull("finished_at").executeTakeFirst();completed=updatedRowCount(completeResult)>0}const callbacks=getBatchCallbacks(batchId);const dispatched=new DispatchedBatch(batchId);if(callbacks){for(const cb of callbacks.progressCallbacks){try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in progress callback for batch ${batchId}:`,e)}}}if(completed){try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:completed",{jobId:batchId})}catch{}const freshRecord=await getBatchRecord(batchId);if(!freshRecord){removeBatchCallbacks(batchId);log.info(`[Batch] Batch ${batchId} finished (record vanished)`);return}const opts=JSON.parse(freshRecord.options||"{}");const hasFailed=(freshRecord.failed_jobs||0)>0;const succeeded=!hasFailed||opts.allowFailures;if(callbacks){if(succeeded){for(const cb of callbacks.thenCallbacks){try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in then callback for batch ${batchId}:`,e)}}}for(const cb of callbacks.finallyCallbacks){try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in finally callback for batch ${batchId}:`,e)}}removeBatchCallbacks(batchId)}if(succeeded){const thenHandler=parsePersistentHandler(freshRecord.then_handler);if(thenHandler)await firePersistentHandler(thenHandler,batchId)}else{const catchHandler=parsePersistentHandler(freshRecord.catch_handler);if(catchHandler)await firePersistentHandler(catchHandler,batchId)}const finallyHandler=parsePersistentHandler(freshRecord.finally_handler);if(finallyHandler)await firePersistentHandler(finallyHandler,batchId);log.info(`[Batch] Batch ${batchId} finished`)}}export async function recordBatchJobFailure(batchId,jobId,error){const record=await getBatchRecord(batchId);if(!record)return;const opts=JSON.parse(record.options||"{}");const dispatched=new DispatchedBatch(batchId);const callbacks=getBatchCallbacks(batchId);let completed=false;if(getQueueDriver()==="redis"){completed=await decrementBatchInRedis(batchId,true,!!opts.allowFailures);const fresh=await getBatchRecord(batchId);if(fresh){let failedIds=[];try{failedIds=JSON.parse(fresh.failed_job_ids||"[]")}catch{failedIds=[]}failedIds.push(jobId);await updateBatchInRedis(batchId,{failed_job_ids:JSON.stringify(failedIds)})}if(callbacks){for(const cb of callbacks.catchCallbacks){try{await cb(dispatched,error)}catch(e){log.error(`[Batch] Error in catch callback for batch ${batchId}:`,e)}}}try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:failed",{jobId:batchId,error})}catch{}}else{const{db,sql}=await import("@stacksjs/database/runtime");await db.updateTable("job_batches").set({pending_jobs:sql`GREATEST(pending_jobs - 1, 0)`,failed_jobs:sql`failed_jobs + 1`}).where("id","=",batchId).where("pending_jobs",">",0).execute();try{const fresh=await getBatchRecord(batchId);if(fresh){let failedIds=[];try{failedIds=JSON.parse(fresh.failed_job_ids||"[]")}catch{failedIds=[]}failedIds.push(jobId);await updateBatchRecord(batchId,{failed_job_ids:JSON.stringify(failedIds)})}}catch{}if(callbacks){for(const cb of callbacks.catchCallbacks){try{await cb(dispatched,error)}catch(e){log.error(`[Batch] Error in catch callback for batch ${batchId}:`,e)}}}try{const{emitQueueEvent}=await import("./events");await emitQueueEvent("batch:failed",{jobId:batchId,error})}catch{}const finishedAt=new Date().toISOString().slice(0,19).replace("T"," ");let finalize=db.updateTable("job_batches").set(opts.allowFailures?{finished_at:finishedAt}:{finished_at:finishedAt,cancelled_at:finishedAt}).where("id","=",batchId).whereNull("finished_at");if(opts.allowFailures)finalize=finalize.where("pending_jobs","=",0);const finalizeResult=await finalize.executeTakeFirst();completed=updatedRowCount(finalizeResult)>0}if(!completed)return;const succeeded=!!opts.allowFailures;if(callbacks){if(succeeded){for(const cb of callbacks.thenCallbacks){try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in then callback for batch ${batchId}:`,e)}}}for(const cb of callbacks.finallyCallbacks){try{await cb(dispatched)}catch(e){log.error(`[Batch] Error in finally callback for batch ${batchId}:`,e)}}removeBatchCallbacks(batchId)}const freshRecord=await getBatchRecord(batchId);if(freshRecord){if(succeeded){const thenHandler=parsePersistentHandler(freshRecord.then_handler);if(thenHandler)await firePersistentHandler(thenHandler,batchId)}else{const catchHandler=parsePersistentHandler(freshRecord.catch_handler);if(catchHandler)await firePersistentHandler(catchHandler,batchId)}const finallyHandler=parsePersistentHandler(freshRecord.finally_handler);if(finallyHandler)await firePersistentHandler(finallyHandler,batchId)}log.info(`[Batch] Batch ${batchId} finished with failure(s)`)}export async function isBatchCancelled(batchId){const record=await getBatchRecord(batchId);return record?.cancelled_at!==null}
@@ -1 +1 @@
1
- import{db,lockRow,sqliteWriteOptions,parseSqlDateTime}from"@stacksjs/database/runtime";import{seedStateRow}from"./state-row";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;console.warn("[queue/circuit-breaker] queue_circuit_state table missing - circuit breaker disabled. Run migrations to enable.")}async function seedCircuitRow(tx,queue,now){await seedStateRow(tx,"queue_circuit_state",["queue_name"],{queue_name:queue,success_count:0,failure_count:0,window_start:now,paused_at:null,resume_at:null})}export async function isCircuitOpen(queue){try{return await db.transaction(async(tx)=>{const row=await lockRow(tx,"queue_circuit_state",{queue_name:queue});if(!row?.paused_at)return!1;const resume=parseSqlDateTime(row.resume_at)?.getTime();if(resume!==void 0&&Date.now()>=resume){await tx.updateTable("queue_circuit_state").set({paused_at:null,resume_at:null,success_count:0,failure_count:0,window_start:new Date().toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute();return!1}return!0},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return!1}throw error}}async function recordObservation(queue,success,config){const now=new Date,nowStr=now.toISOString().slice(0,19).replace("T"," ");try{return await db.transaction(async(tx)=>{await seedCircuitRow(tx,queue,nowStr);const row=await lockRow(tx,"queue_circuit_state",{queue_name:queue}),start=parseSqlDateTime(row.window_start)?.getTime(),reset=start===void 0||now.getTime()-start>=(config.windowSeconds??300)*1000,successes=(reset?0:Number(row.success_count))+(success?1:0),failures=(reset?0:Number(row.failure_count))+(success?0:1),observed=successes+failures,trip=!success&&!row.paused_at&&observed>=(config.minObservations??10)&&failures/observed>=(config.failureRateThreshold??0.5);await tx.updateTable("queue_circuit_state").set({success_count:successes,failure_count:failures,window_start:reset?nowStr:row.window_start,...trip?{paused_at:nowStr,resume_at:new Date(now.getTime()+(config.pauseSeconds??300)*1000).toISOString().slice(0,19).replace("T"," ")}:{}}).where("queue_name","=",queue).execute();return trip},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return!1}throw error}}export async function recordCircuitSuccess(queue,config={}){await recordObservation(queue,!0,config)}export async function recordCircuitFailure(queue,config={}){return recordObservation(queue,!1,config)}export async function pauseQueue(queue,pauseSeconds=300){const now=new Date,nowStr=now.toISOString().slice(0,19).replace("T"," ");try{await db.transaction(async(tx)=>{await seedCircuitRow(tx,queue,nowStr);await lockRow(tx,"queue_circuit_state",{queue_name:queue});await tx.updateTable("queue_circuit_state").set({paused_at:nowStr,resume_at:new Date(now.getTime()+pauseSeconds*1000).toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute()},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return}throw error}}export async function resumeQueue(queue){try{await db.transaction(async(tx)=>{if(!await lockRow(tx,"queue_circuit_state",{queue_name:queue}))return;await tx.updateTable("queue_circuit_state").set({paused_at:null,resume_at:null,success_count:0,failure_count:0,window_start:new Date().toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute()},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return}throw error}}export async function listCircuitState(){try{return await db.selectFrom("queue_circuit_state").selectAll().execute()??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}
1
+ import{db,lockRow,sqliteWriteOptions,parseSqlDateTime}from"@stacksjs/database/runtime";import{seedStateRow}from"./state-row";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;console.warn("[queue/circuit-breaker] queue_circuit_state table missing - circuit breaker disabled. "+"Run migrations to enable.")}async function seedCircuitRow(tx,queue,now){await seedStateRow(tx,"queue_circuit_state",["queue_name"],{queue_name:queue,success_count:0,failure_count:0,window_start:now,paused_at:null,resume_at:null})}export async function isCircuitOpen(queue){try{return await db.transaction(async(tx)=>{const row=await lockRow(tx,"queue_circuit_state",{queue_name:queue});if(!row?.paused_at)return false;const resume=parseSqlDateTime(row.resume_at)?.getTime();if(resume!==undefined&&Date.now()>=resume){await tx.updateTable("queue_circuit_state").set({paused_at:null,resume_at:null,success_count:0,failure_count:0,window_start:new Date().toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute();return false}return true},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return false}throw error}}async function recordObservation(queue,success,config){const now=new Date;const nowStr=now.toISOString().slice(0,19).replace("T"," ");try{return await db.transaction(async(tx)=>{await seedCircuitRow(tx,queue,nowStr);const row=await lockRow(tx,"queue_circuit_state",{queue_name:queue});const start=parseSqlDateTime(row.window_start)?.getTime();const reset=start===undefined||now.getTime()-start>=(config.windowSeconds??300)*1000;const successes=(reset?0:Number(row.success_count))+(success?1:0);const failures=(reset?0:Number(row.failure_count))+(success?0:1);const observed=successes+failures;const trip=!success&&!row.paused_at&&observed>=(config.minObservations??10)&&failures/observed>=(config.failureRateThreshold??0.5);await tx.updateTable("queue_circuit_state").set({success_count:successes,failure_count:failures,window_start:reset?nowStr:row.window_start,...trip?{paused_at:nowStr,resume_at:new Date(now.getTime()+(config.pauseSeconds??300)*1000).toISOString().slice(0,19).replace("T"," ")}:{}}).where("queue_name","=",queue).execute();return trip},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return false}throw error}}export async function recordCircuitSuccess(queue,config={}){await recordObservation(queue,true,config)}export async function recordCircuitFailure(queue,config={}){return recordObservation(queue,false,config)}export async function pauseQueue(queue,pauseSeconds=300){const now=new Date;const nowStr=now.toISOString().slice(0,19).replace("T"," ");try{await db.transaction(async(tx)=>{await seedCircuitRow(tx,queue,nowStr);await lockRow(tx,"queue_circuit_state",{queue_name:queue});await tx.updateTable("queue_circuit_state").set({paused_at:nowStr,resume_at:new Date(now.getTime()+pauseSeconds*1000).toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute()},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return}throw error}}export async function resumeQueue(queue){try{await db.transaction(async(tx)=>{if(!await lockRow(tx,"queue_circuit_state",{queue_name:queue}))return;await tx.updateTable("queue_circuit_state").set({paused_at:null,resume_at:null,success_count:0,failure_count:0,window_start:new Date().toISOString().slice(0,19).replace("T"," ")}).where("queue_name","=",queue).execute()},sqliteWriteOptions())}catch(error){if(isMissingTableError(error)){warnOnceAboutMissingTable();return}throw error}}export async function listCircuitState(){try{const rows=await db.selectFrom("queue_circuit_state").selectAll().execute();return rows??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}
@@ -1 +1 @@
1
- import{db,lockRow,sqliteWriteOptions,mutationCount}from"@stacksjs/database/runtime";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;console.warn("[queue/dlq] dead_letter_jobs table missing - DLQ disabled. Run migrations to enable poison-message isolation.")}export async function moveToDeadLetter(failedJob,reason,totalFailures=1){const now=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.insertInto("dead_letter_jobs").values({uuid:failedJob.uuid??crypto.randomUUID(),connection:failedJob.connection??"database",queue:failedJob.queue??"default",payload:failedJob.payload??"{}",exception:failedJob.exception??"unknown",reason,total_failures:totalFailures,first_failed_at:failedJob.failed_at??now,last_failed_at:now,dead_lettered_at:now}).execute();return!0}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function listDeadLetterJobs(filter={}){const limit=filter.limit??100;if(!Number.isSafeInteger(limit)||limit<=0)throw RangeError("Dead-letter limit must be a positive integer");try{let q=db.selectFrom("dead_letter_jobs").selectAll();if(filter.queue)q=q.where("queue","=",filter.queue);if(filter.reason)q=q.where("reason","=",filter.reason);if(filter.sinceCutoffMs){const cutoff=new Date(filter.sinceCutoffMs).toISOString().slice(0,19).replace("T"," ");q=q.where("dead_lettered_at",">=",cutoff)}q=q.limit(limit);return await q.execute()??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}export async function retryDeadLetterJob(id){try{return await db.transaction(async(tx)=>{const row=await lockRow(tx,"dead_letter_jobs",{id});if(!row)return!1;const nowSec=Math.floor(Date.now()/1000);await tx.insertInto("jobs").values({queue:row.queue,payload:row.payload,attempts:0,reserved_at:null,available_at:nowSec,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();await tx.deleteFrom("dead_letter_jobs").where("id","=",id).execute();return!0},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function purgeDeadLetterJobs(olderThanDays=30){try{const cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000).toISOString().slice(0,19).replace("T"," "),result=await db.deleteFrom("dead_letter_jobs").where("dead_lettered_at","<",cutoff).execute();return mutationCount(result)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return 0}throw err}}
1
+ import{db,lockRow,sqliteWriteOptions,mutationCount}from"@stacksjs/database/runtime";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;console.warn("[queue/dlq] dead_letter_jobs table missing - DLQ disabled. "+"Run migrations to enable poison-message isolation.")}export async function moveToDeadLetter(failedJob,reason,totalFailures=1){const now=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.insertInto("dead_letter_jobs").values({uuid:failedJob.uuid??crypto.randomUUID(),connection:failedJob.connection??"database",queue:failedJob.queue??"default",payload:failedJob.payload??"{}",exception:failedJob.exception??"unknown",reason,total_failures:totalFailures,first_failed_at:failedJob.failed_at??now,last_failed_at:now,dead_lettered_at:now}).execute();return true}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return false}throw err}}export async function listDeadLetterJobs(filter={}){const limit=filter.limit??100;if(!Number.isSafeInteger(limit)||limit<=0)throw new RangeError("Dead-letter limit must be a positive integer");try{let q=db.selectFrom("dead_letter_jobs").selectAll();if(filter.queue)q=q.where("queue","=",filter.queue);if(filter.reason)q=q.where("reason","=",filter.reason);if(filter.sinceCutoffMs){const cutoff=new Date(filter.sinceCutoffMs).toISOString().slice(0,19).replace("T"," ");q=q.where("dead_lettered_at",">=",cutoff)}q=q.limit(limit);const rows=await q.execute();return rows??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}export async function retryDeadLetterJob(id){try{return await db.transaction(async(tx)=>{const row=await lockRow(tx,"dead_letter_jobs",{id});if(!row)return false;const nowSec=Math.floor(Date.now()/1000);await tx.insertInto("jobs").values({queue:row.queue,payload:row.payload,attempts:0,reserved_at:null,available_at:nowSec,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();await tx.deleteFrom("dead_letter_jobs").where("id","=",id).execute();return true},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return false}throw err}}export async function purgeDeadLetterJobs(olderThanDays=30){try{const cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000).toISOString().slice(0,19).replace("T"," ");const result=await db.deleteFrom("dead_letter_jobs").where("dead_lettered_at","<",cutoff).execute();return mutationCount(result)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return 0}throw err}}
package/dist/discovery.js CHANGED
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";class JobRegistry{jobs=new Map;initialized=!1;register(job){this.jobs.set(job.name,job);log.debug(`Registered job: ${job.name} (${job.type})`)}get(name){return this.jobs.get(name)}all(){return Array.from(this.jobs.values())}byQueue(queue){return this.all().filter((job)=>job.config.queue===queue)}scheduled(){return this.all().filter((job)=>job.config.enabled!==!1&&(job.config.rate||job.config.schedule))}has(name){return this.jobs.has(name)}clear(){this.jobs.clear();this.initialized=!1}setInitialized(value){this.initialized=value}isInitialized(){return this.initialized}}export const jobRegistry=new JobRegistry;export async function discoverJobs(jobsPath,options={}){const basePath=jobsPath||p.userJobsPath(),discovered=[];if(!existsSync(basePath))return discovered;try{const glob=new Bun.Glob("**/*.{ts,js}"),scanOptions={cwd:basePath,onlyFiles:!0,absolute:!0};for await(const file of glob.scan(scanOptions)){if(file.endsWith(".d.ts")||file.includes(".test.")||file.includes(".spec.")||file.endsWith("index.ts")||file.endsWith("index.js"))continue;try{const job=await loadJob(file,options.strict);if(job){discovered.push(job);jobRegistry.register(job)}}catch(error){if(options.strict)throw error;log.warn(`Failed to load job from ${file}: ${error.message}`)}}jobRegistry.setInitialized(!0);log.info(`Discovered ${discovered.length} jobs from ${basePath}`);return discovered}catch(error){if(options.strict)throw error;log.error(`Failed to discover jobs: ${error.message}`);return[]}}async function loadJob(filePath,strict=!1){try{const module=await import(filePath),fileName=filePath.split("/").pop()?.replace(/\.(ts|js)$/,"")||"UnknownJob";if(module.default&&typeof module.default==="function"){const JobClass=module.default;if(typeof JobClass.handle==="function"||typeof JobClass.prototype?.handle==="function"){const config=JobClass.config||{};return{name:config.name||fileName,path:filePath,config:normalizeConfig(config,fileName),type:"class",module:JobClass}}}if(module.default&&typeof module.default==="object"){const jobConfig=module.default;if(typeof jobConfig.handle==="function"||typeof jobConfig.action==="string")return{name:jobConfig.name||fileName,path:filePath,config:normalizeConfig(jobConfig,fileName),type:"function",module:jobConfig}}if(strict)throw TypeError(`No executable job export in ${filePath}`);return null}catch(error){if(strict)throw error;log.debug(`Could not load job from ${filePath}: ${error.message}`);return null}}function normalizeConfig(config,fileName){return{name:config.name||fileName,description:config.description,queue:config.queue||"default",enabled:config.enabled,tries:config.tries??config.retries??3,backoff:config.backoff??config.retryAfter,rate:config.rate,schedule:config.schedule,timeout:config.timeout??config.timeOut,withoutOverlapping:config.withoutOverlapping,retryAfter:config.retryAfter,backoffConfig:config.backoffConfig}}export function getJob(name){return jobRegistry.get(name)}export function getAllJobs(){return jobRegistry.all()}export function getScheduledJobs(){return jobRegistry.scheduled()}export async function executeJob(name,payload){const job=jobRegistry.get(name);if(!job)throw Error(`Job "${name}" not found. Did you run discoverJobs()?`);try{if(job.type==="class"){if(typeof job.module.handle==="function")return await job.module.handle(payload);return await new job.module().handle(payload)}else{if(typeof job.module.handle==="function")return await job.module.handle(payload);throw Error(`Job "${name}" does not have a handle method`)}}catch(error){log.error(`Failed to execute job "${name}": ${error.message}`);throw error}}export function toJobOptions(job){const config=job.config;return{name:config.name,queue:config.queue,tries:config.tries,backoff:config.backoff,timeout:config.timeout,backoffConfig:config.backoffConfig,rate:config.rate}}
1
+ import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";class JobRegistry{jobs=new Map;initialized=false;register(job){this.jobs.set(job.name,job);log.debug(`Registered job: ${job.name} (${job.type})`)}get(name){return this.jobs.get(name)}all(){return Array.from(this.jobs.values())}byQueue(queue){return this.all().filter((job)=>job.config.queue===queue)}scheduled(){return this.all().filter((job)=>job.config.enabled!==false&&(job.config.rate||job.config.schedule))}has(name){return this.jobs.has(name)}clear(){this.jobs.clear();this.initialized=false}setInitialized(value){this.initialized=value}isInitialized(){return this.initialized}}export const jobRegistry=new JobRegistry;export async function discoverJobs(jobsPath,options={}){const basePath=jobsPath||p.userJobsPath();const discovered=[];if(!existsSync(basePath))return discovered;try{const glob=new Bun.Glob("**/*.{ts,js}");const scanOptions={cwd:basePath,onlyFiles:true,absolute:true};for await(const file of glob.scan(scanOptions)){if(file.endsWith(".d.ts")||file.includes(".test.")||file.includes(".spec.")||file.endsWith("index.ts")||file.endsWith("index.js")){continue}try{const job=await loadJob(file,options.strict);if(job){discovered.push(job);jobRegistry.register(job)}}catch(error){if(options.strict)throw error;log.warn(`Failed to load job from ${file}: ${error.message}`)}}jobRegistry.setInitialized(true);log.info(`Discovered ${discovered.length} jobs from ${basePath}`);return discovered}catch(error){if(options.strict)throw error;log.error(`Failed to discover jobs: ${error.message}`);return[]}}async function loadJob(filePath,strict=false){try{const module=await import(filePath);const fileName=filePath.split("/").pop()?.replace(/\.(ts|js)$/,"")||"UnknownJob";if(module.default&&typeof module.default==="function"){const JobClass=module.default;if(typeof JobClass.handle==="function"||typeof JobClass.prototype?.handle==="function"){const config=JobClass.config||{};return{name:config.name||fileName,path:filePath,config:normalizeConfig(config,fileName),type:"class",module:JobClass}}}if(module.default&&typeof module.default==="object"){const jobConfig=module.default;if(typeof jobConfig.handle==="function"||typeof jobConfig.action==="string"){return{name:jobConfig.name||fileName,path:filePath,config:normalizeConfig(jobConfig,fileName),type:"function",module:jobConfig}}}if(strict)throw new TypeError(`No executable job export in ${filePath}`);return null}catch(error){if(strict)throw error;log.debug(`Could not load job from ${filePath}: ${error.message}`);return null}}function normalizeConfig(config,fileName){return{name:config.name||fileName,description:config.description,queue:config.queue||"default",enabled:config.enabled,tries:config.tries??config.retries??3,backoff:config.backoff??config.retryAfter,rate:config.rate,schedule:config.schedule,timeout:config.timeout??config.timeOut,withoutOverlapping:config.withoutOverlapping,retryAfter:config.retryAfter,backoffConfig:config.backoffConfig}}export function getJob(name){return jobRegistry.get(name)}export function getAllJobs(){return jobRegistry.all()}export function getScheduledJobs(){return jobRegistry.scheduled()}export async function executeJob(name,payload){const job=jobRegistry.get(name);if(!job){throw new Error(`Job "${name}" not found. Did you run discoverJobs()?`)}try{if(job.type==="class"){if(typeof job.module.handle==="function"){return await job.module.handle(payload)}const instance=new job.module;return await instance.handle(payload)}else{if(typeof job.module.handle==="function"){return await job.module.handle(payload)}throw new Error(`Job "${name}" does not have a handle method`)}}catch(error){log.error(`Failed to execute job "${name}": ${error.message}`);throw error}}export function toJobOptions(job){const config=job.config;return{name:config.name,queue:config.queue,tries:config.tries,backoff:config.backoff,timeout:config.timeout,backoffConfig:config.backoffConfig,rate:config.rate}}
package/dist/driver.js CHANGED
@@ -1 +1 @@
1
- import{env}from"@stacksjs/env";export function resolveQueueDriver(driver=env.QUEUE_DRIVER,environment=env.APP_ENV){const production=environment==="production",selected=driver||(production?"database":"sync");if(!["sync","database","redis"].includes(selected))throw Error(["sqs","memory","beanstalkd"].includes(selected)?`[queue] Driver "${selected}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`:`[queue] Unknown QUEUE_DRIVER "${selected}". Allowed values: redis, database, sync.`);if(production&&selected==="sync")throw Error("[queue] Production requires a durable database or redis queue; sync executes inline.");return selected}
1
+ import{env}from"@stacksjs/env";export function resolveQueueDriver(driver=env.QUEUE_DRIVER,environment=env.APP_ENV){const production=environment==="production";const selected=driver||(production?"database":"sync");if(!["sync","database","redis"].includes(selected))throw new Error(["sqs","memory","beanstalkd"].includes(selected)?`[queue] Driver "${selected}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`:`[queue] Unknown QUEUE_DRIVER "${selected}". Allowed values: redis, database, sync.`);if(production&&selected==="sync")throw new Error("[queue] Production requires a durable database or redis queue; sync executes inline.");return selected}
@@ -1 +1 @@
1
- import{Queue as BunQueue,batch,chain,dispatch,dispatchAfter,dispatchSync,getQueueManager,QueueManager,setQueueManager}from"@stacksjs/bun-queue";import{log}from"@stacksjs/logging";export{batch,chain,dispatch,dispatchAfter,dispatchSync,getQueueManager,QueueManager,setQueueManager};export function backoffSeconds(value){const seconds=Number(value);return Number.isFinite(seconds)&&seconds>=0?seconds:1}export class RedisQueue{queue;config;isProcessing=!1;constructor(name,config){this.config=config;this.queue=new BunQueue(name,{driver:"redis",prefix:config.prefix,redis:config.redis?{url:config.redis.url||this.buildRedisUrl(config.redis)}:void 0,defaultJobOptions:config.defaultJobOptions?{delay:config.defaultJobOptions.delay,attempts:config.defaultJobOptions.attempts,backoff:config.defaultJobOptions.backoff,removeOnComplete:config.defaultJobOptions.removeOnComplete,removeOnFail:config.defaultJobOptions.removeOnFail,priority:config.defaultJobOptions.priority,lifo:config.defaultJobOptions.lifo,timeout:config.defaultJobOptions.timeout,jobId:config.defaultJobOptions.jobId,dependsOn:config.defaultJobOptions.dependsOn,keepJobs:config.defaultJobOptions.keepJobs,deadLetter:config.defaultJobOptions.deadLetter}:void 0,limiter:config.limiter,metrics:config.metrics,stalledJobCheckInterval:config.stalledJobCheckInterval,maxStalledJobRetries:config.maxStalledJobRetries,distributedLock:config.distributedLock,defaultDeadLetterOptions:config.defaultDeadLetterOptions,horizontalScaling:config.horizontalScaling,logLevel:config.logLevel});log.debug(`Redis queue "${name}" initialized`)}buildRedisUrl(redis){const host=redis.host||"localhost",port=redis.port||6379,passwordSegment=redis.password?`:${encodeURIComponent(redis.password)}@`:"",db=Number.isFinite(redis.db)&&redis.db>=0?redis.db:0;return`redis://${passwordSegment}${host}:${port}/${db}`}async add(data,options){const jobOptions={delay:options?.delay?options.delay*1000:void 0,attempts:options?.maxTries,priority:options?.priority,timeout:options?.timeout?options.timeout*1000:void 0,backoff:Array.isArray(options?.backoff)?options.backoff.map((s)=>backoffSeconds(s)*1000):typeof options?.backoff==="number"?{type:"fixed",delay:backoffSeconds(options.backoff)*1000}:void 0};return this.queue.add(data,jobOptions)}process(concurrency,handler){if(this.isProcessing){log.warn("Queue is already processing");return}this.isProcessing=!0;this.queue.process(concurrency,handler);log.info(`Started processing queue with concurrency ${concurrency}`)}async getJob(jobId){return this.queue.getJob(jobId)}async getJobs(status){return this.queue.getJobs(status)}async getJobCounts(){return this.queue.getJobCounts()}async removeJob(jobId){return this.queue.removeJob(jobId)}async pause(){return this.queue.pause()}async resume(){return this.queue.resume()}async empty(){return this.queue.empty()}async close(){this.isProcessing=!1;return this.queue.close()}async getMetrics(){return this.queue.getMetrics()}async ping(){return this.queue.ping()}async scheduleCron(options){return this.queue.scheduleCron({cronExpression:options.cron,data:options.data,timezone:options.tz,jobId:options.name})}async unscheduleCron(jobId){return this.queue.unscheduleCron(jobId)}async getDeadLetterJobs(){return this.queue.getDeadLetterJobs()}async republishDeadLetterJob(jobId){return this.queue.republishDeadLetterJob(jobId)}async clearDeadLetterQueue(){return this.queue.clearDeadLetterQueue()}async bulkRemove(jobIds){return this.queue.bulkRemove(jobIds)}async getClusterInfo(){return this.queue.getClusterInfo()}isLeader(){return this.queue.isLeader()}getQueue(){return this.queue}on(event,handler){this.queue.events.on(event,handler)}}const sharedQueues=new Map;export function sharedRedisQueue(name,config){const key=`${name}\x00${JSON.stringify(config)}`;let queue=sharedQueues.get(key);if(!queue){queue=new RedisQueue(name,config);sharedQueues.set(key,queue)}return queue}export async function closeSharedRedisQueues(){const queues=[...sharedQueues.values()];sharedQueues.clear();await Promise.all(queues.map((queue)=>queue.close()))}export class StacksQueueManager{config;queues=new Map;defaultConnection="default";constructor(config){this.config=config;for(const[name,connectionConfig]of Object.entries(config))if(connectionConfig.driver==="redis")this.queues.set(name,new RedisQueue(name,connectionConfig))}queue(name){const queueName=name||this.defaultConnection;let queue=this.queues.get(queueName);if(!queue){const config=this.config[queueName];if(!config)throw Error(`Queue "${queueName}" not configured`);queue=new RedisQueue(queueName,config);this.queues.set(queueName,queue)}return queue}setDefaultConnection(name){this.defaultConnection=name}async closeAll(){const closePromises=Array.from(this.queues.values()).map((q)=>q.close());await Promise.all(closePromises);this.queues.clear()}}export function createRedisDispatcher(queueName,config){const queue=new RedisQueue(queueName,config);return async(data,options)=>{return queue.add(data,options)}}export class RedisJob{data;options={};queue;constructor(queueName,config,data){this.data=data;this.queue=new RedisQueue(queueName,config)}async dispatch(){await this.queue.add(this.data,this.options)}async dispatchNow(){await this.queue.add(this.data,{...this.options,immediate:!0})}delay(seconds){this.options.delay=seconds;return this}afterResponse(){this.options.afterResponse=!0;return this}chain(jobs){this.options.chainedJobs=jobs;return this}onQueue(queue){this.options.queue=queue;return this}priority(level){this.options.priority=level;return this}tries(count){this.options.maxTries=count;return this}timeout(seconds){this.options.timeout=seconds;return this}backoff(attempts){this.options.backoff=attempts;return this}}
1
+ import{Queue as BunQueue,batch,chain,dispatch,dispatchAfter,dispatchSync,getQueueManager,QueueManager,setQueueManager}from"@stacksjs/bun-queue";import{log}from"@stacksjs/logging";export{batch,chain,dispatch,dispatchAfter,dispatchSync,getQueueManager,QueueManager,setQueueManager};export function backoffSeconds(value){const seconds=Number(value);return Number.isFinite(seconds)&&seconds>=0?seconds:1}export class RedisQueue{queue;config;isProcessing=false;constructor(name,config){this.config=config;this.queue=new BunQueue(name,{driver:"redis",prefix:config.prefix,redis:config.redis?{url:config.redis.url||this.buildRedisUrl(config.redis)}:undefined,defaultJobOptions:config.defaultJobOptions?{delay:config.defaultJobOptions.delay,attempts:config.defaultJobOptions.attempts,backoff:config.defaultJobOptions.backoff,removeOnComplete:config.defaultJobOptions.removeOnComplete,removeOnFail:config.defaultJobOptions.removeOnFail,priority:config.defaultJobOptions.priority,lifo:config.defaultJobOptions.lifo,timeout:config.defaultJobOptions.timeout,jobId:config.defaultJobOptions.jobId,dependsOn:config.defaultJobOptions.dependsOn,keepJobs:config.defaultJobOptions.keepJobs,deadLetter:config.defaultJobOptions.deadLetter}:undefined,limiter:config.limiter,metrics:config.metrics,stalledJobCheckInterval:config.stalledJobCheckInterval,maxStalledJobRetries:config.maxStalledJobRetries,distributedLock:config.distributedLock,defaultDeadLetterOptions:config.defaultDeadLetterOptions,horizontalScaling:config.horizontalScaling,logLevel:config.logLevel});log.debug(`Redis queue "${name}" initialized`)}buildRedisUrl(redis){const host=redis.host||"localhost";const port=redis.port||6379;const passwordSegment=redis.password?`:${encodeURIComponent(redis.password)}@`:"";const db=Number.isFinite(redis.db)&&redis.db>=0?redis.db:0;return`redis://${passwordSegment}${host}:${port}/${db}`}async add(data,options){const jobOptions={delay:options?.delay?options.delay*1000:undefined,attempts:options?.maxTries,priority:options?.priority,timeout:options?.timeout?options.timeout*1000:undefined,backoff:Array.isArray(options?.backoff)?options.backoff.map((s)=>backoffSeconds(s)*1000):typeof options?.backoff==="number"?{type:"fixed",delay:backoffSeconds(options.backoff)*1000}:undefined};return this.queue.add(data,jobOptions)}process(concurrency,handler){if(this.isProcessing){log.warn("Queue is already processing");return}this.isProcessing=true;this.queue.process(concurrency,handler);log.info(`Started processing queue with concurrency ${concurrency}`)}async getJob(jobId){return this.queue.getJob(jobId)}async getJobs(status){return this.queue.getJobs(status)}async getJobCounts(){return this.queue.getJobCounts()}async removeJob(jobId){return this.queue.removeJob(jobId)}async pause(){return this.queue.pause()}async resume(){return this.queue.resume()}async empty(){return this.queue.empty()}async close(){this.isProcessing=false;return this.queue.close()}async getMetrics(){return this.queue.getMetrics()}async ping(){return this.queue.ping()}async scheduleCron(options){return this.queue.scheduleCron({cronExpression:options.cron,data:options.data,timezone:options.tz,jobId:options.name})}async unscheduleCron(jobId){return this.queue.unscheduleCron(jobId)}async getDeadLetterJobs(){return this.queue.getDeadLetterJobs()}async republishDeadLetterJob(jobId){return this.queue.republishDeadLetterJob(jobId)}async clearDeadLetterQueue(){return this.queue.clearDeadLetterQueue()}async bulkRemove(jobIds){return this.queue.bulkRemove(jobIds)}async getClusterInfo(){return this.queue.getClusterInfo()}isLeader(){return this.queue.isLeader()}getQueue(){return this.queue}on(event,handler){this.queue.events.on(event,handler)}}const sharedQueues=new Map;export function sharedRedisQueue(name,config){const key=`${name}\x00${JSON.stringify(config)}`;let queue=sharedQueues.get(key);if(!queue){queue=new RedisQueue(name,config);sharedQueues.set(key,queue)}return queue}export async function closeSharedRedisQueues(){const queues=[...sharedQueues.values()];sharedQueues.clear();await Promise.all(queues.map((queue)=>queue.close()))}export class StacksQueueManager{config;queues=new Map;defaultConnection="default";constructor(config){this.config=config;for(const[name,connectionConfig]of Object.entries(config)){if(connectionConfig.driver==="redis"){this.queues.set(name,new RedisQueue(name,connectionConfig))}}}queue(name){const queueName=name||this.defaultConnection;let queue=this.queues.get(queueName);if(!queue){const config=this.config[queueName];if(!config){throw new Error(`Queue "${queueName}" not configured`)}queue=new RedisQueue(queueName,config);this.queues.set(queueName,queue)}return queue}setDefaultConnection(name){this.defaultConnection=name}async closeAll(){const closePromises=Array.from(this.queues.values()).map((q)=>q.close());await Promise.all(closePromises);this.queues.clear()}}export function createRedisDispatcher(queueName,config){const queue=new RedisQueue(queueName,config);return async(data,options)=>{return queue.add(data,options)}}export class RedisJob{data;options={};queue;constructor(queueName,config,data){this.data=data;this.queue=new RedisQueue(queueName,config)}async dispatch(){await this.queue.add(this.data,this.options)}async dispatchNow(){await this.queue.add(this.data,{...this.options,immediate:true})}delay(seconds){this.options.delay=seconds;return this}afterResponse(){this.options.afterResponse=true;return this}chain(jobs){this.options.chainedJobs=jobs;return this}onQueue(queue){this.options.queue=queue;return this}priority(level){this.options.priority=level;return this}tries(count){this.options.maxTries=count;return this}timeout(seconds){this.options.timeout=seconds;return this}backoff(attempts){this.options.backoff=attempts;return this}}
package/dist/envelope.js CHANGED
@@ -1 +1 @@
1
- export const JOB_ENVELOPE_VERSION=1;export function createEnvelope(jobName,payload,options,traceId,context){return{jobName,payload,options,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:new Date().toISOString(),...traceId?{traceId}:{},...context!==void 0?{context}:{}}}export function serializeEnvelope(envelope){try{return JSON.stringify(envelope)}catch(err){throw serializationError(envelope,err)}}export function assertEnvelopeSerializable(envelope){serializeEnvelope(envelope)}function serializationError(envelope,cause){const seeContract="See the JSON round-trip contract in @stacksjs/queue's src/envelope.ts.";if(isBigIntFailure(cause)){let offender=null;try{offender=findBigInt(envelope,"",new Set)}catch{}const where=offender?`\`${offender.path}\` is a BigInt (${offender.value}n)`:"it holds a BigInt";return Error(`[queue] Job "${envelope.jobName}" was not dispatched: ${where}, and job envelopes travel as JSON, which cannot represent one. Convert it where you dispatch - \`String(value)\` keeps every digit, \`Number(value)\` is exact below 2^53 - and convert it back inside the job handler. ${seeContract}`,{cause})}if(isCircularFailure(cause))return Error(`[queue] Job "${envelope.jobName}" was not dispatched: its payload contains a circular reference, which JSON cannot represent. Send the ids of the things the payload points at rather than the objects themselves - that also keeps the job replayable once those objects have changed. ${seeContract}`,{cause});const detail=cause instanceof Error?cause.message:String(cause);return Error(`[queue] Job "${envelope.jobName}" was not dispatched: serializing its payload threw (${detail}). JSON rejects only two things on its own and this was neither, so the throw came from the payload - a \`toJSON()\` or a property getter. ${seeContract}`,{cause})}function isBigIntFailure(cause){return cause instanceof TypeError&&/bigint/i.test(cause.message)}function isCircularFailure(cause){return cause instanceof TypeError&&/circular|cyclic/i.test(cause.message)}function findBigInt(value,path,seen){if(typeof value==="bigint")return{path:path||"envelope",value};if(!value||typeof value!=="object")return null;if(seen.has(value))return null;seen.add(value);if(Array.isArray(value)){for(let i=0;i<value.length;i++){const hit=findBigInt(value[i],`${path}[${i}]`,seen);if(hit)return hit}return null}for(const[key,child]of Object.entries(value)){const hit=findBigInt(child,path?`${path}.${key}`:key,seen);if(hit)return hit}return null}const warned=new Set;function warnOnce(source,message){if(warned.has(source))return;warned.add(source);console.warn(message)}export function clearEnvelopeWarnings(){warned.clear()}export function parseEnvelope(raw){let obj;if(typeof raw==="string")try{obj=JSON.parse(raw)}catch{return{ok:!1,reason:"malformed",detail:"not valid JSON"}}else if(raw&&typeof raw==="object")obj=raw;else return{ok:!1,reason:"malformed",detail:`expected string or object, got ${typeof raw}`};if(obj.envelopeVersion===JOB_ENVELOPE_VERSION){if(typeof obj.jobName!=="string")return{ok:!1,reason:"missing-job-name"};return{ok:!0,envelope:{jobName:obj.jobName,payload:obj.payload,options:obj.options??void 0,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:typeof obj.dispatchedAt==="string"?obj.dispatchedAt:new Date(0).toISOString(),...typeof obj.traceId==="string"&&obj.traceId?{traceId:obj.traceId}:{},...obj.context!==void 0?{context:obj.context}:{}},source:"v1"}}if(typeof obj.envelopeVersion==="number"&&obj.envelopeVersion>JOB_ENVELOPE_VERSION)return{ok:!1,reason:"unknown-version",detail:`envelopeVersion=${obj.envelopeVersion}, this worker speaks v${JOB_ENVELOPE_VERSION}`};if(typeof obj.jobName==="string"){warnOnce("v0-implicit","[queue/envelope] Processing pre-#1884 job envelope without envelopeVersion. In-flight jobs from before the upgrade will continue to work; new dispatches use the v1 shape automatically.");return{ok:!0,envelope:{jobName:obj.jobName,payload:obj.payload,options:obj.options??void 0,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:typeof obj.dispatchedAt==="string"?obj.dispatchedAt:new Date(0).toISOString(),...typeof obj.traceId==="string"&&obj.traceId?{traceId:obj.traceId}:{}},source:"v0-implicit"}}if(typeof obj.job==="string"){warnOnce("laravel-legacy","[queue/envelope] Processing Laravel-legacy job envelope (`{ job, data }` shape). Will continue to process but the queue table contains migration-era rows - consider flushing once they drain.");return{ok:!0,envelope:{jobName:obj.job.replace(/^App\\+Jobs\\+/,"").replace(/^.*\\/,""),payload:obj.data,options:void 0,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:new Date(0).toISOString()},source:"laravel-legacy"}}return{ok:!1,reason:"missing-job-name"}}
1
+ export const JOB_ENVELOPE_VERSION=1;export function createEnvelope(jobName,payload,options,traceId,context){return{jobName,payload,options,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:new Date().toISOString(),...traceId?{traceId}:{},...context!==undefined?{context}:{}}}export function serializeEnvelope(envelope){try{return JSON.stringify(envelope)}catch(err){throw serializationError(envelope,err)}}export function assertEnvelopeSerializable(envelope){serializeEnvelope(envelope)}function serializationError(envelope,cause){const seeContract="See the JSON round-trip contract in @stacksjs/queue's src/envelope.ts.";if(isBigIntFailure(cause)){let offender=null;try{offender=findBigInt(envelope,"",new Set)}catch{}const where=offender?`\`${offender.path}\` is a BigInt (${offender.value}n)`:"it holds a BigInt";return new Error(`[queue] Job "${envelope.jobName}" was not dispatched: ${where}, `+"and job envelopes travel as JSON, which cannot represent one. Convert it where you dispatch - "+"`String(value)` keeps every digit, `Number(value)` is exact below 2^53 - and convert it back inside "+`the job handler. ${seeContract}`,{cause})}if(isCircularFailure(cause)){return new Error(`[queue] Job "${envelope.jobName}" was not dispatched: its payload contains a circular reference, `+"which JSON cannot represent. Send the ids of the things the payload points at rather than the "+`objects themselves - that also keeps the job replayable once those objects have changed. ${seeContract}`,{cause})}const detail=cause instanceof Error?cause.message:String(cause);return new Error(`[queue] Job "${envelope.jobName}" was not dispatched: serializing its payload threw (${detail}). `+"JSON rejects only two things on its own and this was neither, so the throw came from the payload - "+`a \`toJSON()\` or a property getter. ${seeContract}`,{cause})}function isBigIntFailure(cause){return cause instanceof TypeError&&/bigint/i.test(cause.message)}function isCircularFailure(cause){return cause instanceof TypeError&&/circular|cyclic/i.test(cause.message)}function findBigInt(value,path,seen){if(typeof value==="bigint")return{path:path||"envelope",value};if(!value||typeof value!=="object")return null;if(seen.has(value))return null;seen.add(value);if(Array.isArray(value)){for(let i=0;i<value.length;i++){const hit=findBigInt(value[i],`${path}[${i}]`,seen);if(hit)return hit}return null}for(const[key,child]of Object.entries(value)){const hit=findBigInt(child,path?`${path}.${key}`:key,seen);if(hit)return hit}return null}const warned=new Set;function warnOnce(source,message){if(warned.has(source))return;warned.add(source);console.warn(message)}export function clearEnvelopeWarnings(){warned.clear()}export function parseEnvelope(raw){let obj;if(typeof raw==="string"){try{obj=JSON.parse(raw)}catch{return{ok:false,reason:"malformed",detail:"not valid JSON"}}}else if(raw&&typeof raw==="object"){obj=raw}else{return{ok:false,reason:"malformed",detail:`expected string or object, got ${typeof raw}`}}if(obj.envelopeVersion===JOB_ENVELOPE_VERSION){if(typeof obj.jobName!=="string"){return{ok:false,reason:"missing-job-name"}}const envelope={jobName:obj.jobName,payload:obj.payload,options:obj.options??undefined,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:typeof obj.dispatchedAt==="string"?obj.dispatchedAt:new Date(0).toISOString(),...typeof obj.traceId==="string"&&obj.traceId?{traceId:obj.traceId}:{},...obj.context!==undefined?{context:obj.context}:{}};return{ok:true,envelope,source:"v1"}}if(typeof obj.envelopeVersion==="number"&&obj.envelopeVersion>JOB_ENVELOPE_VERSION){return{ok:false,reason:"unknown-version",detail:`envelopeVersion=${obj.envelopeVersion}, this worker speaks v${JOB_ENVELOPE_VERSION}`}}if(typeof obj.jobName==="string"){warnOnce("v0-implicit","[queue/envelope] Processing pre-#1884 job envelope without envelopeVersion. "+"In-flight jobs from before the upgrade will continue to work; new dispatches "+"use the v1 shape automatically.");return{ok:true,envelope:{jobName:obj.jobName,payload:obj.payload,options:obj.options??undefined,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:typeof obj.dispatchedAt==="string"?obj.dispatchedAt:new Date(0).toISOString(),...typeof obj.traceId==="string"&&obj.traceId?{traceId:obj.traceId}:{}},source:"v0-implicit"}}if(typeof obj.job==="string"){warnOnce("laravel-legacy","[queue/envelope] Processing Laravel-legacy job envelope (`{ job, data }` shape). "+"Will continue to process but the queue table contains migration-era rows - "+"consider flushing once they drain.");const jobName=obj.job.replace(/^App\\+Jobs\\+/,"").replace(/^.*\\/,"");return{ok:true,envelope:{jobName,payload:obj.data,options:undefined,envelopeVersion:JOB_ENVELOPE_VERSION,dispatchedAt:new Date(0).toISOString()},source:"laravel-legacy"}}return{ok:false,reason:"missing-job-name"}}
package/dist/events.js CHANGED
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";export class QueueEvents{handlers=new Map;wildcardHandlers=new Set;listenerSubscriptions=new WeakMap;reclaim=new FinalizationRegistry((unsubscribe)=>{unsubscribe()});on(event,handler){if(!this.handlers.has(event))this.handlers.set(event,new Set);this.handlers.get(event).add(handler);return()=>{this.handlers.get(event)?.delete(handler)}}subscribeListener(listener,event,method){const ref=new WeakRef(listener),weakHandler=(payload)=>{const target=ref.deref();if(target===void 0){removeFromHandlers();return}return method.call(target,payload)},removeFromHandlers=this.on(event,weakHandler),unsubscribe=()=>{removeFromHandlers();const target=ref.deref();if(target===void 0)return;const subscriptions=this.listenerSubscriptions.get(target);if(!subscriptions)return;subscriptions.delete(unsubscribe);if(subscriptions.size===0){this.listenerSubscriptions.delete(target);this.reclaim.unregister(target)}};let owned=this.listenerSubscriptions.get(listener);if(!owned){owned=new Set;this.listenerSubscriptions.set(listener,owned)}owned.add(unsubscribe);this.reclaim.register(listener,removeFromHandlers,listener);return unsubscribe}unsubscribeListener(listener){const owned=this.listenerSubscriptions.get(listener);if(!owned)return 0;const all=Array.from(owned);for(const unsubscribe of all)unsubscribe();this.listenerSubscriptions.delete(listener);this.reclaim.unregister(listener);return all.length}listenerCount(event){if(event==="*")return this.wildcardHandlers.size;return this.handlers.get(event)?.size??0}onAny(handler){this.wildcardHandlers.add(handler);return()=>{this.wildcardHandlers.delete(handler)}}once(event,handler){const wrappedHandler=async(payload)=>{this.handlers.get(event)?.delete(wrappedHandler);await handler(payload)};return this.on(event,wrappedHandler)}async emit(event,payload){const fullPayload={...payload,timestamp:Date.now()};this.logEvent(event,fullPayload);const handlers=this.handlers.get(event);if(handlers)for(const handler of handlers)try{await handler(fullPayload)}catch(error){log.error(`Error in queue event handler for ${event}:`,error)}for(const handler of this.wildcardHandlers)try{await handler(event,fullPayload)}catch(error){log.error("Error in wildcard queue event handler:",error)}}logEvent(event,payload){const jobInfo=payload.jobId?`[${payload.jobId}]`:"",queueInfo=payload.queueName?`on ${payload.queueName}`:"";switch(event){case"job:added":log.debug(`Job added ${jobInfo} ${queueInfo}`);break;case"job:processing":log.debug(`Job processing ${jobInfo} ${queueInfo}`);break;case"job:completed":log.info(`Job completed ${jobInfo} ${queueInfo} in ${payload.duration}ms`);break;case"job:failed":log.error(`Job failed ${jobInfo} ${queueInfo}:`,payload.error);break;case"job:retrying":log.warn(`Job retrying ${jobInfo} ${queueInfo} (attempt ${payload.attemptsMade})`);break;case"job:stalled":log.warn(`Job stalled ${jobInfo} ${queueInfo}`);break;case"queue:error":log.error(`Queue error ${queueInfo}:`,payload.error);break}}off(event){this.handlers.delete(event)}removeAllListeners(){this.handlers.clear();this.wildcardHandlers.clear();this.listenerSubscriptions=new WeakMap}}let globalEvents=null;export function getQueueEvents(){if(!globalEvents)globalEvents=new QueueEvents;return globalEvents}export function onQueueEvent(event,handler){const events=getQueueEvents();if(event==="*")return events.onAny(handler);return events.on(event,handler)}export function emitQueueEvent(event,payload){return getQueueEvents().emit(event,payload)}export function withEvents(queueName,handler){return async(...args)=>{const jobId=args[0]?.id||"unknown",startTime=Date.now();await emitQueueEvent("job:processing",{jobId,queueName,data:args[0]?.data});try{const result=await handler(...args);await emitQueueEvent("job:completed",{jobId,queueName,result,duration:Date.now()-startTime});return result}catch(error){await emitQueueEvent("job:failed",{jobId,queueName,error,duration:Date.now()-startTime});throw error}}}export function OnQueueEvent(event){return function(value,context){if(typeof context!=="object"||context===null)throw TypeError(`@OnQueueEvent('${event}') requires standard (TC39) decorators. Legacy decorators ('experimentalDecorators: true') give a method decorator no construction-time hook, so the handler cannot be bound to an instance.`);if(context.kind!=="method")throw TypeError(`@OnQueueEvent('${event}') can only decorate a class method, but it was applied to a ${context.kind}${context.name===void 0?"":` ('${String(context.name)}')`}. Move the handler into a method, or call onQueueEvent('${event}', handler) directly.`);if(context.static)throw TypeError(`@OnQueueEvent('${event}') cannot decorate the static method '${String(context.name)}': a static method has no instance, so it would subscribe at class-definition time and stay subscribed for the life of the process, even if the class is never used. Use an instance method, or subscribe explicitly with onQueueEvent('${event}', MyClass.${String(context.name)}).`);context.addInitializer(function(){getQueueEvents().subscribeListener(this,event,value)});return value}}export class QueueMetrics{jobCounts={added:0,completed:0,failed:0,processing:0};completions=[];errors=[];unsubscribe=[];constructor(){this.setupListeners()}setupListeners(){const events=getQueueEvents();this.unsubscribe.push(events.on("job:added",()=>{this.jobCounts.added++}),events.on("job:processing",()=>{this.jobCounts.processing++}),events.on("job:completed",(payload)=>{this.jobCounts.completed++;this.jobCounts.processing=Math.max(0,this.jobCounts.processing-1);const duration=payload.duration||0;this.completions.push({timestamp:Date.now(),duration});if(this.completions.length>1000)this.completions.shift()}),events.on("job:failed",(payload)=>{this.jobCounts.failed++;this.jobCounts.processing=Math.max(0,this.jobCounts.processing-1);if(payload.error){this.errors.push({error:payload.error,timestamp:Date.now()});if(this.errors.length>100)this.errors.shift()}}))}getThroughputPerMinute(){const oneMinuteAgo=Date.now()-60000;return this.completions.filter((c)=>c.timestamp>=oneMinuteAgo).length}getAverageProcessingTime(){const oneMinuteAgo=Date.now()-60000,recent=this.completions.filter((c)=>c.timestamp>=oneMinuteAgo);if(recent.length===0)return 0;return recent.reduce((sum,c)=>sum+c.duration,0)/recent.length}getMetrics(){return{counts:{...this.jobCounts},averageDuration:this.getAverageProcessingTime(),recentErrors:[...this.errors],throughputPerMinute:this.getThroughputPerMinute()}}reset(){this.jobCounts={added:0,completed:0,failed:0,processing:0};this.completions=[];this.errors=[]}stop(){this.unsubscribe.forEach((fn)=>fn());this.unsubscribe=[]}}let globalMetrics=null;export function getGlobalMetrics(){if(!globalMetrics)globalMetrics=new QueueMetrics;return globalMetrics}class WorkerTracker{workers=new Map;register(id,queue){this.workers.set(id,{id,status:"idle",queue,processedCount:0,failedCount:0,lastActivityAt:new Date().toISOString(),startedAt:new Date().toISOString()})}markActive(id){const w=this.workers.get(id);if(w){w.status="active";w.lastActivityAt=new Date().toISOString()}}markIdle(id){const w=this.workers.get(id);if(w){w.status="idle";w.lastActivityAt=new Date().toISOString()}}recordCompletion(id){const w=this.workers.get(id);if(w){w.processedCount++;w.lastActivityAt=new Date().toISOString()}}recordFailure(id){const w=this.workers.get(id);if(w){w.failedCount++;w.lastActivityAt=new Date().toISOString()}}unregister(id){const w=this.workers.get(id);if(w)w.status="stopped"}getAll(){return Array.from(this.workers.values())}clear(){this.workers.clear()}}const workerTracker=new WorkerTracker;export function getWorkerTracker(){return workerTracker}
1
+ import{log}from"@stacksjs/logging";export class QueueEvents{handlers=new Map;wildcardHandlers=new Set;listenerSubscriptions=new WeakMap;reclaim=new FinalizationRegistry((unsubscribe)=>{unsubscribe()});on(event,handler){if(!this.handlers.has(event)){this.handlers.set(event,new Set)}this.handlers.get(event).add(handler);return()=>{this.handlers.get(event)?.delete(handler)}}subscribeListener(listener,event,method){const ref=new WeakRef(listener);const weakHandler=(payload)=>{const target=ref.deref();if(target===undefined){removeFromHandlers();return}return method.call(target,payload)};const removeFromHandlers=this.on(event,weakHandler);const unsubscribe=()=>{removeFromHandlers();const target=ref.deref();if(target===undefined)return;const subscriptions=this.listenerSubscriptions.get(target);if(!subscriptions)return;subscriptions.delete(unsubscribe);if(subscriptions.size===0){this.listenerSubscriptions.delete(target);this.reclaim.unregister(target)}};let owned=this.listenerSubscriptions.get(listener);if(!owned){owned=new Set;this.listenerSubscriptions.set(listener,owned)}owned.add(unsubscribe);this.reclaim.register(listener,removeFromHandlers,listener);return unsubscribe}unsubscribeListener(listener){const owned=this.listenerSubscriptions.get(listener);if(!owned)return 0;const all=Array.from(owned);for(const unsubscribe of all)unsubscribe();this.listenerSubscriptions.delete(listener);this.reclaim.unregister(listener);return all.length}listenerCount(event){if(event==="*")return this.wildcardHandlers.size;return this.handlers.get(event)?.size??0}onAny(handler){this.wildcardHandlers.add(handler);return()=>{this.wildcardHandlers.delete(handler)}}once(event,handler){const wrappedHandler=async(payload)=>{this.handlers.get(event)?.delete(wrappedHandler);await handler(payload)};return this.on(event,wrappedHandler)}async emit(event,payload){const fullPayload={...payload,timestamp:Date.now()};this.logEvent(event,fullPayload);const handlers=this.handlers.get(event);if(handlers){for(const handler of handlers){try{await handler(fullPayload)}catch(error){log.error(`Error in queue event handler for ${event}:`,error)}}}for(const handler of this.wildcardHandlers){try{await handler(event,fullPayload)}catch(error){log.error(`Error in wildcard queue event handler:`,error)}}}logEvent(event,payload){const jobInfo=payload.jobId?`[${payload.jobId}]`:"";const queueInfo=payload.queueName?`on ${payload.queueName}`:"";switch(event){case"job:added":log.debug(`Job added ${jobInfo} ${queueInfo}`);break;case"job:processing":log.debug(`Job processing ${jobInfo} ${queueInfo}`);break;case"job:completed":log.info(`Job completed ${jobInfo} ${queueInfo} in ${payload.duration}ms`);break;case"job:failed":log.error(`Job failed ${jobInfo} ${queueInfo}:`,payload.error);break;case"job:retrying":log.warn(`Job retrying ${jobInfo} ${queueInfo} (attempt ${payload.attemptsMade})`);break;case"job:stalled":log.warn(`Job stalled ${jobInfo} ${queueInfo}`);break;case"queue:error":log.error(`Queue error ${queueInfo}:`,payload.error);break}}off(event){this.handlers.delete(event)}removeAllListeners(){this.handlers.clear();this.wildcardHandlers.clear();this.listenerSubscriptions=new WeakMap}}let globalEvents=null;export function getQueueEvents(){if(!globalEvents){globalEvents=new QueueEvents}return globalEvents}export function onQueueEvent(event,handler){const events=getQueueEvents();if(event==="*"){return events.onAny(handler)}return events.on(event,handler)}export function emitQueueEvent(event,payload){return getQueueEvents().emit(event,payload)}export function withEvents(queueName,handler){return async(...args)=>{const jobId=args[0]?.id||"unknown";const startTime=Date.now();await emitQueueEvent("job:processing",{jobId,queueName,data:args[0]?.data});try{const result=await handler(...args);await emitQueueEvent("job:completed",{jobId,queueName,result,duration:Date.now()-startTime});return result}catch(error){await emitQueueEvent("job:failed",{jobId,queueName,error,duration:Date.now()-startTime});throw error}}}export function OnQueueEvent(event){return function(value,context){if(typeof context!=="object"||context===null){throw new TypeError(`@OnQueueEvent('${event}') requires standard (TC39) decorators. `+`Legacy decorators ('experimentalDecorators: true') give a method decorator `+`no construction-time hook, so the handler cannot be bound to an instance.`)}if(context.kind!=="method"){throw new TypeError(`@OnQueueEvent('${event}') can only decorate a class method, but it was applied `+`to a ${context.kind}${context.name===undefined?"":` ('${String(context.name)}')`}. `+`Move the handler into a method, or call onQueueEvent('${event}', handler) directly.`)}if(context.static){throw new TypeError(`@OnQueueEvent('${event}') cannot decorate the static method '${String(context.name)}': `+`a static method has no instance, so it would subscribe at class-definition time `+`and stay subscribed for the life of the process, even if the class is never used. `+`Use an instance method, or subscribe explicitly with `+`onQueueEvent('${event}', MyClass.${String(context.name)}).`)}context.addInitializer(function(){getQueueEvents().subscribeListener(this,event,value)});return value}}export class QueueMetrics{jobCounts={added:0,completed:0,failed:0,processing:0};completions=[];errors=[];unsubscribe=[];constructor(){this.setupListeners()}setupListeners(){const events=getQueueEvents();this.unsubscribe.push(events.on("job:added",()=>{this.jobCounts.added++}),events.on("job:processing",()=>{this.jobCounts.processing++}),events.on("job:completed",(payload)=>{this.jobCounts.completed++;this.jobCounts.processing=Math.max(0,this.jobCounts.processing-1);const duration=payload.duration||0;this.completions.push({timestamp:Date.now(),duration});if(this.completions.length>1000){this.completions.shift()}}),events.on("job:failed",(payload)=>{this.jobCounts.failed++;this.jobCounts.processing=Math.max(0,this.jobCounts.processing-1);if(payload.error){this.errors.push({error:payload.error,timestamp:Date.now()});if(this.errors.length>100){this.errors.shift()}}}))}getThroughputPerMinute(){const oneMinuteAgo=Date.now()-60000;const recentCount=this.completions.filter((c)=>c.timestamp>=oneMinuteAgo).length;return recentCount}getAverageProcessingTime(){const oneMinuteAgo=Date.now()-60000;const recent=this.completions.filter((c)=>c.timestamp>=oneMinuteAgo);if(recent.length===0)return 0;return recent.reduce((sum,c)=>sum+c.duration,0)/recent.length}getMetrics(){return{counts:{...this.jobCounts},averageDuration:this.getAverageProcessingTime(),recentErrors:[...this.errors],throughputPerMinute:this.getThroughputPerMinute()}}reset(){this.jobCounts={added:0,completed:0,failed:0,processing:0};this.completions=[];this.errors=[]}stop(){this.unsubscribe.forEach((fn)=>fn());this.unsubscribe=[]}}let globalMetrics=null;export function getGlobalMetrics(){if(!globalMetrics){globalMetrics=new QueueMetrics}return globalMetrics}class WorkerTracker{workers=new Map;register(id,queue){this.workers.set(id,{id,status:"idle",queue,processedCount:0,failedCount:0,lastActivityAt:new Date().toISOString(),startedAt:new Date().toISOString()})}markActive(id){const w=this.workers.get(id);if(w){w.status="active";w.lastActivityAt=new Date().toISOString()}}markIdle(id){const w=this.workers.get(id);if(w){w.status="idle";w.lastActivityAt=new Date().toISOString()}}recordCompletion(id){const w=this.workers.get(id);if(w){w.processedCount++;w.lastActivityAt=new Date().toISOString()}}recordFailure(id){const w=this.workers.get(id);if(w){w.failedCount++;w.lastActivityAt=new Date().toISOString()}}unregister(id){const w=this.workers.get(id);if(w){w.status="stopped"}}getAll(){return Array.from(this.workers.values())}clear(){this.workers.clear()}}const workerTracker=new WorkerTracker;export function getWorkerTracker(){return workerTracker}
package/dist/health.js CHANGED
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";import{getGlobalMetrics,getWorkerTracker}from"./events";export function queuedJobState(job,nowTimestamp=Math.floor(Date.now()/1000)){if(job.reserved_at)return"processing";const availableAt=typeof job.available_at==="number"?job.available_at:typeof job.available_at==="string"&&job.available_at.trim()?Number(job.available_at):Number.NaN;if(Number.isFinite(availableAt)&&availableAt>nowTimestamp)return"delayed";return"pending"}const defaultConfig={maxPendingWarning:1000,maxPendingCritical:5000,maxFailedWarning:10,maxFailedCritical:100,maxJobAgeWarning:3600,maxJobAgeCritical:86400,maxErrorRateWarning:0.1,maxErrorRateCritical:0.5};export async function checkQueueHealth(config={}){const cfg={...defaultConfig,...config},alerts=[],now=new Date,nowTimestamp=Math.floor(now.getTime()/1000);try{const{db}=await import("@stacksjs/database/runtime"),jobs=await db.selectFrom("jobs").selectAll().execute(),failedJobs=await db.selectFrom("failed_jobs").selectAll().execute(),queueMap=new Map;for(const job of jobs){const queueName=job.queue||"default";if(!queueMap.has(queueName))queueMap.set(queueName,{pending:0,processing:0,delayed:0});const stats=queueMap.get(queueName),state=queuedJobState(job,nowTimestamp);if(state==="processing")stats.processing++;else if(state==="delayed")stats.delayed++;else{stats.pending++;if(job.created_at){const createdAt=typeof job.created_at==="number"?job.created_at:utcSeconds(job.created_at),age=nowTimestamp-createdAt;if(!stats.oldestAge||age>stats.oldestAge)stats.oldestAge=age}}}const failedByQueue=new Map;for(const fj of failedJobs){const queueName=fj.queue||"default";failedByQueue.set(queueName,(failedByQueue.get(queueName)||0)+1)}const queueStatuses=[],allQueues=new Set([...queueMap.keys(),...failedByQueue.keys()]),queuesToCheck=cfg.queues?[...allQueues].filter((q)=>cfg.queues.includes(q)):[...allQueues];let totalPending=0,totalProcessing=0,totalDelayed=0,totalFailed=0;for(const queueName of queuesToCheck){const stats=queueMap.get(queueName)||{pending:0,processing:0,delayed:0},failed=failedByQueue.get(queueName)||0;totalPending+=stats.pending;totalProcessing+=stats.processing;totalDelayed+=stats.delayed;totalFailed+=failed;let status="healthy";if(stats.pending>=cfg.maxPendingCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has ${stats.pending} pending jobs (threshold: ${cfg.maxPendingCritical})`,queue:queueName,timestamp:now.toISOString()})}else if(stats.pending>=cfg.maxPendingWarning){status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has ${stats.pending} pending jobs (threshold: ${cfg.maxPendingWarning})`,queue:queueName,timestamp:now.toISOString()})}if(failed>=cfg.maxFailedCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has ${failed} failed jobs (threshold: ${cfg.maxFailedCritical})`,queue:queueName,timestamp:now.toISOString()})}else if(failed>=cfg.maxFailedWarning){if(status==="healthy")status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has ${failed} failed jobs (threshold: ${cfg.maxFailedWarning})`,queue:queueName,timestamp:now.toISOString()})}if(stats.oldestAge){if(stats.oldestAge>=cfg.maxJobAgeCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has a job waiting for ${Math.floor(stats.oldestAge/3600)} hours`,queue:queueName,timestamp:now.toISOString()})}else if(stats.oldestAge>=cfg.maxJobAgeWarning){if(status==="healthy")status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has a job waiting for ${Math.floor(stats.oldestAge/60)} minutes`,queue:queueName,timestamp:now.toISOString()})}}queueStatuses.push({name:queueName,status,pending:stats.pending,processing:stats.processing,delayed:stats.delayed,failed,oldestJobAge:stats.oldestAge})}const metricsData=getGlobalMetrics().getMetrics(),{throughputPerMinute,averageDuration:averageProcessingTime}=metricsData,totalJobs=totalPending+totalProcessing+totalDelayed+totalFailed,errorRate=totalJobs>0?totalFailed/totalJobs:0;let overallStatus="healthy";if(queueStatuses.some((q)=>q.status==="unhealthy"))overallStatus="unhealthy";else if(queueStatuses.some((q)=>q.status==="degraded"))overallStatus="degraded";if(errorRate>=cfg.maxErrorRateCritical){overallStatus="unhealthy";alerts.push({level:"critical",message:`Overall error rate is ${(errorRate*100).toFixed(1)}% (threshold: ${cfg.maxErrorRateCritical*100}%)`,timestamp:now.toISOString()})}else if(errorRate>=cfg.maxErrorRateWarning){if(overallStatus==="healthy")overallStatus="degraded";alerts.push({level:"warning",message:`Overall error rate is ${(errorRate*100).toFixed(1)}% (threshold: ${cfg.maxErrorRateWarning*100}%)`,timestamp:now.toISOString()})}const workerStatuses=getWorkerTracker().getAll().map((w)=>({id:w.id,status:w.status,queue:w.queue,processedCount:w.processedCount,failedCount:w.failedCount,lastActivityAt:w.lastActivityAt}));return{status:overallStatus,timestamp:now.toISOString(),queues:queueStatuses,workers:workerStatuses,metrics:{totalPending,totalProcessing,totalDelayed,totalFailed,throughputPerMinute,averageProcessingTime,errorRate},alerts}}catch(error){log.error("Failed to perform queue health check:",error);const workerStatuses=getWorkerTracker().getAll().map((w)=>({id:w.id,status:w.status,queue:w.queue,processedCount:w.processedCount,failedCount:w.failedCount,lastActivityAt:w.lastActivityAt}));return{status:"unhealthy",timestamp:now.toISOString(),queues:[],workers:workerStatuses,metrics:{totalPending:0,totalProcessing:0,totalDelayed:0,totalFailed:0,throughputPerMinute:0,averageProcessingTime:0,errorRate:0},alerts:[{level:"critical",message:`Health check failed: ${error.message}`,timestamp:now.toISOString()}]}}}export function createHealthCheckHandler(config={}){return async(_req)=>{const result=await checkQueueHealth(config),statusCode=result.status==="healthy"?200:result.status==="degraded"?207:503;return new Response(JSON.stringify(result,null,2),{status:statusCode,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}export async function isQueueHealthy(config={}){return(await checkQueueHealth(config)).status==="healthy"}export function utcSeconds(value){const text=String(value).trim(),zoned=/(?:Z|[+-]\d{2}:?\d{2})$/i.test(text);return Math.floor(new Date(zoned?text:`${text.replace(" ","T")}Z`).getTime()/1000)}
1
+ import{log}from"@stacksjs/logging";import{getGlobalMetrics,getWorkerTracker}from"./events";export function queuedJobState(job,nowTimestamp=Math.floor(Date.now()/1000)){if(job.reserved_at)return"processing";const availableAt=typeof job.available_at==="number"?job.available_at:typeof job.available_at==="string"&&job.available_at.trim()?Number(job.available_at):Number.NaN;if(Number.isFinite(availableAt)&&availableAt>nowTimestamp)return"delayed";return"pending"}const defaultConfig={maxPendingWarning:1000,maxPendingCritical:5000,maxFailedWarning:10,maxFailedCritical:100,maxJobAgeWarning:3600,maxJobAgeCritical:86400,maxErrorRateWarning:0.1,maxErrorRateCritical:0.5};export async function checkQueueHealth(config={}){const cfg={...defaultConfig,...config};const alerts=[];const now=new Date;const nowTimestamp=Math.floor(now.getTime()/1000);try{const{db}=await import("@stacksjs/database/runtime");const jobs=await db.selectFrom("jobs").selectAll().execute();const failedJobs=await db.selectFrom("failed_jobs").selectAll().execute();const queueMap=new Map;for(const job of jobs){const queueName=job.queue||"default";if(!queueMap.has(queueName)){queueMap.set(queueName,{pending:0,processing:0,delayed:0})}const stats=queueMap.get(queueName);const state=queuedJobState(job,nowTimestamp);if(state==="processing"){stats.processing++}else if(state==="delayed"){stats.delayed++}else{stats.pending++;if(job.created_at){const createdAt=typeof job.created_at==="number"?job.created_at:utcSeconds(job.created_at);const age=nowTimestamp-createdAt;if(!stats.oldestAge||age>stats.oldestAge){stats.oldestAge=age}}}}const failedByQueue=new Map;for(const fj of failedJobs){const queueName=fj.queue||"default";failedByQueue.set(queueName,(failedByQueue.get(queueName)||0)+1)}const queueStatuses=[];const allQueues=new Set([...queueMap.keys(),...failedByQueue.keys()]);const queuesToCheck=cfg.queues?[...allQueues].filter((q)=>cfg.queues.includes(q)):[...allQueues];let totalPending=0;let totalProcessing=0;let totalDelayed=0;let totalFailed=0;for(const queueName of queuesToCheck){const stats=queueMap.get(queueName)||{pending:0,processing:0,delayed:0};const failed=failedByQueue.get(queueName)||0;totalPending+=stats.pending;totalProcessing+=stats.processing;totalDelayed+=stats.delayed;totalFailed+=failed;let status="healthy";if(stats.pending>=cfg.maxPendingCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has ${stats.pending} pending jobs (threshold: ${cfg.maxPendingCritical})`,queue:queueName,timestamp:now.toISOString()})}else if(stats.pending>=cfg.maxPendingWarning){status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has ${stats.pending} pending jobs (threshold: ${cfg.maxPendingWarning})`,queue:queueName,timestamp:now.toISOString()})}if(failed>=cfg.maxFailedCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has ${failed} failed jobs (threshold: ${cfg.maxFailedCritical})`,queue:queueName,timestamp:now.toISOString()})}else if(failed>=cfg.maxFailedWarning){if(status==="healthy")status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has ${failed} failed jobs (threshold: ${cfg.maxFailedWarning})`,queue:queueName,timestamp:now.toISOString()})}if(stats.oldestAge){if(stats.oldestAge>=cfg.maxJobAgeCritical){status="unhealthy";alerts.push({level:"critical",message:`Queue "${queueName}" has a job waiting for ${Math.floor(stats.oldestAge/3600)} hours`,queue:queueName,timestamp:now.toISOString()})}else if(stats.oldestAge>=cfg.maxJobAgeWarning){if(status==="healthy")status="degraded";alerts.push({level:"warning",message:`Queue "${queueName}" has a job waiting for ${Math.floor(stats.oldestAge/60)} minutes`,queue:queueName,timestamp:now.toISOString()})}}queueStatuses.push({name:queueName,status,pending:stats.pending,processing:stats.processing,delayed:stats.delayed,failed,oldestJobAge:stats.oldestAge})}const metrics=getGlobalMetrics();const metricsData=metrics.getMetrics();const throughputPerMinute=metricsData.throughputPerMinute;const averageProcessingTime=metricsData.averageDuration;const totalJobs=totalPending+totalProcessing+totalDelayed+totalFailed;const errorRate=totalJobs>0?totalFailed/totalJobs:0;let overallStatus="healthy";if(queueStatuses.some((q)=>q.status==="unhealthy")){overallStatus="unhealthy"}else if(queueStatuses.some((q)=>q.status==="degraded")){overallStatus="degraded"}if(errorRate>=cfg.maxErrorRateCritical){overallStatus="unhealthy";alerts.push({level:"critical",message:`Overall error rate is ${(errorRate*100).toFixed(1)}% (threshold: ${cfg.maxErrorRateCritical*100}%)`,timestamp:now.toISOString()})}else if(errorRate>=cfg.maxErrorRateWarning){if(overallStatus==="healthy")overallStatus="degraded";alerts.push({level:"warning",message:`Overall error rate is ${(errorRate*100).toFixed(1)}% (threshold: ${cfg.maxErrorRateWarning*100}%)`,timestamp:now.toISOString()})}const trackedWorkers=getWorkerTracker().getAll();const workerStatuses=trackedWorkers.map((w)=>({id:w.id,status:w.status,queue:w.queue,processedCount:w.processedCount,failedCount:w.failedCount,lastActivityAt:w.lastActivityAt}));return{status:overallStatus,timestamp:now.toISOString(),queues:queueStatuses,workers:workerStatuses,metrics:{totalPending,totalProcessing,totalDelayed,totalFailed,throughputPerMinute,averageProcessingTime,errorRate},alerts}}catch(error){log.error("Failed to perform queue health check:",error);const trackedWorkers=getWorkerTracker().getAll();const workerStatuses=trackedWorkers.map((w)=>({id:w.id,status:w.status,queue:w.queue,processedCount:w.processedCount,failedCount:w.failedCount,lastActivityAt:w.lastActivityAt}));return{status:"unhealthy",timestamp:now.toISOString(),queues:[],workers:workerStatuses,metrics:{totalPending:0,totalProcessing:0,totalDelayed:0,totalFailed:0,throughputPerMinute:0,averageProcessingTime:0,errorRate:0},alerts:[{level:"critical",message:`Health check failed: ${error.message}`,timestamp:now.toISOString()}]}}}export function createHealthCheckHandler(config={}){return async(_req)=>{const result=await checkQueueHealth(config);const statusCode=result.status==="healthy"?200:result.status==="degraded"?207:503;return new Response(JSON.stringify(result,null,2),{status:statusCode,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}export async function isQueueHealthy(config={}){const result=await checkQueueHealth(config);return result.status==="healthy"}export function utcSeconds(value){const text=String(value).trim();const zoned=/(?:Z|[+-]\d{2}:?\d{2})$/i.test(text);return Math.floor(new Date(zoned?text:`${text.replace(" ","T")}Z`).getTime()/1000)}
@@ -1 +1 @@
1
- import{isUniqueViolation}from"@stacksjs/error-handling";import{isMissingTableError}from"./missing-table";let databaseModule;function loadDatabaseModule(){return databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=void 0;throw error})}let warnedAboutMissingJobIdempotencyTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingJobIdempotencyTable)return;warnedAboutMissingJobIdempotencyTable=!0;console.warn("[queue/idempotency] job_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.")}export async function hasDispatchedKey(key){try{const{db}=await loadDatabaseModule(),row=await db.selectFrom("job_idempotency").where("idempotency_key","=",key).select(["idempotency_key"]).executeTakeFirst();return Boolean(row)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function recordDispatchedKey(key,jobName,queue){try{const{db}=await loadDatabaseModule();await db.insertInto("job_idempotency").values({idempotency_key:key,job_name:jobName,queue:queue??"default",dispatched_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}if(isUniqueViolation(err))return;throw err}}export async function claimDispatchKey(key,jobName,queue){try{const{db}=await loadDatabaseModule();await db.insertInto("job_idempotency").values({idempotency_key:key,job_name:jobName,queue:queue??"default",dispatched_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();return"claimed"}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return"unenforced"}if(isUniqueViolation(err))return"duplicate";throw err}}export async function releaseDispatchKey(key){try{const{db}=await loadDatabaseModule();await db.deleteFrom("job_idempotency").where("idempotency_key","=",key).execute()}catch{}}
1
+ import{isUniqueViolation}from"@stacksjs/error-handling";import{isMissingTableError}from"./missing-table";let databaseModule;function loadDatabaseModule(){return databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=undefined;throw error})}let warnedAboutMissingJobIdempotencyTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingJobIdempotencyTable)return;warnedAboutMissingJobIdempotencyTable=true;console.warn("[queue/idempotency] job_idempotency table missing - idempotency keys are accepted but NOT enforced. Run migrations to enable dedup.")}export async function hasDispatchedKey(key){try{const{db}=await loadDatabaseModule();const row=await db.selectFrom("job_idempotency").where("idempotency_key","=",key).select(["idempotency_key"]).executeTakeFirst();return Boolean(row)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return false}throw err}}export async function recordDispatchedKey(key,jobName,queue){try{const{db}=await loadDatabaseModule();await db.insertInto("job_idempotency").values({idempotency_key:key,job_name:jobName,queue:queue??"default",dispatched_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}if(isUniqueViolation(err))return;throw err}}export async function claimDispatchKey(key,jobName,queue){try{const{db}=await loadDatabaseModule();await db.insertInto("job_idempotency").values({idempotency_key:key,job_name:jobName,queue:queue??"default",dispatched_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute();return"claimed"}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return"unenforced"}if(isUniqueViolation(err))return"duplicate";throw err}}export async function releaseDispatchKey(key){try{const{db}=await loadDatabaseModule();await db.deleteFrom("job_idempotency").where("idempotency_key","=",key).execute()}catch{}}
@@ -1 +1 @@
1
- const PROGRESS_KEY=(jobId)=>`__job_progress__:${jobId}`,CANCEL_KEY=(jobId)=>`__job_cancel__:${jobId}`,TTL_SECONDS=3600;let progressCacheModule;export function clampProgressPercent(percent){return Number.isFinite(percent)?Math.max(0,Math.min(100,percent)):0}export async function setJobProgress(jobId,percent,message){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await cache.set(PROGRESS_KEY(jobId),{percent:clampProgressPercent(percent),message,updatedAt:Date.now()},TTL_SECONDS)}export async function getJobProgress(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");return await cache.get(PROGRESS_KEY(jobId))??null}export async function cancelJob(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await cache.set(CANCEL_KEY(jobId),1,TTL_SECONDS)}export async function isJobCancelled(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");return Boolean(await cache.get(CANCEL_KEY(jobId)))}export async function clearJobState(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await Promise.all([cache.del(PROGRESS_KEY(jobId)),cache.del(CANCEL_KEY(jobId))])}
1
+ const PROGRESS_KEY=(jobId)=>`__job_progress__:${jobId}`;const CANCEL_KEY=(jobId)=>`__job_cancel__:${jobId}`;const TTL_SECONDS=60*60;let progressCacheModule;export function clampProgressPercent(percent){return Number.isFinite(percent)?Math.max(0,Math.min(100,percent)):0}export async function setJobProgress(jobId,percent,message){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await cache.set(PROGRESS_KEY(jobId),{percent:clampProgressPercent(percent),message,updatedAt:Date.now()},TTL_SECONDS)}export async function getJobProgress(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");return await cache.get(PROGRESS_KEY(jobId))??null}export async function cancelJob(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await cache.set(CANCEL_KEY(jobId),1,TTL_SECONDS)}export async function isJobCancelled(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");return Boolean(await cache.get(CANCEL_KEY(jobId)))}export async function clearJobState(jobId){const{cache}=progressCacheModule??=await import("@stacksjs/cache");await Promise.all([cache.del(PROGRESS_KEY(jobId)),cache.del(CANCEL_KEY(jobId))])}
package/dist/job.js CHANGED
@@ -1 +1 @@
1
- var {require}=import.meta;import{resolveQueueDriver}from"./driver";import{basename}from"node:path";import{appPath,frameworkPath}from"@stacksjs/path";import{enqueueAfterCommit,isInTransaction}from"@stacksjs/database/runtime";import{moveToDeadLetter}from"./dead-letter";import{assertEnvelopeSerializable,createEnvelope,serializeEnvelope}from"./envelope";import{claimDispatchKey,releaseDispatchKey}from"./idempotency";import{isQuarantined}from"./poison";import{runNamedAction}from"./action-runner";let testingModule,databaseModule,traceModule;function loadTraceModule(){return traceModule??=import("@stacksjs/router").catch((error)=>{traceModule=void 0;throw error})}function getQueueDriver(){return resolveQueueDriver()}let _warnedAfterCommitNoTx=!1;function warnAfterCommitOutsideTransaction(){if(_warnedAfterCommitNoTx)return;_warnedAfterCommitNoTx=!0;console.warn("[queue] .afterCommit() was called outside of `db.transaction(...)`. Dispatching immediately. Wrap the call in a transaction or drop .afterCommit() to silence this message.")}class JobBuilder{name;payload;options={};txMode="auto";constructor(name,payload){this.name=name;this.payload=payload}onQueue(queue){this.options.queue=queue;return this}delay(seconds){this.options.delay=seconds;return this}tries(count){this.options.tries=count;return this}timeout(seconds){this.options.timeout=seconds;return this}backoff(delays){this.options.backoff=delays;return this}withContext(context){this.options.context=context;return this}withIdempotencyKey(key){this.options.idempotencyKey=key;return this}afterCommit(){this.txMode="after";return this}withoutCommit(){this.txMode="immediate";return this}async dispatch(){const{isFaked,getFakeQueue}=await(testingModule??=import("./testing").catch((error)=>{testingModule=void 0;throw error}));if(isFaked()){getFakeQueue()?.dispatch(this.name,this.payload,this.options);return}if(this.txMode!=="immediate"){if(isInTransaction()){const buffered=this.runDispatchPipeline.bind(this);if(enqueueAfterCommit(async()=>{await buffered()}))return}else if(this.txMode==="after")warnAfterCommitOutsideTransaction()}await this.runDispatchPipeline()}async runDispatchPipeline(){if(this.options.queue===void 0)this.options.queue=(await jobDefaults(this.name)).queue;let claimedKey=!1;if(this.options.idempotencyKey){const claim=await claimDispatchKey(this.options.idempotencyKey,this.name,this.options.queue);if(claim==="duplicate")return;claimedKey=claim==="claimed"}try{if(await isQuarantined(this.name,this.payload)){const envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context);if(await moveToDeadLetter({queue:this.options.queue||"default",payload:serializeEnvelope(envelope),exception:`quarantined: ${this.name}`},"poison-detected"))return}const driver=getQueueDriver();if(driver==="database")await this.dispatchToDatabase();else if(driver==="redis")await this.dispatchToRedis();else if(driver==="sync")await runJob(this.name,{payload:this.payload,context:this.options.context,traceId:await currentTraceId()});else if(driver==="sqs"||driver==="memory"||driver==="beanstalkd")throw Error(`[queue] Driver "${driver}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`);else throw Error(`[queue] Unknown QUEUE_DRIVER "${driver}". Allowed values: redis, database, sync.`)}catch(err){if(claimedKey&&this.options.idempotencyKey)await releaseDispatchKey(this.options.idempotencyKey);throw err}}async dispatchIf(condition){if(condition)await this.dispatch()}async dispatchUnless(condition){if(!condition)await this.dispatch()}async dispatchToDatabase(){const now=Math.floor(Date.now()/1000),availableAt=this.options.delay?now+this.options.delay:now,envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context),payloadJson=serializeEnvelope(envelope),{db}=await(databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=void 0;throw error}));await db.insertInto("jobs").values({queue:this.options.queue||"default",payload:payloadJson,attempts:0,reserved_at:null,available_at:availableAt,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}async dispatchToRedis(){const envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context);assertEnvelopeSerializable(envelope);const{sharedRedisQueue}=await import("./drivers/redis"),{queue:queueConfig}=await import("@stacksjs/config"),redisConfig=queueConfig?.connections?.redis;if(!redisConfig)throw Error("Redis queue connection is not configured. Check config/queue.ts");await sharedRedisQueue(this.options.queue||"default",redisConfig).add(envelope,{delay:this.options.delay,maxTries:this.options.tries,timeout:this.options.timeout,backoff:this.options.backoff})}async dispatchNow(){await runJob(this.name,{payload:this.payload,context:this.options.context})}}export function job(name,payload){return new JobBuilder(name,payload)}export const Jobs={make(name,payload){return new JobBuilder(name,payload)},async dispatch(name,payload){await new JobBuilder(name,payload).dispatch()},async dispatchIf(condition,name,payload){if(condition)await new JobBuilder(name,payload).dispatch()},async dispatchUnless(condition,name,payload){if(!condition)await new JobBuilder(name,payload).dispatch()},async dispatchNow(name,payload){await new JobBuilder(name,payload).dispatchNow()},dispatchAfter(seconds,name,payload){return new JobBuilder(name,payload).delay(seconds)},async dispatchOnce(key,name,payload){await new JobBuilder(name,payload).withIdempotencyKey(key).dispatch()},async dispatchAfterCommit(name,payload){await new JobBuilder(name,payload).afterCommit().dispatch()}};export function jobBatch(jobs){const{PendingBatch}=require("./batch");return new PendingBatch(jobs)}export async function resolveJobFile(name){const files=name.endsWith("Job")?[`${name}.ts`]:[`${name}.ts`,`${name}Job.ts`],candidates=[...files.map((file)=>appPath(`Jobs/${file}`)),...files.map((file)=>frameworkPath(`defaults/app/Jobs/${file}`))];for(const candidate of candidates)if(await Bun.file(candidate).exists())return candidate;let packageRoot;try{const pkgUrl=import.meta.resolve("@stacksjs/defaults/package.json");packageRoot=new URL(".",pkgUrl).pathname}catch{}if(packageRoot)for(const file of files){const packageCandidate=`${packageRoot}app/Jobs/${file}`;if(await Bun.file(packageCandidate).exists())return packageCandidate}const directories=[appPath("Jobs"),frameworkPath("defaults/app/Jobs"),...packageRoot?[`${packageRoot}app/Jobs`]:[]];for(const directory of directories){const declared=(await declaredJobNames(directory)).get(name);if(declared)return declared}return null}const declaredNamesByDirectory=new Map;function declaredJobNames(directory){let index=declaredNamesByDirectory.get(directory);if(!index){index=(async()=>{const byName=new Map,{existsSync}=await import("node:fs");if(!existsSync(directory))return byName;const glob=new Bun.Glob("*.ts");for await(const file of glob.scan({cwd:directory,absolute:!0,onlyFiles:!0})){if(file.endsWith(".d.ts")||file.includes(".test."))continue;const fileName=basename(file,".ts");let declared;try{declared=(await import(file)).default?.name}catch{continue}if(typeof declared!=="string"||declared===""||declared===fileName)continue;const existing=byName.get(declared);if(existing)throw Error(`Jobs ${existing} and ${file} both declare the name "${declared}"; rename one so a dispatch under it has one job to run`);byName.set(declared,file)}return byName})();index.catch(()=>declaredNamesByDirectory.delete(directory));declaredNamesByDirectory.set(directory,index)}return index}export function clearJobNameIndex(){declaredNamesByDirectory.clear()}export async function jobDefaults(name){try{const jobPath=await resolveJobFile(name);if(!jobPath)return{};const definition=(await import(jobPath)).default;if(!definition||typeof definition!=="object")return{};const tries=Number(definition.tries),timeout=Number(definition.timeout),backoff=definition.backoff;return{queue:typeof definition.queue==="string"&&definition.queue.trim()?definition.queue:void 0,tries:Number.isInteger(tries)&&tries>0?tries:void 0,timeout:Number.isFinite(timeout)&&timeout>0?timeout:void 0,backoff:typeof backoff==="number"||Array.isArray(backoff)&&backoff.every((delay)=>typeof delay==="number")?backoff:void 0}}catch{return{}}}export async function runJob(name,options={}){const{withTraceId}=await loadTraceModule(),traceId=options.traceId??`job:${name}:${Math.random().toString(36).slice(2,10)}`;await withTraceId(traceId,async()=>{const jobPath=await resolveJobFile(name);if(!jobPath)throw Error(`Job ${name} not found. Looked in app/Jobs/${name}.ts${name.endsWith("Job")?"":` (and ${name}Job.ts)`} and the framework defaults (storage/framework/defaults/app/Jobs, @stacksjs/defaults).`);const jobConfig=(await import(jobPath)).default;if(!jobConfig)throw Error(`Job ${name} does not export a default`);if(typeof jobConfig.handle==="function")await jobConfig.handle(options.payload,options.context);else if(typeof jobConfig.action==="string")await runNamedAction(jobConfig.action);else if(typeof jobConfig.action==="function")await jobConfig.action();else if(typeof jobConfig==="function")await jobConfig(options.payload,options.context);else throw Error(`Job ${name} does not have a valid handler`)})}async function currentTraceId(){try{const{getTraceId}=await loadTraceModule();return getTraceId()}catch{return}}
1
+ import{resolveQueueDriver}from"./driver";import{basename}from"node:path";import{appPath,frameworkPath}from"@stacksjs/path";import{enqueueAfterCommit,isInTransaction}from"@stacksjs/database/runtime";import{moveToDeadLetter}from"./dead-letter";import{assertEnvelopeSerializable,createEnvelope,serializeEnvelope}from"./envelope";import{claimDispatchKey,releaseDispatchKey}from"./idempotency";import{isQuarantined}from"./poison";import{runNamedAction}from"./action-runner";let testingModule;let databaseModule;let traceModule;function loadTraceModule(){return traceModule??=import("@stacksjs/router").catch((error)=>{traceModule=undefined;throw error})}function getQueueDriver(){return resolveQueueDriver()}let _warnedAfterCommitNoTx=false;function warnAfterCommitOutsideTransaction(){if(_warnedAfterCommitNoTx)return;_warnedAfterCommitNoTx=true;console.warn("[queue] .afterCommit() was called outside of `db.transaction(...)`. Dispatching immediately. Wrap the call in a transaction or drop .afterCommit() to silence this message.")}class JobBuilder{name;payload;options={};txMode="auto";constructor(name,payload){this.name=name;this.payload=payload}onQueue(queue){this.options.queue=queue;return this}delay(seconds){this.options.delay=seconds;return this}tries(count){this.options.tries=count;return this}timeout(seconds){this.options.timeout=seconds;return this}backoff(delays){this.options.backoff=delays;return this}withContext(context){this.options.context=context;return this}withIdempotencyKey(key){this.options.idempotencyKey=key;return this}afterCommit(){this.txMode="after";return this}withoutCommit(){this.txMode="immediate";return this}async dispatch(){const{isFaked,getFakeQueue}=await(testingModule??=import("./testing").catch((error)=>{testingModule=undefined;throw error}));if(isFaked()){getFakeQueue()?.dispatch(this.name,this.payload,this.options);return}if(this.txMode!=="immediate"){const inTx=isInTransaction();if(inTx){const buffered=this.runDispatchPipeline.bind(this);const enqueued=enqueueAfterCommit(async()=>{await buffered()});if(enqueued)return}else if(this.txMode==="after"){warnAfterCommitOutsideTransaction()}}await this.runDispatchPipeline()}async runDispatchPipeline(){if(this.options.queue===undefined)this.options.queue=(await jobDefaults(this.name)).queue;let claimedKey=false;if(this.options.idempotencyKey){const claim=await claimDispatchKey(this.options.idempotencyKey,this.name,this.options.queue);if(claim==="duplicate")return;claimedKey=claim==="claimed"}try{if(await isQuarantined(this.name,this.payload)){const envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context);const moved=await moveToDeadLetter({queue:this.options.queue||"default",payload:serializeEnvelope(envelope),exception:`quarantined: ${this.name}`},"poison-detected");if(moved)return}const driver=getQueueDriver();if(driver==="database"){await this.dispatchToDatabase()}else if(driver==="redis"){await this.dispatchToRedis()}else if(driver==="sync"){await runJob(this.name,{payload:this.payload,context:this.options.context,traceId:await currentTraceId()})}else if(driver==="sqs"||driver==="memory"||driver==="beanstalkd"){throw new Error(`[queue] Driver "${driver}" is not implemented yet. Set QUEUE_DRIVER to one of: redis, database, sync.`)}else{throw new Error(`[queue] Unknown QUEUE_DRIVER "${driver}". Allowed values: redis, database, sync.`)}}catch(err){if(claimedKey&&this.options.idempotencyKey)await releaseDispatchKey(this.options.idempotencyKey);throw err}}async dispatchIf(condition){if(condition){await this.dispatch()}}async dispatchUnless(condition){if(!condition){await this.dispatch()}}async dispatchToDatabase(){const now=Math.floor(Date.now()/1000);const availableAt=this.options.delay?now+this.options.delay:now;const envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context);const payloadJson=serializeEnvelope(envelope);const{db}=await(databaseModule??=import("@stacksjs/database/runtime").catch((error)=>{databaseModule=undefined;throw error}));await db.insertInto("jobs").values({queue:this.options.queue||"default",payload:payloadJson,attempts:0,reserved_at:null,available_at:availableAt,created_at:new Date().toISOString().slice(0,19).replace("T"," ")}).execute()}async dispatchToRedis(){const envelope=createEnvelope(this.name,this.payload,{queue:this.options.queue,timeout:this.options.timeout,tries:this.options.tries,backoff:this.options.backoff},await currentTraceId(),this.options.context);assertEnvelopeSerializable(envelope);const{sharedRedisQueue}=await import("./drivers/redis");const{queue:queueConfig}=await import("@stacksjs/config");const redisConfig=queueConfig?.connections?.redis;if(!redisConfig){throw new Error("Redis queue connection is not configured. Check config/queue.ts")}const queue=sharedRedisQueue(this.options.queue||"default",redisConfig);await queue.add(envelope,{delay:this.options.delay,maxTries:this.options.tries,timeout:this.options.timeout,backoff:this.options.backoff})}async dispatchNow(){await runJob(this.name,{payload:this.payload,context:this.options.context})}}export function job(name,payload){return new JobBuilder(name,payload)}export const Jobs={make(name,payload){return new JobBuilder(name,payload)},async dispatch(name,payload){await new JobBuilder(name,payload).dispatch()},async dispatchIf(condition,name,payload){if(condition)await new JobBuilder(name,payload).dispatch()},async dispatchUnless(condition,name,payload){if(!condition)await new JobBuilder(name,payload).dispatch()},async dispatchNow(name,payload){await new JobBuilder(name,payload).dispatchNow()},dispatchAfter(seconds,name,payload){return new JobBuilder(name,payload).delay(seconds)},async dispatchOnce(key,name,payload){await new JobBuilder(name,payload).withIdempotencyKey(key).dispatch()},async dispatchAfterCommit(name,payload){await new JobBuilder(name,payload).afterCommit().dispatch()}};export function jobBatch(jobs){const{PendingBatch}=require("./batch");return new PendingBatch(jobs)}export async function resolveJobFile(name){const files=name.endsWith("Job")?[`${name}.ts`]:[`${name}.ts`,`${name}Job.ts`];const candidates=[...files.map((file)=>appPath(`Jobs/${file}`)),...files.map((file)=>frameworkPath(`defaults/app/Jobs/${file}`))];for(const candidate of candidates){if(await Bun.file(candidate).exists())return candidate}let packageRoot;try{const pkgUrl=import.meta.resolve("@stacksjs/defaults/package.json");packageRoot=new URL(".",pkgUrl).pathname}catch{}if(packageRoot){for(const file of files){const packageCandidate=`${packageRoot}app/Jobs/${file}`;if(await Bun.file(packageCandidate).exists())return packageCandidate}}const directories=[appPath("Jobs"),frameworkPath("defaults/app/Jobs"),...packageRoot?[`${packageRoot}app/Jobs`]:[]];for(const directory of directories){const declared=(await declaredJobNames(directory)).get(name);if(declared)return declared}return null}const declaredNamesByDirectory=new Map;function declaredJobNames(directory){let index=declaredNamesByDirectory.get(directory);if(!index){index=(async()=>{const byName=new Map;const{existsSync}=await import("node:fs");if(!existsSync(directory))return byName;const glob=new Bun.Glob("*.ts");for await(const file of glob.scan({cwd:directory,absolute:true,onlyFiles:true})){if(file.endsWith(".d.ts")||file.includes(".test."))continue;const fileName=basename(file,".ts");let declared;try{declared=(await import(file)).default?.name}catch{continue}if(typeof declared!=="string"||declared===""||declared===fileName)continue;const existing=byName.get(declared);if(existing)throw new Error(`Jobs ${existing} and ${file} both declare the name "${declared}"; rename one so a dispatch under it has one job to run`);byName.set(declared,file)}return byName})();index.catch(()=>declaredNamesByDirectory.delete(directory));declaredNamesByDirectory.set(directory,index)}return index}export function clearJobNameIndex(){declaredNamesByDirectory.clear()}export async function jobDefaults(name){try{const jobPath=await resolveJobFile(name);if(!jobPath)return{};const definition=(await import(jobPath)).default;if(!definition||typeof definition!=="object")return{};const tries=Number(definition.tries);const timeout=Number(definition.timeout);const backoff=definition.backoff;return{queue:typeof definition.queue==="string"&&definition.queue.trim()?definition.queue:undefined,tries:Number.isInteger(tries)&&tries>0?tries:undefined,timeout:Number.isFinite(timeout)&&timeout>0?timeout:undefined,backoff:typeof backoff==="number"||Array.isArray(backoff)&&backoff.every((delay)=>typeof delay==="number")?backoff:undefined}}catch{return{}}}export async function runJob(name,options={}){const{withTraceId}=await loadTraceModule();const traceId=options.traceId??`job:${name}:${Math.random().toString(36).slice(2,10)}`;await withTraceId(traceId,async()=>{const jobPath=await resolveJobFile(name);if(!jobPath){throw new Error(`Job ${name} not found. Looked in app/Jobs/${name}.ts${name.endsWith("Job")?"":` (and ${name}Job.ts)`} and the framework defaults (storage/framework/defaults/app/Jobs, @stacksjs/defaults).`)}const jobModule=await import(jobPath);const jobConfig=jobModule.default;if(!jobConfig){throw new Error(`Job ${name} does not export a default`)}if(typeof jobConfig.handle==="function"){await jobConfig.handle(options.payload,options.context)}else if(typeof jobConfig.action==="string"){await runNamedAction(jobConfig.action)}else if(typeof jobConfig.action==="function"){await jobConfig.action()}else if(typeof jobConfig==="function"){await jobConfig(options.payload,options.context)}else{throw new Error(`Job ${name} does not have a valid handler`)}})}async function currentTraceId(){try{const{getTraceId}=await loadTraceModule();return getTraceId()}catch{return}}
@@ -1 +1 @@
1
- const PG_UNDEFINED_TABLE="42P01",MYSQL_NO_SUCH_TABLE=1146;export function isMissingTableError(err){const e=err,errno=e?.errno;if(typeof errno==="string"&&errno.toUpperCase()===PG_UNDEFINED_TABLE)return!0;if(typeof errno==="number"&&errno===MYSQL_NO_SUCH_TABLE)return!0;if((typeof e?.code==="string"?e.code.toUpperCase():"")===PG_UNDEFINED_TABLE)return!0;const msg=e?.message??"";return msg.includes("no such table")||msg.includes("doesn't exist")||msg.includes("does not exist")}
1
+ const PG_UNDEFINED_TABLE="42P01";const MYSQL_NO_SUCH_TABLE=1146;export function isMissingTableError(err){const e=err;const errno=e?.errno;if(typeof errno==="string"&&errno.toUpperCase()===PG_UNDEFINED_TABLE)return true;if(typeof errno==="number"&&errno===MYSQL_NO_SUCH_TABLE)return true;const code=typeof e?.code==="string"?e.code.toUpperCase():"";if(code===PG_UNDEFINED_TABLE)return true;const msg=e?.message??"";return msg.includes("no such table")||msg.includes("doesn't exist")||msg.includes("does not exist")}
@@ -1,4 +1,4 @@
1
- import{log}from"@stacksjs/logging";const HTML_ESCAPE_MAP={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHtml(value){return String(value).replace(/[&<>"']/g,(c)=>HTML_ESCAPE_MAP[c]??c)}export class FailedJobNotifier{config;notificationCount=0;lastResetTime=Date.now();pendingBatch=[];batchTimeout=null;activeFlush=null;constructor(config){this.config=config}async notify(job){if(this.config.filter&&!this.config.filter(job))return;if(this.config.rateLimit){const now=Date.now();if(now-this.lastResetTime>3600000){this.notificationCount=0;this.lastResetTime=now}if(this.notificationCount>=this.config.rateLimit){log.debug("Rate limit reached for failed job notifications");return}}if(this.config.batch){this.pendingBatch.push(job);if(!this.batchTimeout){this.batchTimeout=setTimeout(()=>{this.batchTimeout=null;this.activeFlush=this.flushBatch().catch((error)=>log.error("Failed to flush notification batch:",error)).finally(()=>{this.activeFlush=null})},this.config.batchInterval||60000);this.batchTimeout.unref?.()}return}await this.sendNotifications([job])}async flushBatch(){if(this.pendingBatch.length===0)return;const batch=[...this.pendingBatch];this.pendingBatch=[];if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}await this.sendNotifications(batch)}async shutdown(){if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}if(this.activeFlush)await this.activeFlush.catch(()=>{});await this.flushBatch().catch((error)=>log.error("Failed to flush notification batch on shutdown:",error))}async sendNotifications(jobs){const promises=[];for(const channel of this.config.channels)switch(channel){case"email":if(this.config.email)promises.push(this.sendEmail(jobs));break;case"slack":if(this.config.slack)promises.push(this.sendSlack(jobs));break;case"discord":if(this.config.discord)promises.push(this.sendDiscord(jobs));break;case"webhook":if(this.config.webhook)promises.push(this.sendWebhook(jobs));break;case"log":this.logFailures(jobs);break}try{await Promise.all(promises)}catch(error){log.error("Failed to send job failure notifications:",error)}finally{this.notificationCount+=jobs.length}}async sendEmail(jobs){const config=this.config.email,subject=config.subject||`[Queue] ${jobs.length} Job(s) Failed`,body=this.formatEmailBody(jobs);try{const{mail}=await import("@stacksjs/email");await mail.sendOrFail({to:Array.isArray(config.to)?config.to:[config.to],from:config.from?{address:config.from}:void 0,subject,html:body})}catch(error){log.error("Failed to send email notification:",error)}}formatEmailBody(jobs){const rows=jobs.map((job)=>`
1
+ import{log}from"@stacksjs/logging";const HTML_ESCAPE_MAP={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHtml(value){return String(value).replace(/[&<>"']/g,(c)=>HTML_ESCAPE_MAP[c]??c)}export class FailedJobNotifier{config;notificationCount=0;lastResetTime=Date.now();pendingBatch=[];batchTimeout=null;activeFlush=null;constructor(config){this.config=config}async notify(job){if(this.config.filter&&!this.config.filter(job)){return}if(this.config.rateLimit){const now=Date.now();if(now-this.lastResetTime>3600000){this.notificationCount=0;this.lastResetTime=now}if(this.notificationCount>=this.config.rateLimit){log.debug("Rate limit reached for failed job notifications");return}}if(this.config.batch){this.pendingBatch.push(job);if(!this.batchTimeout){this.batchTimeout=setTimeout(()=>{this.batchTimeout=null;this.activeFlush=this.flushBatch().catch((error)=>log.error("Failed to flush notification batch:",error)).finally(()=>{this.activeFlush=null})},this.config.batchInterval||60000);this.batchTimeout.unref?.()}return}await this.sendNotifications([job])}async flushBatch(){if(this.pendingBatch.length===0)return;const batch=[...this.pendingBatch];this.pendingBatch=[];if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}await this.sendNotifications(batch)}async shutdown(){if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}if(this.activeFlush){await this.activeFlush.catch(()=>{})}await this.flushBatch().catch((error)=>log.error("Failed to flush notification batch on shutdown:",error))}async sendNotifications(jobs){const promises=[];for(const channel of this.config.channels){switch(channel){case"email":if(this.config.email){promises.push(this.sendEmail(jobs))}break;case"slack":if(this.config.slack){promises.push(this.sendSlack(jobs))}break;case"discord":if(this.config.discord){promises.push(this.sendDiscord(jobs))}break;case"webhook":if(this.config.webhook){promises.push(this.sendWebhook(jobs))}break;case"log":this.logFailures(jobs);break}}try{await Promise.all(promises)}catch(error){log.error("Failed to send job failure notifications:",error)}finally{this.notificationCount+=jobs.length}}async sendEmail(jobs){const config=this.config.email;const subject=config.subject||`[Queue] ${jobs.length} Job(s) Failed`;const body=this.formatEmailBody(jobs);try{const{mail}=await import("@stacksjs/email");await mail.sendOrFail({to:Array.isArray(config.to)?config.to:[config.to],from:config.from?{address:config.from}:undefined,subject,html:body})}catch(error){log.error("Failed to send email notification:",error)}}formatEmailBody(jobs){const rows=jobs.map((job)=>`
2
2
  <tr>
3
3
  <td style="padding: 8px; border: 1px solid #ddd;">${escapeHtml(String(job.id))}</td>
4
4
  <td style="padding: 8px; border: 1px solid #ddd;">${escapeHtml(job.name)}</td>
@@ -25,6 +25,6 @@ import{log}from"@stacksjs/logging";const HTML_ESCAPE_MAP={"&":"&amp;","<":"&lt;"
25
25
  ${rows}
26
26
  </tbody>
27
27
  </table>
28
- `}async sendSlack(jobs){const config=this.config.slack,blocks=[{type:"header",text:{type:"plain_text",text:`\uD83D\uDEA8 ${jobs.length} Job(s) Failed`,emoji:!0}},...jobs.slice(0,10).map((job)=>({type:"section",text:{type:"mrkdwn",text:`*${job.name}*
28
+ `}async sendSlack(jobs){const config=this.config.slack;const blocks=[{type:"header",text:{type:"plain_text",text:`\uD83D\uDEA8 ${jobs.length} Job(s) Failed`,emoji:true}},...jobs.slice(0,10).map((job)=>({type:"section",text:{type:"mrkdwn",text:`*${job.name}*
29
29
  Queue: ${job.queue} | Attempts: ${job.attempts}/${job.maxAttempts}
30
- \`\`\`${job.exception.slice(0,200)}\`\`\``}}))];if(jobs.length>10)blocks.push({type:"section",text:{type:"mrkdwn",text:`_...and ${jobs.length-10} more failed jobs_`}});try{const response=await fetch(config.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:config.channel,username:config.username||"Queue Monitor",icon_emoji:config.iconEmoji||":warning:",blocks})});if(!response.ok)log.error(`Slack notification failed with status ${response.status}`)}catch(error){log.error("Failed to send Slack notification:",error)}}async sendDiscord(jobs){const config=this.config.discord,embeds=jobs.slice(0,10).map((job)=>({title:`\u274C ${job.name}`,color:15158332,fields:[{name:"Queue",value:job.queue,inline:!0},{name:"Attempts",value:`${job.attempts}/${job.maxAttempts}`,inline:!0},{name:"Failed At",value:job.failedAt.toISOString(),inline:!0},{name:"Exception",value:`\`\`\`${job.exception.slice(0,500)}\`\`\``}],timestamp:job.failedAt.toISOString()}));try{const response=await fetch(config.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:config.username||"Queue Monitor",avatar_url:config.avatarUrl,content:`\uD83D\uDEA8 **${jobs.length} Job(s) Failed**`,embeds})});if(!response.ok)log.error(`Discord notification failed with status ${response.status}`)}catch(error){log.error("Failed to send Discord notification:",error)}}async sendWebhook(jobs){const config=this.config.webhook,payload={event:"jobs.failed",timestamp:new Date().toISOString(),count:jobs.length,jobs:jobs.map((job)=>({id:job.id,name:job.name,queue:job.queue,attempts:job.attempts,maxAttempts:job.maxAttempts,exception:job.exception,failedAt:job.failedAt.toISOString()}))},headers={"Content-Type":"application/json",...config.headers};if(config.secret){const body=JSON.stringify(payload),signature=await this.generateSignature(body,config.secret);headers["X-Signature"]=signature}try{const response=await fetch(config.url,{method:"POST",headers,body:JSON.stringify(payload)});if(!response.ok)log.error(`Webhook notification failed with status ${response.status}`)}catch(error){log.error("Failed to send webhook notification:",error)}}async generateSignature(payload,secret){const encoder=new TextEncoder,key=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),signature=await crypto.subtle.sign("HMAC",key,encoder.encode(payload));return Array.from(new Uint8Array(signature)).map((b)=>b.toString(16).padStart(2,"0")).join("")}logFailures(jobs){for(const job of jobs)log.error(`[Queue] Job "${job.name}" failed on queue "${job.queue}" after ${job.attempts} attempts: ${job.exception}`)}async cleanup(){if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}if(this.pendingBatch.length>0)await this.flushBatch()}}let globalNotifier=null;export function configureFailedJobNotifications(config){globalNotifier=new FailedJobNotifier(config);return globalNotifier}export function getFailedJobNotifier(){return globalNotifier}export async function notifyJobFailed(job){if(globalNotifier)await globalNotifier.notify(job)}
30
+ \`\`\`${job.exception.slice(0,200)}\`\`\``}}))];if(jobs.length>10){blocks.push({type:"section",text:{type:"mrkdwn",text:`_...and ${jobs.length-10} more failed jobs_`}})}try{const response=await fetch(config.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:config.channel,username:config.username||"Queue Monitor",icon_emoji:config.iconEmoji||":warning:",blocks})});if(!response.ok){log.error(`Slack notification failed with status ${response.status}`)}}catch(error){log.error("Failed to send Slack notification:",error)}}async sendDiscord(jobs){const config=this.config.discord;const embeds=jobs.slice(0,10).map((job)=>({title:`❌ ${job.name}`,color:15158332,fields:[{name:"Queue",value:job.queue,inline:true},{name:"Attempts",value:`${job.attempts}/${job.maxAttempts}`,inline:true},{name:"Failed At",value:job.failedAt.toISOString(),inline:true},{name:"Exception",value:`\`\`\`${job.exception.slice(0,500)}\`\`\``}],timestamp:job.failedAt.toISOString()}));try{const response=await fetch(config.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:config.username||"Queue Monitor",avatar_url:config.avatarUrl,content:`\uD83D\uDEA8 **${jobs.length} Job(s) Failed**`,embeds})});if(!response.ok){log.error(`Discord notification failed with status ${response.status}`)}}catch(error){log.error("Failed to send Discord notification:",error)}}async sendWebhook(jobs){const config=this.config.webhook;const payload={event:"jobs.failed",timestamp:new Date().toISOString(),count:jobs.length,jobs:jobs.map((job)=>({id:job.id,name:job.name,queue:job.queue,attempts:job.attempts,maxAttempts:job.maxAttempts,exception:job.exception,failedAt:job.failedAt.toISOString()}))};const headers={"Content-Type":"application/json",...config.headers};if(config.secret){const body=JSON.stringify(payload);const signature=await this.generateSignature(body,config.secret);headers["X-Signature"]=signature}try{const response=await fetch(config.url,{method:"POST",headers,body:JSON.stringify(payload)});if(!response.ok){log.error(`Webhook notification failed with status ${response.status}`)}}catch(error){log.error("Failed to send webhook notification:",error)}}async generateSignature(payload,secret){const encoder=new TextEncoder;const key=await crypto.subtle.importKey("raw",encoder.encode(secret),{name:"HMAC",hash:"SHA-256"},false,["sign"]);const signature=await crypto.subtle.sign("HMAC",key,encoder.encode(payload));return Array.from(new Uint8Array(signature)).map((b)=>b.toString(16).padStart(2,"0")).join("")}logFailures(jobs){for(const job of jobs){log.error(`[Queue] Job "${job.name}" failed on queue "${job.queue}" after ${job.attempts} attempts: ${job.exception}`)}}async cleanup(){if(this.batchTimeout){clearTimeout(this.batchTimeout);this.batchTimeout=null}if(this.pendingBatch.length>0){await this.flushBatch()}}}let globalNotifier=null;export function configureFailedJobNotifications(config){globalNotifier=new FailedJobNotifier(config);return globalNotifier}export function getFailedJobNotifier(){return globalNotifier}export async function notifyJobFailed(job){if(globalNotifier){await globalNotifier.notify(job)}}
package/dist/poison.js CHANGED
@@ -1 +1 @@
1
- import{hash}from"node:crypto";import{db,lockRow,sqliteWriteOptions,parseSqlDateTime}from"@stacksjs/database/runtime";import{seedStateRow}from"./state-row";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;console.warn("[queue/poison] job_quarantine table missing - poison detection disabled. Run migrations to enable.")}function serializePayload(payload){try{return typeof payload==="string"?payload:JSON.stringify(payload??null)}catch{return String(payload)}}export function hashPayload(payload){return hash("sha256",serializePayload(payload),"hex").slice(0,32)}function canonicalJson(value){if(Array.isArray(value))return value.map(canonicalJson);if(value&&typeof value==="object"){const record=value;return Object.fromEntries(Object.keys(record).sort().map((key)=>[key,canonicalJson(record[key])]))}return value}function payloadKeys(payload){const serialized=serializePayload(payload),legacy=hash("sha256",serialized,"hex").slice(0,32);let value=serialized;if(typeof payload!=="string")try{value=JSON.parse(serialized)}catch{}return{current:`v2:${hash("sha256",JSON.stringify([typeof payload,canonicalJson(value)]),"hex").slice(0,32)}`,legacy}}async function payloadState(tx,jobName,keys,now,windowMs){await seedStateRow(tx,"job_quarantine",["job_name","payload_hash"],{job_name:jobName,payload_hash:keys.current,failure_count:0,window_start:now,quarantined_at:null});const current=await lockRow(tx,"job_quarantine",{job_name:jobName,payload_hash:keys.current});if(!current)throw Error("Poison state disappeared while locked");if(keys.legacy===keys.current)return current;const legacy=await lockRow(tx,"job_quarantine",{job_name:jobName,payload_hash:keys.legacy});if(!legacy)return current;const cutoff=Date.now()-windowMs,active=[current,legacy].filter((row)=>(parseSqlDateTime(row.window_start)?.getTime()??0)>=cutoff),first=active.map((row)=>parseSqlDateTime(row.window_start).getTime()),merged={failure_count:active.reduce((total,row)=>total+Number(row.failure_count),0),window_start:first.length?new Date(Math.min(...first)).toISOString():now,quarantined_at:current.quarantined_at??legacy.quarantined_at};await tx.updateTable("job_quarantine").set(merged).where("id","=",Number(current.id)).execute();await tx.deleteFrom("job_quarantine").where("id","=",Number(legacy.id)).execute();return{...current,...merged}}export async function recordFailureForPoison(jobName,payload,config={}){const maxFailures=config.maxFailures??5,windowMinutes=config.windowMinutes??60,keys=payloadKeys(payload),now=new Date,nowStr=now.toISOString().slice(0,19).replace("T"," ");try{return await db.transaction(async(tx)=>{const row=await payloadState(tx,jobName,keys,nowStr,windowMinutes*60000);if(row.quarantined_at)return!0;const start=parseSqlDateTime(row.window_start)?.getTime(),reset=start===void 0||now.getTime()-start>=windowMinutes*60000,count=(reset?0:Number(row.failure_count))+1,quarantined=count>=maxFailures;await tx.updateTable("job_quarantine").set({failure_count:count,window_start:reset?nowStr:row.window_start,quarantined_at:quarantined?nowStr:null}).where("id","=",Number(row.id)).execute();return quarantined},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function isQuarantined(jobName,payload){const keys=payloadKeys(payload);try{const row=await db.selectFrom("job_quarantine").where("job_name","=",jobName).where("payload_hash","in",[keys.current,keys.legacy,"*"]).whereNotNull("quarantined_at").select(["id","payload_hash"]).executeTakeFirst();if(row?.payload_hash===keys.legacy)await db.transaction((tx)=>payloadState(tx,jobName,keys,new Date().toISOString(),3600000),sqliteWriteOptions());return Boolean(row)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return!1}throw err}}export async function quarantineJob(jobName,payload){const keys=payload===void 0?{current:"*",legacy:"*"}:payloadKeys(payload),nowStr=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.transaction(async(tx)=>{const row=await payloadState(tx,jobName,keys,nowStr,3600000);await tx.updateTable("job_quarantine").set({quarantined_at:nowStr}).where("id","=",Number(row.id)).execute()},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}throw err}}export async function unquarantineJob(jobName){try{await db.deleteFrom("job_quarantine").where("job_name","=",jobName).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}throw err}}export async function listQuarantined(){try{return await db.selectFrom("job_quarantine").whereNotNull("quarantined_at").selectAll().execute()??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}
1
+ import{hash}from"node:crypto";import{db,lockRow,sqliteWriteOptions,parseSqlDateTime}from"@stacksjs/database/runtime";import{seedStateRow}from"./state-row";import{isMissingTableError}from"./missing-table";let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;console.warn("[queue/poison] job_quarantine table missing - poison detection disabled. "+"Run migrations to enable.")}function serializePayload(payload){try{return typeof payload==="string"?payload:JSON.stringify(payload??null)}catch{return String(payload)}}export function hashPayload(payload){return hash("sha256",serializePayload(payload),"hex").slice(0,32)}function canonicalJson(value){if(Array.isArray(value))return value.map(canonicalJson);if(value&&typeof value==="object"){const record=value;return Object.fromEntries(Object.keys(record).sort().map((key)=>[key,canonicalJson(record[key])]))}return value}function payloadKeys(payload){const serialized=serializePayload(payload);const legacy=hash("sha256",serialized,"hex").slice(0,32);let value=serialized;if(typeof payload!=="string"){try{value=JSON.parse(serialized)}catch{}}return{current:`v2:${hash("sha256",JSON.stringify([typeof payload,canonicalJson(value)]),"hex").slice(0,32)}`,legacy}}async function payloadState(tx,jobName,keys,now,windowMs){await seedStateRow(tx,"job_quarantine",["job_name","payload_hash"],{job_name:jobName,payload_hash:keys.current,failure_count:0,window_start:now,quarantined_at:null});const current=await lockRow(tx,"job_quarantine",{job_name:jobName,payload_hash:keys.current});if(!current)throw new Error("Poison state disappeared while locked");if(keys.legacy===keys.current)return current;const legacy=await lockRow(tx,"job_quarantine",{job_name:jobName,payload_hash:keys.legacy});if(!legacy)return current;const cutoff=Date.now()-windowMs;const active=[current,legacy].filter((row)=>(parseSqlDateTime(row.window_start)?.getTime()??0)>=cutoff);const first=active.map((row)=>parseSqlDateTime(row.window_start).getTime());const merged={failure_count:active.reduce((total,row)=>total+Number(row.failure_count),0),window_start:first.length?new Date(Math.min(...first)).toISOString():now,quarantined_at:current.quarantined_at??legacy.quarantined_at};await tx.updateTable("job_quarantine").set(merged).where("id","=",Number(current.id)).execute();await tx.deleteFrom("job_quarantine").where("id","=",Number(legacy.id)).execute();return{...current,...merged}}export async function recordFailureForPoison(jobName,payload,config={}){const maxFailures=config.maxFailures??5;const windowMinutes=config.windowMinutes??60;const keys=payloadKeys(payload);const now=new Date;const nowStr=now.toISOString().slice(0,19).replace("T"," ");try{return await db.transaction(async(tx)=>{const row=await payloadState(tx,jobName,keys,nowStr,windowMinutes*60000);if(row.quarantined_at)return true;const start=parseSqlDateTime(row.window_start)?.getTime();const reset=start===undefined||now.getTime()-start>=windowMinutes*60000;const count=(reset?0:Number(row.failure_count))+1;const quarantined=count>=maxFailures;await tx.updateTable("job_quarantine").set({failure_count:count,window_start:reset?nowStr:row.window_start,quarantined_at:quarantined?nowStr:null}).where("id","=",Number(row.id)).execute();return quarantined},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return false}throw err}}export async function isQuarantined(jobName,payload){const keys=payloadKeys(payload);try{const row=await db.selectFrom("job_quarantine").where("job_name","=",jobName).where("payload_hash","in",[keys.current,keys.legacy,"*"]).whereNotNull("quarantined_at").select(["id","payload_hash"]).executeTakeFirst();if(row?.payload_hash===keys.legacy){await db.transaction((tx)=>payloadState(tx,jobName,keys,new Date().toISOString(),60*60000),sqliteWriteOptions())}return Boolean(row)}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return false}throw err}}export async function quarantineJob(jobName,payload){const keys=payload===undefined?{current:"*",legacy:"*"}:payloadKeys(payload);const nowStr=new Date().toISOString().slice(0,19).replace("T"," ");try{await db.transaction(async(tx)=>{const row=await payloadState(tx,jobName,keys,nowStr,60*60000);await tx.updateTable("job_quarantine").set({quarantined_at:nowStr}).where("id","=",Number(row.id)).execute()},sqliteWriteOptions())}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}throw err}}export async function unquarantineJob(jobName){try{await db.deleteFrom("job_quarantine").where("job_name","=",jobName).execute()}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return}throw err}}export async function listQuarantined(){try{const rows=await db.selectFrom("job_quarantine").whereNotNull("quarantined_at").selectAll().execute();return rows??[]}catch(err){if(isMissingTableError(err)){warnOnceAboutMissingTable();return[]}throw err}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{readFileSync,readlinkSync}from"node:fs";import{hostname}from"node:os";import process from"node:process";function machine(){if(process.platform!=="linux")return;try{const id=readFileSync("/etc/machine-id","utf8").trim(),boot=readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim(),namespace=readlinkSync("/proc/self/ns/pid");if(!id||!boot)return;return{host:createHash("sha256").update(`${hostname()}\x00${id}`).digest("hex"),boot,namespace}}catch{return}}function birth(pid){const stat=readFileSync(`/proc/${pid}/stat`,"utf8"),value=stat.slice(stat.lastIndexOf(")")+2).split(/\s+/)[19];if(!value||!/^\d+$/.test(value))throw Error("Process birth identity unavailable");return value}export function captureProcessLeaseOwner(pid=process.pid){if(!Number.isSafeInteger(pid)||pid<1)return;const local=machine();if(!local)return;try{return{...local,pid,birth:birth(pid)}}catch{return}}export function processLeaseOwnerStatus(value){if(!value||typeof value!=="object")return"unknown";const owner=value;if(typeof owner.host!=="string"||typeof owner.boot!=="string"||typeof owner.birth!=="string"||typeof owner.namespace!=="string"||!/^pid:\[\d+\]$/.test(owner.namespace)||!/^\d+$/.test(owner.birth)||!Number.isSafeInteger(owner.pid)||Number(owner.pid)<1)return"unknown";const local=machine();if(!local||local.host!==owner.host)return"unknown";if(local.boot!==owner.boot)return"dead";if(local.namespace!==owner.namespace)return"unknown";try{return birth(owner.pid)===owner.birth?"alive":"dead"}catch(error){return error.code==="ENOENT"?"dead":"unknown"}}
1
+ import{createHash}from"node:crypto";import{readFileSync,readlinkSync}from"node:fs";import{hostname}from"node:os";import process from"node:process";function machine(){if(process.platform!=="linux")return;try{const id=readFileSync("/etc/machine-id","utf8").trim();const boot=readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim();const namespace=readlinkSync("/proc/self/ns/pid");if(!id||!boot)return;return{host:createHash("sha256").update(`${hostname()}\x00${id}`).digest("hex"),boot,namespace}}catch{return}}function birth(pid){const stat=readFileSync(`/proc/${pid}/stat`,"utf8");const value=stat.slice(stat.lastIndexOf(")")+2).split(/\s+/)[19];if(!value||!/^\d+$/.test(value))throw new Error("Process birth identity unavailable");return value}export function captureProcessLeaseOwner(pid=process.pid){if(!Number.isSafeInteger(pid)||pid<1)return;const local=machine();if(!local)return;try{return{...local,pid,birth:birth(pid)}}catch{return}}export function processLeaseOwnerStatus(value){if(!value||typeof value!=="object")return"unknown";const owner=value;if(typeof owner.host!=="string"||typeof owner.boot!=="string"||typeof owner.birth!=="string"||typeof owner.namespace!=="string"||!/^pid:\[\d+\]$/.test(owner.namespace)||!/^\d+$/.test(owner.birth)||!Number.isSafeInteger(owner.pid)||Number(owner.pid)<1)return"unknown";const local=machine();if(!local||local.host!==owner.host)return"unknown";if(local.boot!==owner.boot)return"dead";if(local.namespace!==owner.namespace)return"unknown";try{return birth(owner.pid)===owner.birth?"alive":"dead"}catch(error){return error.code==="ENOENT"?"dead":"unknown"}}
@@ -1 +1 @@
1
- import{sqliteWriteOptions}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";import{buildScheduledJobRow,storeJob}from"./utils";import{seedStateRow}from"./state-row";let ensured=!1;async function ensureTable(){if(ensured)return!0;try{const{db}=await import("@stacksjs/database/runtime");await db.unsafe("CREATE TABLE IF NOT EXISTS scheduled_job_runs (job_name VARCHAR(255) PRIMARY KEY, last_run_at VARCHAR(64) NOT NULL)").execute();ensured=!0;return!0}catch(err){log.debug(`[scheduler] run-marker persistence unavailable, using in-memory lastRun: ${err instanceof Error?err.message:String(err)}`);return!1}}export async function loadPersistedLastRun(jobName){if(!await ensureTable())return null;try{const{db}=await import("@stacksjs/database/runtime"),row=await db.selectFrom("scheduled_job_runs").where("job_name","=",jobName).select(["last_run_at"]).executeTakeFirst();if(!row?.last_run_at)return null;const d=new Date(row.last_run_at);return Number.isNaN(d.getTime())?null:d}catch{return null}}export async function persistLastRun(jobName,when){if(!await ensureTable())return;try{const{db}=await import("@stacksjs/database/runtime");await db.transaction(async(tx)=>{await seedStateRow(tx,"scheduled_job_runs",["job_name"],{job_name:jobName,last_run_at:when.toISOString()});await tx.updateTable("scheduled_job_runs").set({last_run_at:when.toISOString()}).where("job_name","=",jobName).execute()},sqliteWriteOptions())}catch{}}export async function storeScheduledRun(jobName,when,options){if(!await ensureTable()){await storeJob(jobName,options);return!0}const row=buildScheduledJobRow(jobName,options),{db,lockRow}=await import("@stacksjs/database/runtime");return db.transaction(async(tx)=>{await seedStateRow(tx,"scheduled_job_runs",["job_name"],{job_name:jobName,last_run_at:""});const previous=await lockRow(tx,"scheduled_job_runs",{job_name:jobName});if(previous&&Math.floor(new Date(String(previous.last_run_at)).getTime()/60000)===Math.floor(when.getTime()/60000))return!1;await tx.insertInto("jobs").values({...row}).execute();await tx.updateTable("scheduled_job_runs").set({last_run_at:when.toISOString()}).where("job_name","=",jobName).execute();return!0},sqliteWriteOptions())}export function overlapPayloadPattern(jobName){return`%"jobName":"${jobName.replace(/[\\%_]/g,(character)=>`\\${character}`)}"%`}export async function hasUnfinishedRun(jobName){try{const{db,getDatabaseDialect,sqlHelpers}=await import("@stacksjs/database/runtime"),{param}=sqlHelpers(getDatabaseDialect()),raw=await db.unsafe(`SELECT 1 AS present FROM jobs WHERE payload LIKE ${param(1)} ESCAPE '\\' LIMIT 1`,[overlapPayloadPattern(jobName)]).execute(),list=Array.isArray(raw)?raw:raw?.rows??[];return Array.isArray(list)&&list.length>0}catch(err){log.debug(`[scheduler] overlap check unavailable, dispatching anyway: ${err instanceof Error?err.message:String(err)}`);return!1}}export function __resetSchedulerPersistenceForTests(){ensured=!1}
1
+ import{sqliteWriteOptions}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";import{buildScheduledJobRow,storeJob}from"./utils";import{seedStateRow}from"./state-row";let ensured=false;async function ensureTable(){if(ensured)return true;try{const{db}=await import("@stacksjs/database/runtime");await db.unsafe("CREATE TABLE IF NOT EXISTS scheduled_job_runs (job_name VARCHAR(255) PRIMARY KEY, last_run_at VARCHAR(64) NOT NULL)").execute();ensured=true;return true}catch(err){log.debug(`[scheduler] run-marker persistence unavailable, using in-memory lastRun: ${err instanceof Error?err.message:String(err)}`);return false}}export async function loadPersistedLastRun(jobName){if(!await ensureTable())return null;try{const{db}=await import("@stacksjs/database/runtime");const row=await db.selectFrom("scheduled_job_runs").where("job_name","=",jobName).select(["last_run_at"]).executeTakeFirst();if(!row?.last_run_at)return null;const d=new Date(row.last_run_at);return Number.isNaN(d.getTime())?null:d}catch{return null}}export async function persistLastRun(jobName,when){if(!await ensureTable())return;try{const{db}=await import("@stacksjs/database/runtime");await db.transaction(async(tx)=>{await seedStateRow(tx,"scheduled_job_runs",["job_name"],{job_name:jobName,last_run_at:when.toISOString()});await tx.updateTable("scheduled_job_runs").set({last_run_at:when.toISOString()}).where("job_name","=",jobName).execute()},sqliteWriteOptions())}catch{}}export async function storeScheduledRun(jobName,when,options){if(!await ensureTable()){await storeJob(jobName,options);return true}const row=buildScheduledJobRow(jobName,options);const{db,lockRow}=await import("@stacksjs/database/runtime");return db.transaction(async(tx)=>{await seedStateRow(tx,"scheduled_job_runs",["job_name"],{job_name:jobName,last_run_at:""});const previous=await lockRow(tx,"scheduled_job_runs",{job_name:jobName});if(previous&&Math.floor(new Date(String(previous.last_run_at)).getTime()/60000)===Math.floor(when.getTime()/60000))return false;await tx.insertInto("jobs").values({...row}).execute();await tx.updateTable("scheduled_job_runs").set({last_run_at:when.toISOString()}).where("job_name","=",jobName).execute();return true},sqliteWriteOptions())}export function overlapPayloadPattern(jobName){const escaped=jobName.replace(/[\\%_]/g,(character)=>`\\${character}`);return`%"jobName":"${escaped}"%`}export async function hasUnfinishedRun(jobName){try{const{db,getDatabaseDialect,sqlHelpers}=await import("@stacksjs/database/runtime");const{param}=sqlHelpers(getDatabaseDialect());const rows=await db.unsafe(`SELECT 1 AS present FROM jobs WHERE payload LIKE ${param(1)} ESCAPE '\\' LIMIT 1`,[overlapPayloadPattern(jobName)]).execute();const raw=rows;const list=Array.isArray(raw)?raw:raw?.rows??[];return Array.isArray(list)&&list.length>0}catch(err){log.debug(`[scheduler] overlap check unavailable, dispatching anyway: ${err instanceof Error?err.message:String(err)}`);return false}}export function __resetSchedulerPersistenceForTests(){ensured=false}
package/dist/scheduler.js CHANGED
@@ -1 +1 @@
1
- import{parseCron}from"@stacksjs/cron";import{log}from"@stacksjs/logging";import{discoverJobs,getScheduledJobs}from"./discovery";import{emitQueueEvent}from"./events";import{hasUnfinishedRun,loadPersistedLastRun,storeScheduledRun}from"./scheduler-persistence";import{storeJob}from"./utils";const DEFAULT_CONFIG={checkInterval:60000,preventOverlapping:!0},schedulerState={isRunning:!1,isShuttingDown:!1,checkInterval:null,jobs:new Map,config:{...DEFAULT_CONFIG}};let warnedBadTimezone=!1;const tzFormatterCache=new Map;function tzFormatter(timeZone){let f=tzFormatterCache.get(timeZone);if(!f){f=new Intl.DateTimeFormat("en-US",{timeZone,hour12:!1,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short"});tzFormatterCache.set(timeZone,f)}return f}export function getCronParts(date,timeZone){if(timeZone&&timeZone!=="local"&&timeZone!=="system")try{const parts=tzFormatter(timeZone).formatToParts(date),get=(t)=>parts.find((p)=>p.type===t)?.value??"",weekday={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};let hour=Number(get("hour"));if(hour===24)hour=0;return{minute:Number(get("minute")),hour,day:Number(get("day")),month:Number(get("month")),dayOfWeek:weekday[get("weekday")]??date.getDay()}}catch{if(!warnedBadTimezone){warnedBadTimezone=!0;log.warn(`[scheduler] Invalid timezone "${timeZone}"; falling back to system local time.`)}}return{minute:date.getMinutes(),hour:date.getHours(),day:date.getDate(),month:date.getMonth()+1,dayOfWeek:date.getDay()}}function cronTimeZone(timeZone){const system=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!timeZone||timeZone==="local"||timeZone==="system")return system;try{new Intl.DateTimeFormat("en-US",{timeZone});return timeZone}catch{if(!warnedBadTimezone){warnedBadTimezone=!0;log.warn(`[scheduler] Invalid timezone "${timeZone}"; falling back to system local time.`)}return system}}const warnedInvalidCron=new Set;function nextCronMinute(cronExpression,from,timeZone){try{return parseCron(cronExpression,from.getTime()-60000,{tz:cronTimeZone(timeZone)})}catch(error){if(!warnedInvalidCron.has(cronExpression)){warnedInvalidCron.add(cronExpression);log.warn(`Invalid cron expression: ${cronExpression} (${error instanceof Error?error.message:String(error)})`)}return null}}export function shouldRunNow(cronExpression,lastRun,timeZone){const minute=new Date;minute.setSeconds(0,0);if(lastRun&&Math.floor(lastRun.getTime()/60000)===Math.floor(minute.getTime()/60000))return!1;return nextCronMinute(cronExpression,minute,timeZone)?.getTime()===minute.getTime()}function parseScheduleString(schedule){const mapped={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *"}[schedule.toLowerCase()];if(mapped)return mapped;const everyMatch=schedule.match(/^Every\.(\w+)$/i);if(everyMatch&&everyMatch[1]!==void 0){const interval=everyMatch[1].toLowerCase();return{second:"* * * * *",fiveseconds:"* * * * *",tenseconds:"* * * * *",thirtyseconds:"* * * * *",minute:"* * * * *",fiveminutes:"*/5 * * * *",tenminutes:"*/10 * * * *",fifteenminutes:"*/15 * * * *",thirtyminutes:"*/30 * * * *",hour:"0 * * * *",twohours:"0 */2 * * *",sixhours:"0 */6 * * *",twelvehours:"0 */12 * * *",day:"0 0 * * *",week:"0 0 * * 0",month:"0 0 1 * *"}[interval]||null}const partCount=schedule.split(/\s+/).length;if(partCount>=5&&partCount<=6)return schedule;return null}export function calculateNextRun(cronExpression,timeZone){const next=new Date;next.setSeconds(0,0);next.setTime(next.getTime()+60000);return nextCronMinute(cronExpression,next,timeZone)}export async function startScheduler(config={}){if(schedulerState.isRunning){log.warn("Scheduler is already running");return}schedulerState.config={...DEFAULT_CONFIG,...config};schedulerState.isRunning=!0;schedulerState.isShuttingDown=!1;await discoverJobs();const scheduledJobs=getScheduledJobs();for(const job of scheduledJobs){const schedule=job.config.rate||job.config.schedule;if(schedule){const cronExpression=parseScheduleString(schedule);if(cronExpression){const lastRun=await loadPersistedLastRun(job.name);schedulerState.jobs.set(job.name,{job,lastRun,nextRun:calculateNextRun(cronExpression,schedulerState.config.timezone),isRunning:!1});log.info(`Registered scheduled job: ${job.name} (${cronExpression})`)}else log.warn(`Invalid schedule for job ${job.name}: ${schedule}`)}}if(schedulerState.jobs.size===0){log.info("No scheduled jobs found");return}log.info(`Scheduler started with ${schedulerState.jobs.size} job(s)`);process.on("SIGINT",()=>stopScheduler());process.on("SIGTERM",()=>stopScheduler());let isChecking=!1;const scheduleNextTick=()=>{if(schedulerState.isShuttingDown)return;const interval=schedulerState.config.checkInterval,delay=interval-Date.now()%interval;schedulerState.checkInterval=setTimeout(()=>{if(!schedulerState.isShuttingDown&&!isChecking){isChecking=!0;checkScheduledJobs().catch((err)=>log.error("Scheduler check failed:",err)).finally(()=>{isChecking=!1})}scheduleNextTick()},delay);schedulerState.checkInterval?.unref?.()};scheduleNextTick();await checkScheduledJobs()}async function checkScheduledJobs(){for(const[name,state]of schedulerState.jobs){const schedule=state.job.config.rate||state.job.config.schedule;if(!schedule)continue;const cronExpression=parseScheduleString(schedule);if(!cronExpression)continue;if(shouldRunNow(cronExpression,state.lastRun,schedulerState.config.timezone)){if((schedulerState.config.preventOverlapping||state.job.config.withoutOverlapping)&&await hasUnfinishedRun(name)){log.debug(`Skipping ${name}: previous execution still running`);continue}if(state.isRunning){log.debug(`Skipping ${name}: a dispatch for it is already in flight`);continue}try{state.isRunning=!0;const when=new Date,stored=await storeScheduledRun(name,when,scheduledDispatchOptions(state.job.config));state.lastRun=stored?when:await loadPersistedLastRun(name);state.nextRun=calculateNextRun(cronExpression,schedulerState.config.timezone);state.isRunning=!1;if(!stored)continue;await emitQueueEvent("job:added",{jobId:`scheduled-${name}-${when.getTime()}`,queueName:state.job.config.queue||"default",jobName:name});log.info(`Scheduled job ${name} dispatched to queue`)}catch(error){state.isRunning=!1;log.error(`Failed to dispatch scheduled job ${name}:`,error)}}}}export async function stopScheduler(){if(!schedulerState.isRunning)return;log.info("Stopping scheduler...");schedulerState.isShuttingDown=!0;if(schedulerState.checkInterval){clearTimeout(schedulerState.checkInterval);schedulerState.checkInterval=null}schedulerState.isRunning=!1;schedulerState.jobs.clear();log.info("Scheduler stopped")}export function getSchedulerStatus(){return{isRunning:schedulerState.isRunning,jobCount:schedulerState.jobs.size,jobs:Array.from(schedulerState.jobs.entries()).map(([name,state])=>({name,schedule:state.job.config.rate||state.job.config.schedule,lastRun:state.lastRun,nextRun:state.nextRun,isRunning:state.isRunning}))}}export function isSchedulerRunning(){return schedulerState.isRunning}export function getRegisteredJobs(){return new Map(schedulerState.jobs)}export async function triggerJob(name){const state=schedulerState.jobs.get(name);if(!state)throw Error(`Scheduled job "${name}" not found`);log.info(`Manually triggering scheduled job: ${name}`);await storeJob(name,scheduledDispatchOptions(state.job.config))}export function scheduledDispatchOptions(config){const backoff=config.backoff;return{queue:config.queue||"default",payload:{},maxTries:config.tries??3,timeout:config.timeout,backoff:typeof backoff==="number"||Array.isArray(backoff)?backoff:void 0}}
1
+ import{parseCron}from"@stacksjs/cron";import{log}from"@stacksjs/logging";import{discoverJobs,getScheduledJobs}from"./discovery";import{emitQueueEvent}from"./events";import{hasUnfinishedRun,loadPersistedLastRun,storeScheduledRun}from"./scheduler-persistence";import{storeJob}from"./utils";const DEFAULT_CONFIG={checkInterval:60000,preventOverlapping:true};const schedulerState={isRunning:false,isShuttingDown:false,checkInterval:null,jobs:new Map,config:{...DEFAULT_CONFIG}};let warnedBadTimezone=false;const tzFormatterCache=new Map;function tzFormatter(timeZone){let f=tzFormatterCache.get(timeZone);if(!f){f=new Intl.DateTimeFormat("en-US",{timeZone,hour12:false,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short"});tzFormatterCache.set(timeZone,f)}return f}export function getCronParts(date,timeZone){if(timeZone&&timeZone!=="local"&&timeZone!=="system"){try{const parts=tzFormatter(timeZone).formatToParts(date);const get=(t)=>parts.find((p)=>p.type===t)?.value??"";const weekday={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};let hour=Number(get("hour"));if(hour===24)hour=0;return{minute:Number(get("minute")),hour,day:Number(get("day")),month:Number(get("month")),dayOfWeek:weekday[get("weekday")]??date.getDay()}}catch{if(!warnedBadTimezone){warnedBadTimezone=true;log.warn(`[scheduler] Invalid timezone "${timeZone}"; falling back to system local time.`)}}}return{minute:date.getMinutes(),hour:date.getHours(),day:date.getDate(),month:date.getMonth()+1,dayOfWeek:date.getDay()}}function cronTimeZone(timeZone){const system=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!timeZone||timeZone==="local"||timeZone==="system")return system;try{new Intl.DateTimeFormat("en-US",{timeZone});return timeZone}catch{if(!warnedBadTimezone){warnedBadTimezone=true;log.warn(`[scheduler] Invalid timezone "${timeZone}"; falling back to system local time.`)}return system}}const warnedInvalidCron=new Set;function nextCronMinute(cronExpression,from,timeZone){try{return parseCron(cronExpression,from.getTime()-60000,{tz:cronTimeZone(timeZone)})}catch(error){if(!warnedInvalidCron.has(cronExpression)){warnedInvalidCron.add(cronExpression);log.warn(`Invalid cron expression: ${cronExpression} (${error instanceof Error?error.message:String(error)})`)}return null}}export function shouldRunNow(cronExpression,lastRun,timeZone){const minute=new Date;minute.setSeconds(0,0);if(lastRun&&Math.floor(lastRun.getTime()/60000)===Math.floor(minute.getTime()/60000))return false;return nextCronMinute(cronExpression,minute,timeZone)?.getTime()===minute.getTime()}function parseScheduleString(schedule){const scheduleMap={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *"};const mapped=scheduleMap[schedule.toLowerCase()];if(mapped){return mapped}const everyMatch=schedule.match(/^Every\.(\w+)$/i);if(everyMatch&&everyMatch[1]!==undefined){const interval=everyMatch[1].toLowerCase();const everyMap={second:"* * * * *",fiveseconds:"* * * * *",tenseconds:"* * * * *",thirtyseconds:"* * * * *",minute:"* * * * *",fiveminutes:"*/5 * * * *",tenminutes:"*/10 * * * *",fifteenminutes:"*/15 * * * *",thirtyminutes:"*/30 * * * *",hour:"0 * * * *",twohours:"0 */2 * * *",sixhours:"0 */6 * * *",twelvehours:"0 */12 * * *",day:"0 0 * * *",week:"0 0 * * 0",month:"0 0 1 * *"};return everyMap[interval]||null}const partCount=schedule.split(/\s+/).length;if(partCount>=5&&partCount<=6){return schedule}return null}export function calculateNextRun(cronExpression,timeZone){const next=new Date;next.setSeconds(0,0);next.setTime(next.getTime()+60000);return nextCronMinute(cronExpression,next,timeZone)}export async function startScheduler(config={}){if(schedulerState.isRunning){log.warn("Scheduler is already running");return}schedulerState.config={...DEFAULT_CONFIG,...config};schedulerState.isRunning=true;schedulerState.isShuttingDown=false;await discoverJobs();const scheduledJobs=getScheduledJobs();for(const job of scheduledJobs){const schedule=job.config.rate||job.config.schedule;if(schedule){const cronExpression=parseScheduleString(schedule);if(cronExpression){const lastRun=await loadPersistedLastRun(job.name);schedulerState.jobs.set(job.name,{job,lastRun,nextRun:calculateNextRun(cronExpression,schedulerState.config.timezone),isRunning:false});log.info(`Registered scheduled job: ${job.name} (${cronExpression})`)}else{log.warn(`Invalid schedule for job ${job.name}: ${schedule}`)}}}if(schedulerState.jobs.size===0){log.info("No scheduled jobs found");return}log.info(`Scheduler started with ${schedulerState.jobs.size} job(s)`);process.on("SIGINT",()=>stopScheduler());process.on("SIGTERM",()=>stopScheduler());let isChecking=false;const scheduleNextTick=()=>{if(schedulerState.isShuttingDown)return;const interval=schedulerState.config.checkInterval;const delay=interval-Date.now()%interval;schedulerState.checkInterval=setTimeout(()=>{if(!schedulerState.isShuttingDown&&!isChecking){isChecking=true;checkScheduledJobs().catch((err)=>log.error("Scheduler check failed:",err)).finally(()=>{isChecking=false})}scheduleNextTick()},delay);schedulerState.checkInterval?.unref?.()};scheduleNextTick();await checkScheduledJobs()}async function checkScheduledJobs(){for(const[name,state]of schedulerState.jobs){const schedule=state.job.config.rate||state.job.config.schedule;if(!schedule)continue;const cronExpression=parseScheduleString(schedule);if(!cronExpression)continue;if(shouldRunNow(cronExpression,state.lastRun,schedulerState.config.timezone)){const overlapGuarded=schedulerState.config.preventOverlapping||state.job.config.withoutOverlapping;if(overlapGuarded&&await hasUnfinishedRun(name)){log.debug(`Skipping ${name}: previous execution still running`);continue}if(state.isRunning){log.debug(`Skipping ${name}: a dispatch for it is already in flight`);continue}try{state.isRunning=true;const when=new Date;const stored=await storeScheduledRun(name,when,scheduledDispatchOptions(state.job.config));state.lastRun=stored?when:await loadPersistedLastRun(name);state.nextRun=calculateNextRun(cronExpression,schedulerState.config.timezone);state.isRunning=false;if(!stored)continue;await emitQueueEvent("job:added",{jobId:`scheduled-${name}-${when.getTime()}`,queueName:state.job.config.queue||"default",jobName:name});log.info(`Scheduled job ${name} dispatched to queue`)}catch(error){state.isRunning=false;log.error(`Failed to dispatch scheduled job ${name}:`,error)}}}}export async function stopScheduler(){if(!schedulerState.isRunning){return}log.info("Stopping scheduler...");schedulerState.isShuttingDown=true;if(schedulerState.checkInterval){clearTimeout(schedulerState.checkInterval);schedulerState.checkInterval=null}schedulerState.isRunning=false;schedulerState.jobs.clear();log.info("Scheduler stopped")}export function getSchedulerStatus(){return{isRunning:schedulerState.isRunning,jobCount:schedulerState.jobs.size,jobs:Array.from(schedulerState.jobs.entries()).map(([name,state])=>({name,schedule:state.job.config.rate||state.job.config.schedule,lastRun:state.lastRun,nextRun:state.nextRun,isRunning:state.isRunning}))}}export function isSchedulerRunning(){return schedulerState.isRunning}export function getRegisteredJobs(){return new Map(schedulerState.jobs)}export async function triggerJob(name){const state=schedulerState.jobs.get(name);if(!state){throw new Error(`Scheduled job "${name}" not found`)}log.info(`Manually triggering scheduled job: ${name}`);await storeJob(name,scheduledDispatchOptions(state.job.config))}export function scheduledDispatchOptions(config){const backoff=config.backoff;return{queue:config.queue||"default",payload:{},maxTries:config.tries??3,timeout:config.timeout,backoff:typeof backoff==="number"||Array.isArray(backoff)?backoff:undefined}}
package/dist/state-row.js CHANGED
@@ -1 +1 @@
1
- import{assertSqlIdentifier,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";export async function seedStateRow(connection,table,keys,values){const dialect=sqlHelpers(getDatabaseDialect()),quote=(name)=>{assertSqlIdentifier(name);return dialect.isMysql?`\`${name}\``:`"${name}"`},columns=Object.keys(values),conflict=dialect.isMysql?`ON DUPLICATE KEY UPDATE ${quote(keys[0])} = ${quote(keys[0])}`:`ON CONFLICT (${keys.map(quote).join(", ")}) DO NOTHING`;await connection.unsafe(`INSERT INTO ${quote(table)} (${columns.map(quote).join(", ")}) VALUES (${columns.map((_,index)=>dialect.param(index+1)).join(", ")}) ${conflict}`,Object.values(values))}
1
+ import{assertSqlIdentifier,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";export async function seedStateRow(connection,table,keys,values){const dialect=sqlHelpers(getDatabaseDialect());const quote=(name)=>{assertSqlIdentifier(name);return dialect.isMysql?`\`${name}\``:`"${name}"`};const columns=Object.keys(values);const conflict=dialect.isMysql?`ON DUPLICATE KEY UPDATE ${quote(keys[0])} = ${quote(keys[0])}`:`ON CONFLICT (${keys.map(quote).join(", ")}) DO NOTHING`;await connection.unsafe(`INSERT INTO ${quote(table)} (${columns.map(quote).join(", ")}) VALUES (${columns.map((_,index)=>dialect.param(index+1)).join(", ")}) ${conflict}`,Object.values(values))}
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- class FakeQueue{dispatchedJobs=[];pushedJobs=[];processedJobs=[];failedJobs=[];dispatch(name,data,options={}){this.dispatchedJobs.push({name,data,options,dispatchedAt:new Date,queue:options.queue||"default"})}push(name,data,options={}){this.pushedJobs.push({name,data,options,dispatchedAt:new Date,queue:options.queue||"default"})}dispatched(name){if(name)return this.dispatchedJobs.filter((j)=>j.name===name);return[...this.dispatchedJobs]}pushed(name){if(name)return this.pushedJobs.filter((j)=>j.name===name);return[...this.pushedJobs]}assertDispatched(name,callback){const jobs=this.dispatched(name);if(jobs.length===0)throw Error(`Expected job "${name}" to be dispatched, but it was not.`);if(callback){if(jobs.filter(callback).length===0)throw Error(`Expected job "${name}" to be dispatched matching the callback, but no matching jobs were found.`)}}assertNotDispatched(name){const jobs=this.dispatched(name);if(jobs.length>0)throw Error(`Expected job "${name}" to not be dispatched, but it was dispatched ${jobs.length} time(s).`)}assertDispatchedTimes(name,times){const jobs=this.dispatched(name);if(jobs.length!==times)throw Error(`Expected job "${name}" to be dispatched ${times} time(s), but it was dispatched ${jobs.length} time(s).`)}assertNothingDispatched(){if(this.dispatchedJobs.length>0){const names=[...new Set(this.dispatchedJobs.map((j)=>j.name))].join(", ");throw Error(`Expected no jobs to be dispatched, but found: ${names}`)}}assertPushed(name,callback){const jobs=this.pushed(name);if(jobs.length===0)throw Error(`Expected job "${name}" to be pushed, but it was not.`);if(callback){if(jobs.filter(callback).length===0)throw Error(`Expected job "${name}" to be pushed matching the callback, but no matching jobs were found.`)}}assertPushedWithDelay(name,delay){if(this.pushed(name).filter((j)=>j.options?.delay===delay).length===0)throw Error(`Expected job "${name}" to be pushed with delay ${delay}ms, but no matching jobs were found.`)}assertPushedOn(queue,name){if(this.pushed(name).filter((j)=>j.queue===queue).length===0)throw Error(`Expected job "${name}" to be pushed on queue "${queue}", but it was not.`)}async processJob(name,handler){const job=this.dispatchedJobs.find((j)=>j.name===name);if(!job)throw Error(`No dispatched job found with name "${name}"`);try{await handler(job.data);this.processedJobs.push(job)}catch(error){this.failedJobs.push({job,error});throw error}}processed(name){if(name)return this.processedJobs.filter((j)=>j.name===name);return[...this.processedJobs]}failed(name){if(name)return this.failedJobs.filter((f)=>f.job.name===name);return[...this.failedJobs]}reset(){this.dispatchedJobs=[];this.pushedJobs=[];this.processedJobs=[];this.failedJobs=[]}}let fakeQueue=null;export function fake(){fakeQueue=new FakeQueue;return fakeQueue}export function getFakeQueue(){return fakeQueue}export function isFaked(){return fakeQueue!==null}export function restore(){fakeQueue=null}export class QueueTester{queue;constructor(){this.queue=fake()}dispatch(name,data,options={}){this.queue.dispatch(name,data,options);return this}push(name,data,options={}){this.queue.push(name,data,options);return this}assertDispatched(name,callback){this.queue.assertDispatched(name,callback);return this}assertNotDispatched(name){this.queue.assertNotDispatched(name);return this}assertDispatchedTimes(name,times){this.queue.assertDispatchedTimes(name,times);return this}assertNothingDispatched(){this.queue.assertNothingDispatched();return this}dispatched(name){return this.queue.dispatched(name)}reset(){this.queue.reset();return this}cleanup(){restore()}}export function createQueueTester(){return new QueueTester}export async function runJob(jobModule,data){return await jobModule.handle(data)}export async function expectJobToFail(jobModule,data,expectedError){try{await jobModule.handle(data);throw Error("Expected job to fail, but it succeeded")}catch(error){if(error.message==="Expected job to fail, but it succeeded")throw error;if(expectedError){const message=error.message;if(typeof expectedError==="string"){if(!message.includes(expectedError))throw Error(`Expected error to contain "${expectedError}", got "${message}"`)}else if(!expectedError.test(message))throw Error(`Expected error to match ${expectedError}, got "${message}"`)}return error}}
1
+ class FakeQueue{dispatchedJobs=[];pushedJobs=[];processedJobs=[];failedJobs=[];dispatch(name,data,options={}){this.dispatchedJobs.push({name,data,options,dispatchedAt:new Date,queue:options.queue||"default"})}push(name,data,options={}){this.pushedJobs.push({name,data,options,dispatchedAt:new Date,queue:options.queue||"default"})}dispatched(name){if(name){return this.dispatchedJobs.filter((j)=>j.name===name)}return[...this.dispatchedJobs]}pushed(name){if(name){return this.pushedJobs.filter((j)=>j.name===name)}return[...this.pushedJobs]}assertDispatched(name,callback){const jobs=this.dispatched(name);if(jobs.length===0){throw new Error(`Expected job "${name}" to be dispatched, but it was not.`)}if(callback){const matching=jobs.filter(callback);if(matching.length===0){throw new Error(`Expected job "${name}" to be dispatched matching the callback, but no matching jobs were found.`)}}}assertNotDispatched(name){const jobs=this.dispatched(name);if(jobs.length>0){throw new Error(`Expected job "${name}" to not be dispatched, but it was dispatched ${jobs.length} time(s).`)}}assertDispatchedTimes(name,times){const jobs=this.dispatched(name);if(jobs.length!==times){throw new Error(`Expected job "${name}" to be dispatched ${times} time(s), but it was dispatched ${jobs.length} time(s).`)}}assertNothingDispatched(){if(this.dispatchedJobs.length>0){const names=[...new Set(this.dispatchedJobs.map((j)=>j.name))].join(", ");throw new Error(`Expected no jobs to be dispatched, but found: ${names}`)}}assertPushed(name,callback){const jobs=this.pushed(name);if(jobs.length===0){throw new Error(`Expected job "${name}" to be pushed, but it was not.`)}if(callback){const matching=jobs.filter(callback);if(matching.length===0){throw new Error(`Expected job "${name}" to be pushed matching the callback, but no matching jobs were found.`)}}}assertPushedWithDelay(name,delay){const jobs=this.pushed(name);const matching=jobs.filter((j)=>j.options?.delay===delay);if(matching.length===0){throw new Error(`Expected job "${name}" to be pushed with delay ${delay}ms, but no matching jobs were found.`)}}assertPushedOn(queue,name){const jobs=this.pushed(name).filter((j)=>j.queue===queue);if(jobs.length===0){throw new Error(`Expected job "${name}" to be pushed on queue "${queue}", but it was not.`)}}async processJob(name,handler){const job=this.dispatchedJobs.find((j)=>j.name===name);if(!job){throw new Error(`No dispatched job found with name "${name}"`)}try{await handler(job.data);this.processedJobs.push(job)}catch(error){this.failedJobs.push({job,error});throw error}}processed(name){if(name){return this.processedJobs.filter((j)=>j.name===name)}return[...this.processedJobs]}failed(name){if(name){return this.failedJobs.filter((f)=>f.job.name===name)}return[...this.failedJobs]}reset(){this.dispatchedJobs=[];this.pushedJobs=[];this.processedJobs=[];this.failedJobs=[]}}let fakeQueue=null;export function fake(){fakeQueue=new FakeQueue;return fakeQueue}export function getFakeQueue(){return fakeQueue}export function isFaked(){return fakeQueue!==null}export function restore(){fakeQueue=null}export class QueueTester{queue;constructor(){this.queue=fake()}dispatch(name,data,options={}){this.queue.dispatch(name,data,options);return this}push(name,data,options={}){this.queue.push(name,data,options);return this}assertDispatched(name,callback){this.queue.assertDispatched(name,callback);return this}assertNotDispatched(name){this.queue.assertNotDispatched(name);return this}assertDispatchedTimes(name,times){this.queue.assertDispatchedTimes(name,times);return this}assertNothingDispatched(){this.queue.assertNothingDispatched();return this}dispatched(name){return this.queue.dispatched(name)}reset(){this.queue.reset();return this}cleanup(){restore()}}export function createQueueTester(){return new QueueTester}export async function runJob(jobModule,data){return await jobModule.handle(data)}export async function expectJobToFail(jobModule,data,expectedError){try{await jobModule.handle(data);throw new Error("Expected job to fail, but it succeeded")}catch(error){if(error.message==="Expected job to fail, but it succeeded"){throw error}if(expectedError){const message=error.message;if(typeof expectedError==="string"){if(!message.includes(expectedError)){throw new Error(`Expected error to contain "${expectedError}", got "${message}"`)}}else if(!expectedError.test(message)){throw new Error(`Expected error to match ${expectedError}, got "${message}"`)}}return error}}
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- import{mutationCount}from"@stacksjs/database/runtime";import{createEnvelope,serializeEnvelope}from"./envelope";export function updatedRowCount(result){return mutationCount(result)}export function buildScheduledJobRow(name,options){const envelope=createEnvelope(name,options.payload||{},{queue:options.queue,tries:options.maxTries,timeout:options.timeout,backoff:Array.isArray(options.backoff)||typeof options.backoff==="number"?options.backoff:void 0});return{queue:options.queue||"default",payload:serializeEnvelope(envelope),attempts:0,available_at:generateUnixTimestamp(options.delay||0),created_at:new Date().toISOString().slice(0,19).replace("T"," ")}}export async function storeJob(name,options){const row=buildScheduledJobRow(name,options),{db}=await import("@stacksjs/database/runtime");await db.insertInto("jobs").values(row).execute()}function generateUnixTimestamp(secondsToAdd){const now=Date.now();return Math.floor(now/1000+secondsToAdd)}
1
+ import{mutationCount}from"@stacksjs/database/runtime";import{createEnvelope,serializeEnvelope}from"./envelope";export function updatedRowCount(result){return mutationCount(result)}export function buildScheduledJobRow(name,options){const envelope=createEnvelope(name,options.payload||{},{queue:options.queue,tries:options.maxTries,timeout:options.timeout,backoff:Array.isArray(options.backoff)||typeof options.backoff==="number"?options.backoff:undefined});return{queue:options.queue||"default",payload:serializeEnvelope(envelope),attempts:0,available_at:generateUnixTimestamp(options.delay||0),created_at:new Date().toISOString().slice(0,19).replace("T"," ")}}export async function storeJob(name,options){const row=buildScheduledJobRow(name,options);const{db}=await import("@stacksjs/database/runtime");await db.insertInto("jobs").values(row).execute()}function generateUnixTimestamp(secondsToAdd){const now=Date.now();return Math.floor(now/1000+secondsToAdd)}
@@ -1 +1 @@
1
- import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";export const WORKER_STALE_MS=60000,WORKER_RETENTION_MS=604800000;export async function persistWorkerSnapshot(snapshot){const dialect=sqlHelpers(getDatabaseDialect()),values=[snapshot.worker.id,JSON.stringify(snapshot),snapshot.heartbeatAt],columns=["worker_id","snapshot","heartbeat_at"],quote=(name)=>dialect.isMysql?`\`${name}\``:`"${name}"`,update=["snapshot","heartbeat_at"].map((column)=>dialect.isMysql?`${quote(column)} = VALUES(${quote(column)})`:`${quote(column)} = excluded.${quote(column)}`).join(", ");await db.unsafe(`INSERT INTO queue_workers (${columns.map(quote).join(", ")}) VALUES (${values.map((_,i)=>dialect.param(i+1)).join(", ")}) ${dialect.isMysql?"ON DUPLICATE KEY UPDATE":"ON CONFLICT (worker_id) DO UPDATE SET"} ${update}`,values).execute()}export async function pruneWorkerSnapshots(now=Date.now()){const dialect=sqlHelpers(getDatabaseDialect());await db.unsafe(`DELETE FROM queue_workers WHERE heartbeat_at < ${dialect.param(1)}`,[now-WORKER_RETENTION_MS]).execute()}export function workerSnapshotState(snapshot,now=Date.now()){if(snapshot.worker.status==="stopped"||now-snapshot.heartbeatAt>WORKER_STALE_MS)return{...snapshot,worker:{...snapshot.worker,status:"stopped"},activeJobs:0,metrics:{...snapshot.metrics,throughputPerMinute:0,averageDuration:0}};return snapshot}export async function readWorkerSnapshots(now=Date.now()){const dialect=sqlHelpers(getDatabaseDialect());return(await db.unsafe(`SELECT snapshot FROM queue_workers WHERE heartbeat_at >= ${dialect.param(1)} ORDER BY heartbeat_at DESC`,[now-WORKER_RETENTION_MS]).execute()).map((row)=>workerSnapshotState(JSON.parse(row.snapshot),now))}export function aggregateWorkerMetrics(snapshots){const throughputPerMinute=snapshots.reduce((sum,value)=>sum+value.metrics.throughputPerMinute,0);return{counts:{completed:snapshots.reduce((sum,value)=>sum+value.metrics.completed,0),failed:snapshots.reduce((sum,value)=>sum+value.metrics.failed,0)},throughputPerMinute,averageDuration:throughputPerMinute>0?snapshots.reduce((sum,value)=>sum+value.metrics.averageDuration*value.metrics.throughputPerMinute,0)/throughputPerMinute:0}}
1
+ import{db,getDatabaseDialect,sqlHelpers}from"@stacksjs/database/runtime";export const WORKER_STALE_MS=60000;export const WORKER_RETENTION_MS=7*24*60*60*1000;export async function persistWorkerSnapshot(snapshot){const dialect=sqlHelpers(getDatabaseDialect());const values=[snapshot.worker.id,JSON.stringify(snapshot),snapshot.heartbeatAt];const columns=["worker_id","snapshot","heartbeat_at"];const quote=(name)=>dialect.isMysql?`\`${name}\``:`"${name}"`;const update=["snapshot","heartbeat_at"].map((column)=>dialect.isMysql?`${quote(column)} = VALUES(${quote(column)})`:`${quote(column)} = excluded.${quote(column)}`).join(", ");await db.unsafe(`INSERT INTO queue_workers (${columns.map(quote).join(", ")}) VALUES (${values.map((_,i)=>dialect.param(i+1)).join(", ")}) ${dialect.isMysql?"ON DUPLICATE KEY UPDATE":"ON CONFLICT (worker_id) DO UPDATE SET"} ${update}`,values).execute()}export async function pruneWorkerSnapshots(now=Date.now()){const dialect=sqlHelpers(getDatabaseDialect());await db.unsafe(`DELETE FROM queue_workers WHERE heartbeat_at < ${dialect.param(1)}`,[now-WORKER_RETENTION_MS]).execute()}export function workerSnapshotState(snapshot,now=Date.now()){if(snapshot.worker.status==="stopped"||now-snapshot.heartbeatAt>WORKER_STALE_MS){return{...snapshot,worker:{...snapshot.worker,status:"stopped"},activeJobs:0,metrics:{...snapshot.metrics,throughputPerMinute:0,averageDuration:0}}}return snapshot}export async function readWorkerSnapshots(now=Date.now()){const dialect=sqlHelpers(getDatabaseDialect());const rows=await db.unsafe(`SELECT snapshot FROM queue_workers WHERE heartbeat_at >= ${dialect.param(1)} ORDER BY heartbeat_at DESC`,[now-WORKER_RETENTION_MS]).execute();return rows.map((row)=>workerSnapshotState(JSON.parse(row.snapshot),now))}export function aggregateWorkerMetrics(snapshots){const throughputPerMinute=snapshots.reduce((sum,value)=>sum+value.metrics.throughputPerMinute,0);return{counts:{completed:snapshots.reduce((sum,value)=>sum+value.metrics.completed,0),failed:snapshots.reduce((sum,value)=>sum+value.metrics.failed,0)},throughputPerMinute,averageDuration:throughputPerMinute>0?snapshots.reduce((sum,value)=>sum+value.metrics.averageDuration*value.metrics.throughputPerMinute,0)/throughputPerMinute:0}}
package/dist/worker.js CHANGED
@@ -1 +1 @@
1
- import{persistWorkerSnapshot,pruneWorkerSnapshots}from"./worker-monitor";import{batchMembershipId}from"./batch-payload";import{resolveQueueDriver}from"./driver";import{err,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import process from"node:process";import{parseEnvelope}from"./envelope";import{updatedRowCount}from"./utils";import{captureProcessLeaseOwner,processLeaseOwnerStatus}from"./process-owner";let workerCrashHandlersInstalled=!1;function installWorkerCrashHandlers(){if(workerCrashHandlersInstalled)return;workerCrashHandlersInstalled=!0;process.on("unhandledRejection",(reason,_promise)=>{log.error(`Unhandled Rejection: ${reason}`)});process.on("uncaughtException",(error)=>{log.error(`Uncaught Exception: ${error.message}`)})}let activeJobCount=0,workerRunning=!1,workerId="";const inFlightJobs=new Set,inFlightDatabaseBatches=new Set,reserveErrorLoggedAt=new Map;let reservationScanAfter=0;function ownedReservationPayload(payload){const owner=captureProcessLeaseOwner();if(!owner)return payload;try{const envelope=JSON.parse(payload);if(!envelope||typeof envelope!=="object"||Array.isArray(envelope))return payload;return JSON.stringify({...envelope,_queueProcessOwner:owner})}catch{return payload}}function trackInFlight(promise,pending=inFlightJobs){pending.add(promise);promise.then(()=>pending.delete(promise),()=>pending.delete(promise));return promise}function getReservationTtlSec(){const raw=process.env.STACKS_QUEUE_RESERVATION_TTL_SEC,n=raw===void 0?Number.NaN:Number.parseInt(raw,10);return Number.isFinite(n)&&n>0?n:3600}function getRetryJitterRatio(){const raw=process.env.STACKS_QUEUE_RETRY_JITTER;if(raw===void 0)return 0.2;const n=Number(raw);if(!Number.isFinite(n)||n<0)return 0.2;return Math.min(n,1)}export function applyRetryJitter(delaySeconds,ratio,random=Math.random){if(!(delaySeconds>0)||ratio<=0)return delaySeconds;return Math.round(delaySeconds+delaySeconds*ratio*random())}function getSweepIntervalMs(){const raw=process.env.STACKS_QUEUE_SWEEP_INTERVAL_SEC,n=raw===void 0?Number.NaN:Number.parseInt(raw,10);return(Number.isFinite(n)&&n>0?n:60)*1000}async function sweepStaleReservations(){const ttlSec=getReservationTtlSec(),cutoff=Math.floor(Date.now()/1000)-ttlSec,now=Math.floor(Date.now()/1000);try{const{db}=await import("@stacksjs/database/runtime"),result=await db.updateTable("jobs").set({reserved_at:null,available_at:now}).where("reserved_at","<=",cutoff).executeTakeFirst();let requeued=updatedRowCount(result);const owned=await db.selectFrom("jobs").select(["id","payload","reserved_at"]).where("reserved_at",">",cutoff).where("id",">",reservationScanAfter).orderBy("id","asc").limit(128).execute();reservationScanAfter=owned.length===128?Number(owned.at(-1).id):0;for(const row of owned){let owner;try{owner=JSON.parse(String(row.payload))._queueProcessOwner}catch{continue}if(processLeaseOwnerStatus(owner)!=="dead")continue;const released=await db.updateTable("jobs").set({reserved_at:null,available_at:now}).where("id","=",row.id).where("reserved_at","=",row.reserved_at).where("payload","=",row.payload).executeTakeFirst();requeued+=updatedRowCount(released)}if(requeued>0)log.warn(`[queue] Requeued ${requeued} job(s) after their owner exited or their reservation exceeded the ${ttlSec}s TTL. Set STACKS_QUEUE_RESERVATION_TTL_SEC to tune.`);return requeued}catch(error){log.error("[queue] Reservation sweep failed",{reason:error instanceof Error?error.message:String(error)});return 0}}function isNonRetryableError(e){if(!e||typeof e!=="object")return!1;const status=e.status??e.statusCode;if(typeof status==="number"&&status>=400&&status<500)return!0;const name=e.name;if(typeof name==="string"&&(name==="ValidationError"||name==="ModelNotFoundError"))return!0;return!1}function getQueueDriver(){return resolveQueueDriver()}async function monitorWorker(id){const{getWorkerTracker,getGlobalMetrics}=await import("./events");let writing,warned=!1;const persist=()=>{if(writing)return writing;const worker=getWorkerTracker().getAll().find((worker)=>worker.id===id);if(!worker)return Promise.resolve();const metrics=getGlobalMetrics().getMetrics();writing=persistWorkerSnapshot({worker:{...worker},heartbeatAt:Date.now(),activeJobs:getActiveJobCount(),metrics:{completed:worker.processedCount,failed:worker.failedCount,throughputPerMinute:metrics.throughputPerMinute,averageDuration:metrics.averageDuration}}).catch((error)=>{if(warned)return;warned=!0;log.warn(`Queue worker telemetry unavailable. Run migrations for QueueWorker: ${error instanceof Error?error.message:String(error)}`)}).finally(()=>{writing=void 0});return writing};pruneWorkerSnapshots().catch(()=>{});persist();const timer=setInterval(()=>{persist()},1e4);timer.unref();return async()=>{clearInterval(timer);await writing;await persist()}}export async function startProcessor(queueName,options={}){let stopMonitor,monitoredId;try{log.info("Starting queue processor...");installWorkerCrashHandlers();workerRunning=!0;workerId=`worker-${process.pid}-${Date.now()}`;const concurrency=options.concurrency||1,queueDriver=getQueueDriver(),{getWorkerTracker,getGlobalMetrics}=await import("./events");getGlobalMetrics();getWorkerTracker().register(workerId,queueName||"*");monitoredId=workerId;stopMonitor=await monitorWorker(monitoredId);if(queueDriver==="redis"){log.info("Using Redis queue driver (bun-queue)");await processJobsFromRedis(queueName||"default",concurrency);return ok(void 0)}const named=namedWorkerQueues(queueName);let queues;if(named.length>0)queues=named;else{queues=await getAllQueues();if(queues.length===0)queues=["default"]}log.info(`Processing queues: ${queues.join(", ")}`);await processJobsFromDatabase(queues,concurrency,{followNewQueues:named.length===0});return ok(void 0)}catch(error){workerRunning=!1;return err(error)}finally{const{getWorkerTracker}=await import("./events");if(monitoredId)getWorkerTracker().unregister(monitoredId);await stopMonitor?.()}}async function getAllQueues(){try{const{db}=await import("@stacksjs/database/runtime"),queues=(await db.selectFrom("jobs").select("queue").distinct().execute()).map((r)=>r.queue).filter((q)=>Boolean(q));return queues.length>0?queues:["default"]}catch{return["default"]}}export function namedWorkerQueues(queueName){if(typeof queueName!=="string")return[];return[...new Set(queueName.split(",").map((name)=>name.trim()).filter(Boolean))]}async function processJobsFromDatabase(initialQueues,concurrency,options={followNewQueues:!0}){log.info("Listening for jobs...");let queues=initialQueues,lastQueueRefresh=Date.now();const queueRefreshInterval=1e4;let lastSweep=Date.now();const sweepIntervalMs=getSweepIntervalMs();await sweepStaleReservations();while(workerRunning)try{let processedJobs=!1;const now=Date.now();if(options.followNewQueues&&now-lastQueueRefresh>queueRefreshInterval){try{const refreshedQueues=await getAllQueues();if(refreshedQueues.length>0)queues=refreshedQueues}catch{}lastQueueRefresh=now}if(now-lastSweep>sweepIntervalMs){await sweepStaleReservations();lastSweep=now}for(const queueName of queues){if(!workerRunning)break;try{const{isCircuitOpen}=await import("./circuit-breaker");if(await isCircuitOpen(queueName))continue}catch{}if(!workerRunning)break;const processed=await trackInFlight(processDatabaseBatch(queueName,concurrency),inFlightDatabaseBatches);processedJobs||=processed}if(workerRunning&&!processedJobs)await sleep(1000)}catch{await sleep(3000)}}async function processDatabaseBatch(queueName,concurrency){let jobs=[];try{jobs=await fetchPendingJobs(queueName,concurrency)}catch(error){const now=Date.now(),last=reserveErrorLoggedAt.get(queueName)??0;if(now-last>60000){reserveErrorLoggedAt.set(queueName,now);log.error(`[queue] Could not reserve jobs on "${queueName}" - retrying each cycle:`,error)}return!1}await Promise.all(jobs.map(async(job)=>{try{log.info(`Processing job ${job.id} from queue "${queueName}"`);await trackInFlight(processJob(job))}catch{log.error(`Unexpected error processing job ${job.id}`)}}));return jobs.length>0}async function fetchPendingJobs(queueName,limit){const now=Math.floor(Date.now()/1000),{db}=await import("@stacksjs/database/runtime"),claimed=[];for(let i=0;i<limit&&workerRunning;i++){const job=await db.selectFrom("jobs").where("queue","=",queueName).whereNull("reserved_at").where("available_at","<=",now).orderBy("id","asc").limit(1).selectAll().executeTakeFirst();if(!job||!workerRunning)break;const payload=ownedReservationPayload(String(job.payload)),result=await db.updateTable("jobs").set({reserved_at:now,attempts:Number(job.attempts||0)+1,payload}).where("id","=",job.id).whereNull("reserved_at").where("payload","=",job.payload).executeTakeFirst();if(updatedRowCount(result)>0)claimed.push({...job,payload})}return claimed}async function processJob(job){const jobId=job.id,queueName=job.queue||"default";activeJobCount++;const startTime=Date.now(),{emitQueueEvent,getWorkerTracker}=await import("./events"),tracker=getWorkerTracker();tracker.markActive(workerId);let parsedJobName;try{parsedJobName=JSON.parse(job.payload||"{}").jobName}catch{}await emitQueueEvent("job:processing",{jobId:String(jobId),queueName,jobName:parsedJobName});try{const parsedForBatch=JSON.parse(job.payload||"{}"),batchId=batchMembershipId(parsedForBatch.payload);if(batchId){const{isBatchCancelled}=await import("./batch");if(await isBatchCancelled(batchId)){log.info(`[Queue] Skipping job ${jobId} - batch ${batchId} has been cancelled`);await deleteJob(jobId);activeJobCount--;tracker.markIdle(workerId);return}}}catch{}let jobError=null;const declared=parsedJobName?await(await import("./job")).jobDefaults(parsedJobName):{};try{const payload=JSON.parse(job.payload||"{}"),timeoutSec=readJobTimeoutSec(payload)??declared.timeout;if(timeoutSec===void 0)await executeJobPayload(payload);else await raceWithTimeout(executeJobPayload(payload),timeoutSec*1000,`Job ${jobId} exceeded ${timeoutSec}s timeout`)}catch(e){jobError=e instanceof Error?e:Error(String(e))}if(!jobError)try{await deleteJob(jobId);log.info(`[Queue] Job ${jobId} completed`);tracker.recordCompletion(workerId);try{const{recordCircuitSuccess}=await import("./circuit-breaker");await recordCircuitSuccess(job.queue??"default")}catch{}await emitQueueEvent("job:completed",{jobId:String(jobId),queueName,duration:Date.now()-startTime});try{const payload=JSON.parse(job.payload||"{}"),batchId=batchMembershipId(payload.payload);if(batchId){const{recordBatchJobCompletion}=await import("./batch");await recordBatchJobCompletion(batchId)}}catch{}}catch{log.info(`[Queue] Failed to delete completed job ${jobId}`)}else{const errorMessage=jobError.message;log.info(`[Queue] Job ${jobId} failed: ${errorMessage}`);tracker.recordFailure(workerId);await emitQueueEvent("job:failed",{jobId:String(jobId),queueName,error:jobError,duration:Date.now()-startTime,attemptsMade:(job.attempts||0)+1});let maxAttempts=1,parsedPayload={};try{parsedPayload=JSON.parse(job.payload||"{}");maxAttempts=parsedPayload.options?.tries||declared.tries||1}catch{}const currentAttempts=(job.attempts||0)+1;if(currentAttempts>=maxAttempts){log.info(`[Queue] Job ${jobId} exceeded max attempts (${currentAttempts}/${maxAttempts})`);let persisted=!1;if(parsedPayload?._retriedFromFailed===!0)try{const{moveToDeadLetter}=await import("./dead-letter");persisted=await moveToDeadLetter({queue:job.queue,payload:job.payload,exception:jobError.stack||jobError.message},"repeat-failure",2);if(persisted)log.info(`[Queue] Job ${jobId} re-failed after retry - moved to dead_letter_jobs`)}catch{persisted=!1}if(!persisted){log.info(`[Queue] Moving job ${jobId} to failed_jobs`);try{persisted=await moveToFailedJobs(job,jobError,{attempts:currentAttempts,maxAttempts,durationMs:Date.now()-startTime})}catch{persisted=!1}}if(persisted)try{await deleteJob(jobId)}catch{log.info(`[Queue] Failed to delete failed job ${jobId}`)}else log.error(`[Queue] Job ${jobId} exhausted its retries but could NOT be persisted to failed_jobs - leaving it in the queue to avoid data loss (the reservation sweep will retry it). Check that the failed_jobs table exists and is writable.`);try{const{recordFailureForPoison}=await import("./poison"),{recordCircuitFailure}=await import("./circuit-breaker"),jobName=parsedPayload?.jobName??"unknown";await recordFailureForPoison(jobName,parsedPayload?.payload);await recordCircuitFailure(job.queue??"default")}catch{}try{const batchId=batchMembershipId(parsedPayload.payload);if(batchId){const{recordBatchJobFailure}=await import("./batch");await recordBatchJobFailure(batchId,String(jobId),jobError)}}catch{}}else{const backoffDelays=parsedPayload.options?.backoff??declared.backoff;let retryDelay=30;if(Array.isArray(backoffDelays)&&backoffDelays.length>0){const backoffIndex=Math.min(currentAttempts-1,backoffDelays.length-1);retryDelay=backoffDelays[backoffIndex]}else if(typeof backoffDelays==="number"&&backoffDelays>0)retryDelay=backoffDelays;retryDelay=Number(retryDelay);if(!Number.isFinite(retryDelay)||retryDelay<0)retryDelay=30;retryDelay=applyRetryJitter(retryDelay,getRetryJitterRatio());log.info(`[Queue] Job ${jobId} will be retried in ${retryDelay}s (attempt ${currentAttempts}/${maxAttempts})`);try{await releaseJob(jobId,retryDelay);log.info(`[Queue] Job ${jobId} released for retry`)}catch{log.info(`[Queue] Failed to release job ${jobId} for retry`)}}}activeJobCount--;tracker.markIdle(workerId)}async function deleteJob(jobId){const{db}=await import("@stacksjs/database/runtime");await db.deleteFrom("jobs").where("id","=",jobId).execute()}async function releaseJob(jobId,delaySeconds=30){const retryAt=Math.floor(Date.now()/1000)+delaySeconds;log.debug(`Releasing job ${jobId} for retry at ${retryAt}`);try{const{db}=await import("@stacksjs/database/runtime");await db.updateTable("jobs").set({reserved_at:null,available_at:retryAt}).where("id","=",jobId).execute();log.debug(`Job ${jobId} released successfully`)}catch{log.error(`Failed to release job ${jobId}`)}}async function moveToFailedJobs(job,error,metrics){try{const failedAt=new Date().toISOString().slice(0,19).replace("T"," "),uuid=crypto.randomUUID(),exception=error.stack||error.message,{db}=await import("@stacksjs/database/runtime");await db.insertInto("failed_jobs").values({uuid,connection:"database",queue:job.queue,payload:job.payload,exception,attempts:metrics.attempts,max_attempts:metrics.maxAttempts,duration_ms:metrics.durationMs,failed_at:failedAt}).execute();return!0}catch(insertError){log.error("Failed to log failed job:",insertError);return!1}}function readJobTimeoutSec(payload){if(!payload||typeof payload!=="object")return;const t=payload.options?.timeout;if(typeof t!=="number"||!Number.isFinite(t)||t<=0)return;return t}async function raceWithTimeout(task,timeoutMs,message){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(message)),timeoutMs)});try{return await Promise.race([task,timeout])}finally{if(timer!==void 0)clearTimeout(timer)}}async function executeJobPayload(payload){const parsed=parseEnvelope(payload);if(!parsed.ok)throw Error(`[queue] Cannot deserialize job envelope: ${parsed.reason}`+(parsed.detail?` (${parsed.detail})`:""));const{runJob}=await import("./job");await runJob(parsed.envelope.jobName,{payload:parsed.envelope.payload,context:parsed.envelope.context,traceId:parsed.envelope.traceId})}async function processJobsFromRedis(queueName,concurrency){const{RedisQueue}=await import("./drivers/redis"),{queue:queueConfig}=await import("@stacksjs/config"),redisConfig=queueConfig?.connections?.redis;if(!redisConfig)throw Error("Redis queue connection is not configured. Check config/queue.ts");const queue=new RedisQueue(queueName,redisConfig),{emitQueueEvent,getWorkerTracker}=await import("./events"),tracker=getWorkerTracker(),handleRedisJob=async(bunJob)=>{activeJobCount++;tracker.markActive(workerId);const startTime=Date.now(),parsed=parseEnvelope(bunJob.data);if(!parsed.ok){activeJobCount--;tracker.markIdle(workerId);log.error(`[Queue] Skipping Redis job ${bunJob.id} - unparseable envelope: ${parsed.reason}${parsed.detail?` (${parsed.detail})`:""}`);return}const data=parsed.envelope,batchId=batchMembershipId(data.payload);if(batchId)try{const{isBatchCancelled}=await import("./batch");if(await isBatchCancelled(batchId)){log.info(`[Queue] Skipping Redis job ${bunJob.id} - batch ${batchId} has been cancelled`);activeJobCount--;tracker.markIdle(workerId);return}}catch{}await emitQueueEvent("job:processing",{jobId:String(bunJob.id),queueName});try{const{runJob}=await import("./job");await runJob(data.jobName,{payload:data.payload,context:data.context,traceId:data.traceId});tracker.recordCompletion(workerId);await emitQueueEvent("job:completed",{jobId:String(bunJob.id),queueName,duration:Date.now()-startTime});if(batchId)try{const{recordBatchJobCompletion}=await import("./batch");await recordBatchJobCompletion(batchId)}catch{}log.info(`[Queue] Redis job ${bunJob.id} completed`)}catch(e){tracker.recordFailure(workerId);await emitQueueEvent("job:failed",{jobId:String(bunJob.id),queueName,error:e instanceof Error?e:Error(String(e)),duration:Date.now()-startTime});if(batchId)try{const{recordBatchJobFailure}=await import("./batch");await recordBatchJobFailure(batchId,String(bunJob.id),e instanceof Error?e:Error(String(e)))}catch{}log.error(`[Queue] Redis job ${bunJob.id} failed: ${e}`);if(isNonRetryableError(e)){log.info(`[Queue] Redis job ${bunJob.id} hit a non-retryable error - skipping retry`);return}throw e}finally{activeJobCount--;tracker.markIdle(workerId)}};queue.process(concurrency,(bunJob)=>trackInFlight(handleRedisJob(bunJob)));log.info(`Listening for Redis jobs on queue "${queueName}" with concurrency ${concurrency}...`);while(workerRunning)await sleep(1000);await queue.close()}export async function stopProcessor(options={}){const graceMs=options.graceMs??1e4;workerRunning=!1;const pending=new Set([...inFlightDatabaseBatches,...inFlightJobs]);if(pending.size>0&&graceMs>0){log.info(`[queue] Draining database reservations and in-flight jobs (grace ${graceMs}ms)`);const drain=Promise.allSettled([...pending]),timeout=new Promise((resolve)=>setTimeout(()=>resolve("timeout"),graceMs));if(await Promise.race([drain.then(()=>"drained"),timeout])==="timeout"&&(inFlightJobs.size>0||inFlightDatabaseBatches.size>0))log.warn("[queue] Drain timed out with reservations or jobs still active. Their reservations will be reclaimed by the next worker's sweep (Q-2).")}if(workerId){const{getWorkerTracker}=await import("./events");getWorkerTracker().unregister(workerId)}if(getQueueDriver()==="redis"){const{closeSharedRedisQueues}=await import("./drivers/redis");await closeSharedRedisQueues()}log.info("Queue processor stopped")}export async function executeFailedJobs(){const{db}=await import("@stacksjs/database/runtime"),failedJobs=await db.selectFrom("failed_jobs").selectAll().execute();for(const failedJob of failedJobs)await retryFailedJob(Number(failedJob.id))}export async function retryFailedJob(id){const now=Math.floor(Date.now()/1000),createdAt=new Date().toISOString().slice(0,19).replace("T"," "),{db}=await import("@stacksjs/database/runtime"),failedJob=(await db.selectFrom("failed_jobs").where("id","=",id).selectAll().execute())[0];if(!failedJob)throw Error(`Failed job ${id} not found`);const storedPayload=typeof failedJob.payload==="string"?failedJob.payload:"";let payloadToRequeue=storedPayload;try{const env=JSON.parse(storedPayload||"{}");env._retriedFromFailed=!0;payloadToRequeue=JSON.stringify(env)}catch{}await db.insertInto("jobs").values({queue:failedJob.queue,payload:payloadToRequeue,attempts:0,reserved_at:null,available_at:now,created_at:createdAt}).execute();await db.deleteFrom("failed_jobs").where("id","=",id).execute();log.info(`Failed job ${id} has been re-queued`)}export function getActiveJobCount(){return activeJobCount}export function isWorkerRunning(){return workerRunning}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}
1
+ import{persistWorkerSnapshot,pruneWorkerSnapshots}from"./worker-monitor";import{batchMembershipId}from"./batch-payload";import{resolveQueueDriver}from"./driver";import{err,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import process from"node:process";import{parseEnvelope}from"./envelope";import{updatedRowCount}from"./utils";import{captureProcessLeaseOwner,processLeaseOwnerStatus}from"./process-owner";let workerCrashHandlersInstalled=false;function installWorkerCrashHandlers(){if(workerCrashHandlersInstalled)return;workerCrashHandlersInstalled=true;process.on("unhandledRejection",(reason,_promise)=>{log.error(`Unhandled Rejection: ${reason}`)});process.on("uncaughtException",(error)=>{log.error(`Uncaught Exception: ${error.message}`)})}let activeJobCount=0;let workerRunning=false;let workerId="";const inFlightJobs=new Set;const inFlightDatabaseBatches=new Set;const reserveErrorLoggedAt=new Map;let reservationScanAfter=0;function ownedReservationPayload(payload){const owner=captureProcessLeaseOwner();if(!owner)return payload;try{const envelope=JSON.parse(payload);if(!envelope||typeof envelope!=="object"||Array.isArray(envelope))return payload;return JSON.stringify({...envelope,_queueProcessOwner:owner})}catch{return payload}}function trackInFlight(promise,pending=inFlightJobs){pending.add(promise);promise.then(()=>pending.delete(promise),()=>pending.delete(promise));return promise}function getReservationTtlSec(){const raw=process.env.STACKS_QUEUE_RESERVATION_TTL_SEC;const n=raw===undefined?Number.NaN:Number.parseInt(raw,10);return Number.isFinite(n)&&n>0?n:3600}function getRetryJitterRatio(){const raw=process.env.STACKS_QUEUE_RETRY_JITTER;if(raw===undefined)return 0.2;const n=Number(raw);if(!Number.isFinite(n)||n<0)return 0.2;return Math.min(n,1)}export function applyRetryJitter(delaySeconds,ratio,random=Math.random){if(!(delaySeconds>0)||ratio<=0)return delaySeconds;return Math.round(delaySeconds+delaySeconds*ratio*random())}function getSweepIntervalMs(){const raw=process.env.STACKS_QUEUE_SWEEP_INTERVAL_SEC;const n=raw===undefined?Number.NaN:Number.parseInt(raw,10);return(Number.isFinite(n)&&n>0?n:60)*1000}async function sweepStaleReservations(){const ttlSec=getReservationTtlSec();const cutoff=Math.floor(Date.now()/1000)-ttlSec;const now=Math.floor(Date.now()/1000);try{const{db}=await import("@stacksjs/database/runtime");const result=await db.updateTable("jobs").set({reserved_at:null,available_at:now}).where("reserved_at","<=",cutoff).executeTakeFirst();let requeued=updatedRowCount(result);const owned=await db.selectFrom("jobs").select(["id","payload","reserved_at"]).where("reserved_at",">",cutoff).where("id",">",reservationScanAfter).orderBy("id","asc").limit(128).execute();reservationScanAfter=owned.length===128?Number(owned.at(-1).id):0;for(const row of owned){let owner;try{owner=JSON.parse(String(row.payload))._queueProcessOwner}catch{continue}if(processLeaseOwnerStatus(owner)!=="dead")continue;const released=await db.updateTable("jobs").set({reserved_at:null,available_at:now}).where("id","=",row.id).where("reserved_at","=",row.reserved_at).where("payload","=",row.payload).executeTakeFirst();requeued+=updatedRowCount(released)}if(requeued>0){log.warn(`[queue] Requeued ${requeued} job(s) after their owner exited or their reservation exceeded the ${ttlSec}s TTL. Set STACKS_QUEUE_RESERVATION_TTL_SEC to tune.`)}return requeued}catch(error){log.error("[queue] Reservation sweep failed",{reason:error instanceof Error?error.message:String(error)});return 0}}function isNonRetryableError(e){if(!e||typeof e!=="object")return false;const status=e.status??e.statusCode;if(typeof status==="number"&&status>=400&&status<500)return true;const name=e.name;if(typeof name==="string"&&(name==="ValidationError"||name==="ModelNotFoundError"))return true;return false}function getQueueDriver(){return resolveQueueDriver()}async function monitorWorker(id){const{getWorkerTracker,getGlobalMetrics}=await import("./events");let writing;let warned=false;const persist=()=>{if(writing)return writing;const worker=getWorkerTracker().getAll().find((worker)=>worker.id===id);if(!worker)return Promise.resolve();const metrics=getGlobalMetrics().getMetrics();writing=persistWorkerSnapshot({worker:{...worker},heartbeatAt:Date.now(),activeJobs:getActiveJobCount(),metrics:{completed:worker.processedCount,failed:worker.failedCount,throughputPerMinute:metrics.throughputPerMinute,averageDuration:metrics.averageDuration}}).catch((error)=>{if(warned)return;warned=true;log.warn(`Queue worker telemetry unavailable. Run migrations for QueueWorker: ${error instanceof Error?error.message:String(error)}`)}).finally(()=>{writing=undefined});return writing};pruneWorkerSnapshots().catch(()=>{});persist();const timer=setInterval(()=>{persist()},1e4);timer.unref();return async()=>{clearInterval(timer);await writing;await persist()}}export async function startProcessor(queueName,options={}){let stopMonitor;let monitoredId;try{log.info("Starting queue processor...");installWorkerCrashHandlers();workerRunning=true;workerId=`worker-${process.pid}-${Date.now()}`;const concurrency=options.concurrency||1;const queueDriver=getQueueDriver();const{getWorkerTracker,getGlobalMetrics}=await import("./events");getGlobalMetrics();getWorkerTracker().register(workerId,queueName||"*");monitoredId=workerId;stopMonitor=await monitorWorker(monitoredId);if(queueDriver==="redis"){log.info("Using Redis queue driver (bun-queue)");await processJobsFromRedis(queueName||"default",concurrency);return ok(undefined)}const named=namedWorkerQueues(queueName);let queues;if(named.length>0){queues=named}else{queues=await getAllQueues();if(queues.length===0){queues=["default"]}}log.info(`Processing queues: ${queues.join(", ")}`);await processJobsFromDatabase(queues,concurrency,{followNewQueues:named.length===0});return ok(undefined)}catch(error){workerRunning=false;return err(error)}finally{const{getWorkerTracker}=await import("./events");if(monitoredId)getWorkerTracker().unregister(monitoredId);await stopMonitor?.()}}async function getAllQueues(){try{const{db}=await import("@stacksjs/database/runtime");const rows=await db.selectFrom("jobs").select("queue").distinct().execute();const queues=rows.map((r)=>r.queue).filter((q)=>Boolean(q));return queues.length>0?queues:["default"]}catch{return["default"]}}export function namedWorkerQueues(queueName){if(typeof queueName!=="string")return[];return[...new Set(queueName.split(",").map((name)=>name.trim()).filter(Boolean))]}async function processJobsFromDatabase(initialQueues,concurrency,options={followNewQueues:true}){log.info(`Listening for jobs...`);let queues=initialQueues;let lastQueueRefresh=Date.now();const queueRefreshInterval=1e4;let lastSweep=Date.now();const sweepIntervalMs=getSweepIntervalMs();await sweepStaleReservations();while(workerRunning){try{let processedJobs=false;const now=Date.now();if(options.followNewQueues&&now-lastQueueRefresh>queueRefreshInterval){try{const refreshedQueues=await getAllQueues();if(refreshedQueues.length>0){queues=refreshedQueues}}catch{}lastQueueRefresh=now}if(now-lastSweep>sweepIntervalMs){await sweepStaleReservations();lastSweep=now}for(const queueName of queues){if(!workerRunning)break;try{const{isCircuitOpen}=await import("./circuit-breaker");if(await isCircuitOpen(queueName))continue}catch{}if(!workerRunning)break;const processed=await trackInFlight(processDatabaseBatch(queueName,concurrency),inFlightDatabaseBatches);processedJobs||=processed}if(workerRunning&&!processedJobs)await sleep(1000)}catch{await sleep(3000)}}}async function processDatabaseBatch(queueName,concurrency){let jobs=[];try{jobs=await fetchPendingJobs(queueName,concurrency)}catch(error){const now=Date.now();const last=reserveErrorLoggedAt.get(queueName)??0;if(now-last>60000){reserveErrorLoggedAt.set(queueName,now);log.error(`[queue] Could not reserve jobs on "${queueName}" - retrying each cycle:`,error)}return false}await Promise.all(jobs.map(async(job)=>{try{log.info(`Processing job ${job.id} from queue "${queueName}"`);await trackInFlight(processJob(job))}catch{log.error(`Unexpected error processing job ${job.id}`)}}));return jobs.length>0}async function fetchPendingJobs(queueName,limit){const now=Math.floor(Date.now()/1000);const{db}=await import("@stacksjs/database/runtime");const claimed=[];for(let i=0;i<limit&&workerRunning;i++){const job=await db.selectFrom("jobs").where("queue","=",queueName).whereNull("reserved_at").where("available_at","<=",now).orderBy("id","asc").limit(1).selectAll().executeTakeFirst();if(!job||!workerRunning)break;const payload=ownedReservationPayload(String(job.payload));const result=await db.updateTable("jobs").set({reserved_at:now,attempts:Number(job.attempts||0)+1,payload}).where("id","=",job.id).whereNull("reserved_at").where("payload","=",job.payload).executeTakeFirst();const updated=updatedRowCount(result);if(updated>0){claimed.push({...job,payload})}}return claimed}async function processJob(job){const jobId=job.id;const queueName=job.queue||"default";activeJobCount++;const startTime=Date.now();const{emitQueueEvent,getWorkerTracker}=await import("./events");const tracker=getWorkerTracker();tracker.markActive(workerId);let parsedJobName;try{parsedJobName=JSON.parse(job.payload||"{}").jobName}catch{}await emitQueueEvent("job:processing",{jobId:String(jobId),queueName,jobName:parsedJobName});try{const parsedForBatch=JSON.parse(job.payload||"{}");const batchId=batchMembershipId(parsedForBatch.payload);if(batchId){const{isBatchCancelled}=await import("./batch");if(await isBatchCancelled(batchId)){log.info(`[Queue] Skipping job ${jobId} - batch ${batchId} has been cancelled`);await deleteJob(jobId);activeJobCount--;tracker.markIdle(workerId);return}}}catch{}let jobError=null;const declared=parsedJobName?await(await import("./job")).jobDefaults(parsedJobName):{};try{const payload=JSON.parse(job.payload||"{}");const timeoutSec=readJobTimeoutSec(payload)??declared.timeout;if(timeoutSec===undefined){await executeJobPayload(payload)}else{await raceWithTimeout(executeJobPayload(payload),timeoutSec*1000,`Job ${jobId} exceeded ${timeoutSec}s timeout`)}}catch(e){jobError=e instanceof Error?e:new Error(String(e))}if(!jobError){try{await deleteJob(jobId);log.info(`[Queue] Job ${jobId} completed`);tracker.recordCompletion(workerId);try{const{recordCircuitSuccess}=await import("./circuit-breaker");await recordCircuitSuccess(job.queue??"default")}catch{}await emitQueueEvent("job:completed",{jobId:String(jobId),queueName,duration:Date.now()-startTime});try{const payload=JSON.parse(job.payload||"{}");const batchId=batchMembershipId(payload.payload);if(batchId){const{recordBatchJobCompletion}=await import("./batch");await recordBatchJobCompletion(batchId)}}catch{}}catch{log.info(`[Queue] Failed to delete completed job ${jobId}`)}}else{const errorMessage=jobError.message;log.info(`[Queue] Job ${jobId} failed: ${errorMessage}`);tracker.recordFailure(workerId);await emitQueueEvent("job:failed",{jobId:String(jobId),queueName,error:jobError,duration:Date.now()-startTime,attemptsMade:(job.attempts||0)+1});let maxAttempts=1;let parsedPayload={};try{parsedPayload=JSON.parse(job.payload||"{}");maxAttempts=parsedPayload.options?.tries||declared.tries||1}catch{}const currentAttempts=(job.attempts||0)+1;if(currentAttempts>=maxAttempts){log.info(`[Queue] Job ${jobId} exceeded max attempts (${currentAttempts}/${maxAttempts})`);let persisted=false;if(parsedPayload?._retriedFromFailed===true){try{const{moveToDeadLetter}=await import("./dead-letter");persisted=await moveToDeadLetter({queue:job.queue,payload:job.payload,exception:jobError.stack||jobError.message},"repeat-failure",2);if(persisted)log.info(`[Queue] Job ${jobId} re-failed after retry - moved to dead_letter_jobs`)}catch{persisted=false}}if(!persisted){log.info(`[Queue] Moving job ${jobId} to failed_jobs`);try{persisted=await moveToFailedJobs(job,jobError,{attempts:currentAttempts,maxAttempts,durationMs:Date.now()-startTime})}catch{persisted=false}}if(persisted){try{await deleteJob(jobId)}catch{log.info(`[Queue] Failed to delete failed job ${jobId}`)}}else{log.error(`[Queue] Job ${jobId} exhausted its retries but could NOT be persisted to failed_jobs - leaving it in the queue to avoid data loss (the reservation sweep will retry it). Check that the failed_jobs table exists and is writable.`)}try{const{recordFailureForPoison}=await import("./poison");const{recordCircuitFailure}=await import("./circuit-breaker");const jobName=parsedPayload?.jobName??"unknown";await recordFailureForPoison(jobName,parsedPayload?.payload);await recordCircuitFailure(job.queue??"default")}catch{}try{const batchId=batchMembershipId(parsedPayload.payload);if(batchId){const{recordBatchJobFailure}=await import("./batch");await recordBatchJobFailure(batchId,String(jobId),jobError)}}catch{}}else{const backoffDelays=parsedPayload.options?.backoff??declared.backoff;let retryDelay=30;if(Array.isArray(backoffDelays)&&backoffDelays.length>0){const backoffIndex=Math.min(currentAttempts-1,backoffDelays.length-1);retryDelay=backoffDelays[backoffIndex]}else if(typeof backoffDelays==="number"&&backoffDelays>0){retryDelay=backoffDelays}retryDelay=Number(retryDelay);if(!Number.isFinite(retryDelay)||retryDelay<0)retryDelay=30;retryDelay=applyRetryJitter(retryDelay,getRetryJitterRatio());log.info(`[Queue] Job ${jobId} will be retried in ${retryDelay}s (attempt ${currentAttempts}/${maxAttempts})`);try{await releaseJob(jobId,retryDelay);log.info(`[Queue] Job ${jobId} released for retry`)}catch{log.info(`[Queue] Failed to release job ${jobId} for retry`)}}}activeJobCount--;tracker.markIdle(workerId)}async function deleteJob(jobId){const{db}=await import("@stacksjs/database/runtime");await db.deleteFrom("jobs").where("id","=",jobId).execute()}async function releaseJob(jobId,delaySeconds=30){const retryAt=Math.floor(Date.now()/1000)+delaySeconds;log.debug(`Releasing job ${jobId} for retry at ${retryAt}`);try{const{db}=await import("@stacksjs/database/runtime");await db.updateTable("jobs").set({reserved_at:null,available_at:retryAt}).where("id","=",jobId).execute();log.debug(`Job ${jobId} released successfully`)}catch{log.error(`Failed to release job ${jobId}`)}}async function moveToFailedJobs(job,error,metrics){try{const failedAt=new Date().toISOString().slice(0,19).replace("T"," ");const uuid=crypto.randomUUID();const exception=error.stack||error.message;const{db}=await import("@stacksjs/database/runtime");await db.insertInto("failed_jobs").values({uuid,connection:"database",queue:job.queue,payload:job.payload,exception,attempts:metrics.attempts,max_attempts:metrics.maxAttempts,duration_ms:metrics.durationMs,failed_at:failedAt}).execute();return true}catch(insertError){log.error("Failed to log failed job:",insertError);return false}}function readJobTimeoutSec(payload){if(!payload||typeof payload!=="object")return;const opts=payload.options;const t=opts?.timeout;if(typeof t!=="number"||!Number.isFinite(t)||t<=0)return;return t}async function raceWithTimeout(task,timeoutMs,message){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)});try{return await Promise.race([task,timeout])}finally{if(timer!==undefined)clearTimeout(timer)}}async function executeJobPayload(payload){const parsed=parseEnvelope(payload);if(!parsed.ok){throw new Error(`[queue] Cannot deserialize job envelope: ${parsed.reason}`+(parsed.detail?` (${parsed.detail})`:""))}const{runJob}=await import("./job");await runJob(parsed.envelope.jobName,{payload:parsed.envelope.payload,context:parsed.envelope.context,traceId:parsed.envelope.traceId})}async function processJobsFromRedis(queueName,concurrency){const{RedisQueue}=await import("./drivers/redis");const{queue:queueConfig}=await import("@stacksjs/config");const redisConfig=queueConfig?.connections?.redis;if(!redisConfig){throw new Error("Redis queue connection is not configured. Check config/queue.ts")}const queue=new RedisQueue(queueName,redisConfig);const{emitQueueEvent,getWorkerTracker}=await import("./events");const tracker=getWorkerTracker();const handleRedisJob=async(bunJob)=>{activeJobCount++;tracker.markActive(workerId);const startTime=Date.now();const parsed=parseEnvelope(bunJob.data);if(!parsed.ok){activeJobCount--;tracker.markIdle(workerId);log.error(`[Queue] Skipping Redis job ${bunJob.id} - unparseable envelope: ${parsed.reason}${parsed.detail?` (${parsed.detail})`:""}`);return}const data=parsed.envelope;const batchId=batchMembershipId(data.payload);if(batchId){try{const{isBatchCancelled}=await import("./batch");if(await isBatchCancelled(batchId)){log.info(`[Queue] Skipping Redis job ${bunJob.id} - batch ${batchId} has been cancelled`);activeJobCount--;tracker.markIdle(workerId);return}}catch{}}await emitQueueEvent("job:processing",{jobId:String(bunJob.id),queueName});try{const{runJob}=await import("./job");await runJob(data.jobName,{payload:data.payload,context:data.context,traceId:data.traceId});tracker.recordCompletion(workerId);await emitQueueEvent("job:completed",{jobId:String(bunJob.id),queueName,duration:Date.now()-startTime});if(batchId){try{const{recordBatchJobCompletion}=await import("./batch");await recordBatchJobCompletion(batchId)}catch{}}log.info(`[Queue] Redis job ${bunJob.id} completed`)}catch(e){tracker.recordFailure(workerId);await emitQueueEvent("job:failed",{jobId:String(bunJob.id),queueName,error:e instanceof Error?e:new Error(String(e)),duration:Date.now()-startTime});if(batchId){try{const{recordBatchJobFailure}=await import("./batch");await recordBatchJobFailure(batchId,String(bunJob.id),e instanceof Error?e:new Error(String(e)))}catch{}}log.error(`[Queue] Redis job ${bunJob.id} failed: ${e}`);if(isNonRetryableError(e)){log.info(`[Queue] Redis job ${bunJob.id} hit a non-retryable error - skipping retry`);return}throw e}finally{activeJobCount--;tracker.markIdle(workerId)}};queue.process(concurrency,(bunJob)=>trackInFlight(handleRedisJob(bunJob)));log.info(`Listening for Redis jobs on queue "${queueName}" with concurrency ${concurrency}...`);while(workerRunning){await sleep(1000)}await queue.close()}export async function stopProcessor(options={}){const graceMs=options.graceMs??1e4;workerRunning=false;const pending=new Set([...inFlightDatabaseBatches,...inFlightJobs]);if(pending.size>0&&graceMs>0){log.info(`[queue] Draining database reservations and in-flight jobs (grace ${graceMs}ms)`);const drain=Promise.allSettled([...pending]);const timeout=new Promise((resolve)=>setTimeout(()=>resolve("timeout"),graceMs));const outcome=await Promise.race([drain.then(()=>"drained"),timeout]);if(outcome==="timeout"&&(inFlightJobs.size>0||inFlightDatabaseBatches.size>0)){log.warn(`[queue] Drain timed out with reservations or jobs still active. Their reservations will be reclaimed by the next worker's sweep (Q-2).`)}}if(workerId){const{getWorkerTracker}=await import("./events");getWorkerTracker().unregister(workerId)}if(getQueueDriver()==="redis"){const{closeSharedRedisQueues}=await import("./drivers/redis");await closeSharedRedisQueues()}log.info("Queue processor stopped")}export async function executeFailedJobs(){const{db}=await import("@stacksjs/database/runtime");const failedJobs=await db.selectFrom("failed_jobs").selectAll().execute();for(const failedJob of failedJobs){await retryFailedJob(Number(failedJob.id))}}export async function retryFailedJob(id){const now=Math.floor(Date.now()/1000);const createdAt=new Date().toISOString().slice(0,19).replace("T"," ");const{db}=await import("@stacksjs/database/runtime");const failedJobs=await db.selectFrom("failed_jobs").where("id","=",id).selectAll().execute();const failedJob=failedJobs[0];if(!failedJob){throw new Error(`Failed job ${id} not found`)}const storedPayload=typeof failedJob.payload==="string"?failedJob.payload:"";let payloadToRequeue=storedPayload;try{const env=JSON.parse(storedPayload||"{}");env._retriedFromFailed=true;payloadToRequeue=JSON.stringify(env)}catch{}await db.insertInto("jobs").values({queue:failedJob.queue,payload:payloadToRequeue,attempts:0,reserved_at:null,available_at:now,created_at:createdAt}).execute();await db.deleteFrom("failed_jobs").where("id","=",id).execute();log.info(`Failed job ${id} has been re-queued`)}export function getActiveJobCount(){return activeJobCount}export function isWorkerRunning(){return workerRunning}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/queue",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.514",
5
+ "version": "0.75.518",
6
6
  "description": "The Stacks Queue system powered by bun-queue.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -63,23 +63,23 @@
63
63
  "prepublishOnly": "bun run build"
64
64
  },
65
65
  "dependencies": {
66
- "@stacksjs/action-runner": "0.75.514",
66
+ "@stacksjs/action-runner": "0.75.518",
67
67
  "@stacksjs/bun-queue": "^0.1.8",
68
- "@stacksjs/cache": "0.75.514",
69
- "@stacksjs/config": "0.75.514",
70
- "@stacksjs/cron": "0.75.514",
71
- "@stacksjs/database": "0.75.514",
72
- "@stacksjs/env": "0.75.514",
73
- "@stacksjs/error-handling": "0.75.514",
74
- "@stacksjs/logging": "0.75.514",
75
- "@stacksjs/path": "0.75.514"
68
+ "@stacksjs/cache": "0.75.518",
69
+ "@stacksjs/config": "0.75.518",
70
+ "@stacksjs/cron": "0.75.518",
71
+ "@stacksjs/database": "0.75.518",
72
+ "@stacksjs/env": "0.75.518",
73
+ "@stacksjs/error-handling": "0.75.518",
74
+ "@stacksjs/logging": "0.75.518",
75
+ "@stacksjs/path": "0.75.518"
76
76
  },
77
77
  "devDependencies": {
78
78
  "better-dx": "^0.2.24"
79
79
  },
80
80
  "peerDependencies": {
81
- "@stacksjs/email": "0.75.514",
82
- "@stacksjs/router": "0.75.514"
81
+ "@stacksjs/email": "0.75.518",
82
+ "@stacksjs/router": "0.75.518"
83
83
  },
84
84
  "peerDependenciesMeta": {
85
85
  "@stacksjs/email": {