import { resolveQueueDriver } from './driver' /** * Stacks Job Helper * * Simple helper for dispatching file-based jobs from app/Jobs/*.ts * For class-based jobs, use bun-queue's JobBase directly. */ import { basename } from 'node:path' import { appPath, frameworkPath } from '@stacksjs/path' import { enqueueAfterCommit, isInTransaction } from '@stacksjs/database/runtime' import type { Job } from './action' import { moveToDeadLetter } from './dead-letter' import { assertEnvelopeSerializable, createEnvelope, serializeEnvelope } from './envelope' import { claimDispatchKey, releaseDispatchKey } from './idempotency' import { isMissingTableError, missingJobsTableError } from './missing-table' import { isQuarantined } from './poison' import { runNamedAction } from './action-runner' let testingModule: Promise | undefined let databaseModule: Promise | undefined let traceModule: Promise | undefined function loadTraceModule(): Promise { return traceModule ??= import('@stacksjs/router').catch((error) => { traceModule = undefined throw error }) } function getQueueDriver(): string { return resolveQueueDriver() } /** * One-shot warning when a caller asks for `.afterCommit()` outside * any active transaction (stacksjs/stacks#1882). The dispatch still * fires immediately — silently rewriting the caller's intent would * be worse than the noise. */ let _warnedAfterCommitNoTx = false function warnAfterCommitOutsideTransaction(): void { if (_warnedAfterCommitNoTx) return _warnedAfterCommitNoTx = true // eslint-disable-next-line no-console 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.', ) } /** * Options for job dispatch */ export interface JobDispatchOptions { /** Queue name to dispatch to */ queue?: string /** Delay in seconds before processing */ delay?: number /** Number of retry attempts */ tries?: number /** Timeout in seconds */ timeout?: number /** Backoff delays in seconds */ backoff?: number[] /** Additional context */ context?: any /** * Caller-supplied idempotency key (stacksjs/stacks#1872 Q-8). * * When set, `dispatch()` consults the `job_idempotency` dedup * table before enqueuing. A second dispatch with the same key * is a no-op — the framework returns without re-pushing to the * queue. Closes the duplicate-job loophole that double-clicked * buttons and webhook-retry loops opened. * * Construction guidance: derive the key from the business event * (e.g. `process-order:${orderId}`, * `send-welcome:${userId}`), not from job-name + payload (which * would collide across unrelated dispatches and prevent legitimate * re-runs). */ idempotencyKey?: string } /** * Per-builder override of the transaction-context default. * `'auto'` (the default) respects the current transaction scope: * buffers when inside `db.transaction(...)`, dispatches immediately * otherwise. `'after'` forces buffering even outside a transaction * (warn-and-dispatch since there's nothing to buffer against). * `'immediate'` forces immediate dispatch even inside a transaction * — used for fire-and-forget side-effects that legitimately want * to run before the surrounding transaction commits (analytics, * lock probes, etc.). * * See stacksjs/stacks#1882. */ type TransactionMode = 'auto' | 'after' | 'immediate' /** * Fluent job builder for file-based jobs */ class JobBuilder { private options: JobDispatchOptions = {} private txMode: TransactionMode = 'auto' constructor( private name: string, private payload?: unknown, ) {} /** * Set the queue name */ onQueue(queue: string): this { this.options.queue = queue return this } /** * Set delay before processing (in seconds) */ delay(seconds: number): this { this.options.delay = seconds return this } /** * Set number of retry attempts */ tries(count: number): this { this.options.tries = count return this } /** * Set timeout (in seconds) */ timeout(seconds: number): this { this.options.timeout = seconds return this } /** * Set backoff delays (in seconds) */ backoff(delays: number[]): this { this.options.backoff = delays return this } /** * Add context to the job */ withContext(context: any): this { this.options.context = context return this } /** * Attach an idempotency key so duplicate dispatches are * deduplicated against the `job_idempotency` table * (stacksjs/stacks#1872 Q-8). See {@link JobDispatchOptions.idempotencyKey} * for construction guidance. */ withIdempotencyKey(key: string): this { this.options.idempotencyKey = key return this } /** * Force the dispatch to be buffered until the surrounding * `db.transaction(...)` commits (stacksjs/stacks#1882). Inside a * transaction this is the default behaviour; calling * `.afterCommit()` is mostly useful for documentation. Outside a * transaction the dispatch happens immediately and a one-shot * warning logs — the caller probably wanted the buffering they * asked for, so silently changing semantics is worse than the * noise. */ afterCommit(): this { this.txMode = 'after' return this } /** * Force the dispatch to fire IMMEDIATELY even inside a * `db.transaction(...)` (stacksjs/stacks#1882). Use for * side-effects that genuinely want to run before commit: * - analytics events (must fire regardless of commit outcome) * - distributed lock probes * - log entries the caller wants visible even if the tx * rolls back so they can audit the failed attempt */ withoutCommit(): this { this.txMode = 'immediate' return this } /** * Dispatch the job to the queue */ async dispatch(): Promise { // Check if queue is faked (testing mode) const { isFaked, getFakeQueue } = await (testingModule ??= import('./testing').catch((error) => { testingModule = undefined throw error })) if (isFaked()) { getFakeQueue()?.dispatch(this.name, this.payload, this.options) return } // Transaction-aware buffering (stacksjs/stacks#1882). When the // dispatch happens inside `db.transaction(...)`, defer it until // commit so the worker can't pick up a job whose data hasn't // been written yet. `.withoutCommit()` opts out; `.afterCommit()` // forces buffering (no-op when already inside a transaction). // // Outside any transaction, `auto` falls through to immediate // dispatch. `after` warns once and dispatches anyway — caller // asked for "after commit" without a commit to wait on; silently // dropping their intent would surprise them. if (this.txMode !== 'immediate') { const inTx = isInTransaction() if (inTx) { // Buffer — capture `this` state into a closure since the // builder might be reused (it shouldn't be, but defending // against a fluent-API misuse costs nothing). const buffered = this.runDispatchPipeline.bind(this) const enqueued = enqueueAfterCommit(async () => { await buffered() }) // Defensive: enqueueAfterCommit returned false means the // scope vanished between `isInTransaction()` and now (can // happen if the user manually escapes the ALS context via // `.bind(null)` etc.). Fall through to immediate dispatch. if (enqueued) return } else if (this.txMode === 'after') { warnAfterCommitOutsideTransaction() } } await this.runDispatchPipeline() } /** * The driver-routing portion of dispatch — extracted from * `dispatch()` so the transaction-buffering wrapper can call it * either immediately or via the after-commit hook * (stacksjs/stacks#1882). */ private async runDispatchPipeline(): Promise { // Resolve a by-name job's declared route before deduplication, quarantine // or driver selection. An explicit onQueue(), including "default", wins. if (this.options.queue === undefined) this.options.queue = (await jobDefaults(this.name)).queue // Idempotency-key claim (stacksjs/stacks#1872 Q-8, hardened in #1984). We // INSERT the dedup row UP FRONT and let the UNIQUE constraint be the gate, // instead of the old check-then-act (SELECT → dispatch → INSERT), under // which two concurrent dispatches both passed the SELECT and both enqueued // — the exact double-dispatch the key exists to prevent. `duplicate` means // someone else already claimed it → skip. `unenforced` means the table // isn't migrated → dedup off, proceed (opt-in degrade). On a `claimed` // key we release it if the dispatch below throws, preserving the "failed // dispatches are not recorded" contract so a retry can re-claim. 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 { // Quarantine short-circuit (stacksjs/stacks#1885 / #1984). A job+payload // that a poison-detector or an operator (`queue:quarantine`) has // quarantined skips the queue and lands directly in the DLQ, instead of // being enqueued to churn through retry→fail→retry. Opt-in: if the DLQ // table isn't migrated, `moveToDeadLetter` returns false and we fall // through to a normal dispatch (quarantine stays inert until migrated). // A quarantined job that lands in the DLQ keeps its claimed key — it WAS // handled, so a re-dispatch under the same key should still skip. 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') { /* * The ambient trace, carried explicitly. * * `runJob` mints an id when it is not given one, and minting *replaces* * the caller's - so a job run inline under a request logged under a * different id from the request that ran it, which is the one case * where the connection is trivially available and was being thrown * away. */ await runJob(this.name, { payload: this.payload, context: this.options.context, traceId: await currentTraceId(), }) } else if (driver === 'sqs' || driver === 'memory' || driver === 'beanstalkd') { // Listed in config schemas but never implemented (stacksjs/stacks#1872 Q-1). // The previous fallback ran the job inline via `runJob` — same behavior // as `sync` but without telling the caller their background pipeline // had silently degraded to blocking sends. Loud-fail instead. throw new Error( `[queue] Driver "${driver}" is not implemented yet. ` + `Set QUEUE_DRIVER to one of: redis, database, sync.`, ) } else { // Genuinely unknown driver — also loud-fail. A typo in QUEUE_DRIVER // used to silently run jobs synchronously, which is the worst kind // of "it works on my machine" surprise. throw new Error( `[queue] Unknown QUEUE_DRIVER "${driver}". ` + `Allowed values: redis, database, sync.`, ) } } catch (err) { // Compensate: a failed dispatch must not leave the key claimed, or a // legitimate retry with the same key would be wrongly deduped. if (claimedKey && this.options.idempotencyKey) await releaseDispatchKey(this.options.idempotencyKey) throw err } } /** * Dispatch only if the condition is true */ async dispatchIf(condition: boolean): Promise { if (condition) { await this.dispatch() } } /** * Dispatch unless the condition is true */ async dispatchUnless(condition: boolean): Promise { if (!condition) { await this.dispatch() } } /** * Dispatch the job to the database queue */ private async dispatchToDatabase(): Promise { const now = Math.floor(Date.now() / 1000) const availableAt = this.options.delay ? now + this.options.delay : now // Unified envelope (stacksjs/stacks#1884 Q-6). Both database // and redis drivers write through `createEnvelope` so a worker // processing one driver can deserialize jobs queued under the // other — fixes the silent in-flight job loss when teams // switch QUEUE_DRIVER mid-flight. 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) // `serializeEnvelope` rather than a bare `JSON.stringify` // (stacksjs/stacks#2282 item 6): a BigInt anywhere in the payload throws // from inside JSON naming neither the job nor the property, which is a // hard error to act on when it arrives from a dispatch three call frames // away. See the round-trip contract there for what else JSON costs a // payload — `undefined` dropped, `Date` flattened to a string. // // Serialized before the database module is loaded, so a payload that can // never be written costs nothing to reject. const payloadJson = serializeEnvelope(envelope) const { db } = await (databaseModule ??= import('@stacksjs/database/runtime').catch((error) => { databaseModule = undefined throw error })) try { 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() } catch (error) { // Said in words that carry the fix: this is read in a log, by someone // wondering why an email never arrived, not by the code that dispatched. if (isMissingTableError(error)) throw missingJobsTableError(this.name, error) throw error } } /** * Dispatch the job to Redis via bun-queue */ private async dispatchToRedis(): Promise { // Same envelope shape as the database driver writes // (stacksjs/stacks#1884 Q-6). bun-queue's `Queue.add(data, opts)` // takes `data` as opaque `T` — wrapping the framework envelope // inside is transparent to bun-queue. Options stay on bun-queue's // separate opts arg AND inside the envelope so a worker reading // the envelope sees the same retry/timeout/backoff config the // bun-queue layer is already enforcing. // // The trace id too, as the database driver carries it: a job queued on // Redis logged under an id of its own. 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) /* * bun-queue stringifies `data` itself, several layers down, so an * unserializable payload surfaces there as the bare TypeError this guard * exists to replace (stacksjs/stacks#2282 item 6). * * Checked HERE, at the top: the first cut sat below `new RedisQueue(...)` * while claiming to spare the caller a failure that arrives "only after * the Redis connection is open" — which the placement made false. Nothing * in the check needs the driver, the config, or a socket, so it runs * before all three. It costs one throwaway serialize of a dispatch-sized * object, which is noise next to the round trip below. */ assertEnvelopeSerializable(envelope) const { sharedRedisQueue } = await import('./drivers/redis') const { queue: queueConfig } = await import('@stacksjs/config') // `queueConfig` is typed as `StacksOptions['queue']` already — the // previous `as any` cast (stacksjs/stacks#1875 T-6) escaped that // typing so a config-shape rename would silently break here. 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 as Parameters[1]) await queue.add( envelope, { delay: this.options.delay, maxTries: this.options.tries, timeout: this.options.timeout, backoff: this.options.backoff, }, ) } /** * Dispatch the job synchronously (immediate execution) */ async dispatchNow(): Promise { await runJob(this.name, { payload: this.payload, context: this.options.context, }) } } /** * Create a job builder for dispatching file-based jobs * * @example * ```typescript * // Basic dispatch * await job('SendWelcomeEmail', { userId: 1 }).dispatch() * * // With options * await job('ProcessOrder', { orderId: 123 }) * .onQueue('orders') * .tries(3) * .backoff([10, 30, 60]) * .dispatch() * * // Immediate execution * await job('SendNotification', { message: 'Hello' }).dispatchNow() * ``` */ /** * Augmentation target: every job that can be dispatched by name. * * The keys are job filenames without the extension - `'SendWelcomeEmail'`, * `'SendPasswordResetEmailJob'` - under `app/Jobs/` or the framework defaults * behind it. Filled by `storage/framework/types/registries.d.ts` from the jobs * barrel, which covers the same directories {@link resolveJobFile} searches. */ // eslint-disable-next-line ts/no-empty-object-type -- augmentation target; empty by design export interface Jobs {} /** * A job name, as narrow as the application has made it. * * Falls back to `string` while the registry is empty, so a project that has not * run `generate:types` yet still compiles. Once it is filled, * `job('SendWelcomeEmial')` is a compile error rather than a dispatch that * resolves to nothing. */ export type JobName = keyof Jobs extends never ? string : RegisteredJobName | WithoutJobSuffix type RegisteredJobName = keyof Jobs & string /** * `'SendEmailJob'` → `'SendEmail'`, the other spelling {@link resolveJobFile} * finds a job under. * * The runtime tries `.ts` and then `Job.ts`, because the mailer * dispatches `SendEmail` while the framework ships `SendEmailJob.ts`. The type * only knew the file names, so `job('SendEmail')` - what `mail.queue()` does, * and what the framework's own tests call - was a compile error in every app * whose registry had been filled. A generic, so it distributes over the union. */ type WithoutJobSuffix = T extends `${infer Base}Job` ? (Base extends '' ? never : Base) : never /** * The payload the named job's handler declares. * * The jobs registry is a real re-export barrel rather than a name-to-path map, * so `Jobs[N]` is the job instance itself and its payload type can be read off * it. Dispatching by name therefore gets the same checking as importing the * job and calling `.dispatch()` - which matters more here, because by-name is * the form that cannot be caught by a rename. * * Falls back to `unknown` for a job that declares no payload, and for any name * while the registry is empty. */ export type JobPayload = N extends keyof Jobs ? PayloadOf // The suffix-less spelling, resolved the way the runtime does: `.ts` // first (the branch above), then `Job.ts`. : `${N}Job` extends keyof Jobs ? PayloadOf : unknown type PayloadOf = J extends Job ? P : unknown export function job(name: N, payload?: JobPayload): JobBuilder { return new JobBuilder(name, payload) } /** * Laravel-style static facade for the file-based job dispatcher. The * existing `Job` class (in ./action.ts) is the *declaration* form used * inside `app/Jobs/*.ts`; this `Jobs` facade is the *call-site* form for * dispatching by name from anywhere in the app. It lets one-liner * dispatches skip the builder while still allowing the chainable form * via `Jobs.make(...)` for option-heavy cases. * * @example * ```typescript * // One-shot dispatch (no options) * await Jobs.dispatch('SendWelcomeEmail', { userId: 1 }) * * // Conditional dispatch * await Jobs.dispatchIf(user.isNew, 'SendWelcomeEmail', { userId: user.id }) * * // With options — fall back to the builder * await Jobs.make('ProcessOrder', { orderId: 123 }) * .onQueue('orders') * .tries(3) * .dispatch() * * // Immediate (synchronous) execution, ignoring the queue * await Jobs.dispatchNow('SendNotification', { message: 'Hello' }) * ``` */ export const Jobs = { /** Construct a builder without dispatching — for chained option calls. */ make(name: N, payload?: JobPayload): JobBuilder { return new JobBuilder(name, payload) }, /** Dispatch a job in one call. Equivalent to `job(name, payload).dispatch()`. */ async dispatch(name: N, payload?: JobPayload): Promise { await new JobBuilder(name, payload).dispatch() }, /** Dispatch only if `condition` is truthy. */ async dispatchIf(condition: boolean, name: N, payload?: JobPayload): Promise { if (condition) await new JobBuilder(name, payload).dispatch() }, /** Dispatch unless `condition` is truthy. */ async dispatchUnless(condition: boolean, name: N, payload?: JobPayload): Promise { if (!condition) await new JobBuilder(name, payload).dispatch() }, /** Run the job synchronously, bypassing the queue. */ async dispatchNow(name: N, payload?: JobPayload): Promise { await new JobBuilder(name, payload).dispatchNow() }, /** Schedule the job to run after `seconds` of delay. */ dispatchAfter(seconds: number, name: N, payload?: JobPayload): JobBuilder { return new JobBuilder(name, payload).delay(seconds) }, /** * Dispatch with an idempotency key in one call * (stacksjs/stacks#1872 Q-8). Equivalent to * `Jobs.make(name, payload).withIdempotencyKey(key).dispatch()`. */ async dispatchOnce(key: string, name: N, payload?: JobPayload): Promise { await new JobBuilder(name, payload).withIdempotencyKey(key).dispatch() }, /** * Explicitly defer to the surrounding transaction's commit * (stacksjs/stacks#1882). Equivalent to * `Jobs.make(name, payload).afterCommit().dispatch()`. Inside a * `db.transaction(...)` this is the default behaviour — the * helper exists for callers that want the intent visible at the * call site for readability. */ async dispatchAfterCommit(name: N, payload?: JobPayload): Promise { await new JobBuilder(name, payload).afterCommit().dispatch() }, } /** * Create a job batch for dispatching multiple jobs together * * @example * ```typescript * import SendWelcomeEmail from '~/app/Jobs/SendWelcomeEmail' * import ProcessOrder from '~/app/Jobs/ProcessOrder' * * const batch = await jobBatch([ * { job: SendWelcomeEmail, payload: { email: 'user@example.com' } }, * { job: ProcessOrder, payload: { orderId: 123 } }, * ]) * .name('Onboard User') * .allowFailures() * .then(async (_b) => console.log('All done!')) * .dispatch() * ``` */ export function jobBatch(jobs: Array): import('./batch').PendingBatch { // Use inline require for synchronous access - batch module is local // eslint-disable-next-line ts/no-require-imports const { PendingBatch } = require('./batch') as typeof import('./batch') return new PendingBatch(jobs) } /** * Locate a job file by name, userland first. * * Actions resolve by string out of the framework defaults; jobs did not, so a * framework-shipped action that dispatched a framework-shipped job by name * could never find it. The default password-reset flow is exactly that shape — * `SendPasswordResetEmailAction` resolves from `@stacksjs/defaults`, then calls * `job('SendPasswordResetEmailJob')`, which looked only in the app's own * `app/Jobs/`. In a stock app that directory holds a `.gitkeep`, so password * reset silently sent nothing (stacksjs/stacks#2225). * * The three candidates mirror `resolveActionFile`: * 1. `app/Jobs/.ts` — userland always wins * 2. `storage/framework/defaults/app/Jobs/…` — vendored framework checkout * 3. `@stacksjs/defaults`'s copy of the same — framework-as-dependencies * * (3) resolves the package root through `package.json` and joins the subpath by * hand rather than importing `@stacksjs/defaults/app/Jobs/`, for the * reason documented on `resolveActionFile`: the `./*` exports map rewrites the * subpath under the `bun` condition and does not land on the file. * * A job is also found by the `name` it declares, in the same three places, * when no file is called that. The name is optional and defaults to the file * name, but a job that sets one - the scaffold's `ExampleJob.ts` says * `name: 'Example Job'` - is dispatched under it: `new Job({...}).dispatch()` * writes it into the envelope, and the scheduler's `rate` runner scheduled it * by it. The worker then looked for `app/Jobs/Example Job.ts` and failed every * run of a job that was sitting right there. */ export async function resolveJobFile(name: string): Promise { // `SendEmail`, then `SendEmailJob`. The mailer dispatches `SendEmail` // (`mail.queue()` and friends) while the framework ships its handler as // `SendEmailJob.ts`, so looking up only `${name}.ts` failed every queued // email with "Job SendEmail not found" in every app. Each place is tried // with both spellings before the next, so an app's own copy still wins. 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: string | undefined try { const pkgUrl = import.meta.resolve('@stacksjs/defaults/package.json') packageRoot = new URL('.', pkgUrl).pathname } catch { /* not installed in this layout */ } 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 } /** Each job directory's declared names, read once per process. */ const declaredNamesByDirectory = new Map>>() /** * The jobs in `directory` that declare a `name` other than their file name, * by that name. Two files declaring one name is an error, since a dispatch * under it could mean either. */ function declaredJobNames(directory: string): Promise> { 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: unknown try { declared = ((await import(file)).default as { name?: unknown } | undefined)?.name } catch { // A job that cannot load fails when it is run by its file name, // with its own error; it has no declared name to offer here. 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 })() // A failed scan is not remembered, so the next lookup reports it again. index.catch(() => declaredNamesByDirectory.delete(directory)) declaredNamesByDirectory.set(directory, index) } return index } /** Forget the declared-name index, after job files change. */ export function clearJobNameIndex(): void { declaredNamesByDirectory.clear() } /** * What a job's own definition says about retrying it, for a dispatch that * did not. * * A job dispatched by name inherits its declared queue unless explicitly routed. * A job dispatched by name - `mail.queue()` sending `SendEmailJob`, a * `Queue.dispatch('X')` - carried none of the `tries`, `backoff` or * `timeout` the job declares, and the worker defaulted to one attempt. A * transient SMTP failure sent the email straight to failed_jobs although the * job asks for three tries with 10/30/60s backoff. The worker reads these * when the envelope is silent; anything set on the dispatch still wins. */ export async function jobDefaults(name: string): Promise<{ queue?: string, tries?: number, backoff?: number | number[], timeout?: number }> { try { const jobPath = await resolveJobFile(name) if (!jobPath) return {} const definition = (await import(jobPath)).default as { queue?: unknown, tries?: unknown, backoff?: unknown, timeout?: unknown } | undefined 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 as number | number[] : undefined, } } catch { return {} } } /** * Run a job immediately by name * * This loads the job from app/Jobs/{name}.ts, falling back to the framework * defaults, and executes it * * Wraps execution in `withTraceId(...)` so log lines, db queries, and * downstream HTTP calls emitted from inside the job carry the same * trace id as the request (or a fresh one for cron-triggered runs). * `options.traceId` lets dispatchers attach a parent id explicitly; * absent that, we mint one of the form `job::` so * background work is at least correlatable to itself. */ export async function runJob(name: string, options: { payload?: any; context?: any; traceId?: string } = {}): Promise { 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) // Named explicitly rather than letting `import(undefined)` throw a module // resolution error: the fix for a missing job is to create it or correct // the name, and the old message pointed only at the app directory even // when the job was meant to come from the framework. 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`) } }) } /** * The trace id of whatever is dispatching, if anything is. * * Read at dispatch rather than at run, because a worker is another process and * the AsyncLocalStorage the trace lives in during a request cannot reach it. * The id has to be written into the row. * * Never throws. A trace id is a debugging aid, and failing a dispatch because * one could not be read would trade a real feature for a diagnostic. */ async function currentTraceId(): Promise { try { const { getTraceId } = await loadTraceModule() return getTraceId() } catch { return undefined } }