@open-mercato/queue-provider-local 0.0.0-stage → 0.11.1-develop.8983.1.8f477e3f83

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.
@@ -0,0 +1,1279 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+ import { createLogger } from '@open-mercato/shared/lib/logger'
6
+ import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
7
+ import type {
8
+ Queue,
9
+ QueuedJob,
10
+ JobHandler,
11
+ LocalQueueOptions,
12
+ ProcessOptions,
13
+ ProcessResult,
14
+ EnqueueOptions,
15
+ QueueJobScope,
16
+ QueueProcessingStats,
17
+ InFlightJobSummary,
18
+ RecentJob,
19
+ } from '@open-mercato/queue-provider-kit/types'
20
+ import { resolveCoalesceKey } from '@open-mercato/queue-provider-kit/coalescing'
21
+ import { attachTraceMetadata, runJobInTrace } from '@open-mercato/queue-provider-kit/tracing'
22
+ import {
23
+ QueueIntrospectionUnavailableError,
24
+ resolveJobType,
25
+ resolveOffset,
26
+ resolveWindowSize,
27
+ } from '@open-mercato/queue-provider-kit/introspection'
28
+ import { publishWithTimeout, validateEnqueueOptions } from '@open-mercato/queue-provider-kit/publication'
29
+ import { resolveLocalQueueBaseDir } from './base-dir'
30
+
31
+ const packageLogger = createLogger('queue')
32
+
33
+ type LocalState = {
34
+ lastProcessedId?: string
35
+ completedCount?: number
36
+ failedCount?: number
37
+ }
38
+
39
+ /**
40
+ * The enqueue that arrived while its coalescing twin was already running, parked on that twin's
41
+ * record until it finishes. At most one exists per record: a later arrival overwrites it, so the
42
+ * follow-up run always carries the latest payload.
43
+ *
44
+ * It keeps the id minted for the latest enqueue in the active burst, matching BullMQ's stored
45
+ * proto-job. The caller receives the active job's id because that is the outstanding job BullMQ
46
+ * reports for a deduplicated add; the follow-up id is internal until the job is promoted.
47
+ */
48
+ type CoalescedNextJob<T> = {
49
+ id: string
50
+ payload: T
51
+ createdAt: string
52
+ metadata?: Record<string, unknown>
53
+ delayMs?: number
54
+ }
55
+
56
+ type StoredJob<T> = QueuedJob<T> & {
57
+ availableAt?: string
58
+ attemptCount?: number
59
+ /** Coalescing key. While a record carries it, further enqueues for that key collapse into it. */
60
+ coalesceKey?: string
61
+ coalesceNext?: CoalescedNextJob<T>
62
+ }
63
+
64
+ /**
65
+ * The consumer's record of which jobs it selected into the current batch and has not yet finalized
66
+ * on disk. Selection captures the payload, so every selected id is leased before the lock opens —
67
+ * including jobs whose handlers have not started yet.
68
+ *
69
+ * Producers run in other processes, so `inFlightJobIds` cannot answer "is this job running right
70
+ * now?" for them — and that question is the whole of `keepLastIfActive`. Hence a file. It has
71
+ * exactly one writer (the strategy's single consumer, see the topology note above), so it needs an
72
+ * atomic replacement.
73
+ */
74
+ type ActiveLease = {
75
+ jobIds: string[]
76
+ since: number
77
+ pid: number
78
+ host: string
79
+ }
80
+
81
+ type QueueFileIdentity = {
82
+ device: number
83
+ inode: number
84
+ }
85
+
86
+ function payloadMatchesScope(payload: unknown, scope: QueueJobScope): boolean {
87
+ if (!payload || typeof payload !== 'object') return false
88
+ const scopedPayload = payload as { tenantId?: unknown; organizationId?: unknown; jobType?: unknown }
89
+ if (scopedPayload.tenantId !== scope.tenantId) return false
90
+ if (scope.organizationId !== undefined) {
91
+ if ((scopedPayload.organizationId ?? null) !== scope.organizationId) return false
92
+ }
93
+ if (scope.jobTypes?.length) {
94
+ return typeof scopedPayload.jobType === 'string' && scope.jobTypes.includes(scopedPayload.jobType)
95
+ }
96
+ return true
97
+ }
98
+
99
+ /** Polling interval while delayed or retrying work remains queued. */
100
+ const DEFAULT_POLL_INTERVAL = 1000
101
+ /** Idle safety interval for missed filesystem watcher events. */
102
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 5000
103
+ const DEFAULT_MAX_ATTEMPTS = 3
104
+ const RETRY_BACKOFF_BASE_MS = 1000
105
+
106
+ /**
107
+ * Cross-process lock tuning. A held lock only ever spans local file I/O — job
108
+ * handlers run outside it — so realistic hold times are milliseconds and the
109
+ * stale threshold sits orders of magnitude above them. It exists solely so a
110
+ * process that dies mid-segment cannot wedge the queue forever. A holder that
111
+ * was merely suspended rather than dead can still be reclaimed, which is why
112
+ * every acquisition carries an owner token and releases only its own lock.
113
+ */
114
+ /**
115
+ * How long a lease written by a *different host* is believed. On the same host a lease is checked
116
+ * against its owner's pid instead, which is exact and imposes no ceiling on how long a job may run.
117
+ * A file-backed queue shared across hosts is outside this strategy's contract, so this is only a
118
+ * backstop that keeps such a setup from wedging on a lease nobody will ever clear.
119
+ */
120
+ const ACTIVE_LEASE_FOREIGN_HOST_STALE_MS = 15 * 60 * 1000
121
+
122
+ const LOCK_STALE_MS = 15_000
123
+ const LOCK_ACQUIRE_TIMEOUT_MS = 30_000
124
+ const LOCK_RETRY_MIN_MS = 2
125
+ const LOCK_RETRY_MAX_MS = 20
126
+ const RENAME_MAX_RETRIES = 5
127
+ const RENAME_RETRY_BASE_MS = 10
128
+
129
+ const fsp = fs.promises
130
+
131
+ /**
132
+ * Creates a file-based local queue.
133
+ *
134
+ * Jobs are stored in JSON files within a directory structure:
135
+ * - `.mercato/queue/<name>/queue.json` - Array of queued jobs
136
+ * - `.mercato/queue/<name>/state.json` - Processing state (last processed ID)
137
+ * - `.mercato/queue/<name>/active.json` - Which jobs the consumer selected (created on demand)
138
+ *
139
+ * `EnqueueOptions.coalesce` is honoured here, not just by the `async` strategy, so development and
140
+ * integration runs collapse bursts the way production does. A record carrying `coalesceKey` *is* the
141
+ * key — no separate index, because a local job stays stored for its whole life. Coalescing needs one
142
+ * thing that cannot be derived from `queue.json`, namely whether a job is running right now, and
143
+ * `active.json` supplies it across processes.
144
+ *
145
+ * **Limitations:**
146
+ * - Jobs are processed sequentially (concurrency option is for logging/compatibility only)
147
+ * - Not suitable for production: there is no dead-letter store, no throughput
148
+ * beyond one job at a time, and every operation rewrites the whole queue file
149
+ *
150
+ * Multiple processes MAY share a queue directory, which is the default
151
+ * development topology: the dev worker runs in its own process alongside the
152
+ * Next.js server. What that buys you, and what it does not:
153
+ *
154
+ * - **Safe** — concurrent producers. Every read-modify-write segment takes the
155
+ * `queue.lock` directory lock and every persist swaps the file in with an
156
+ * atomic rename, so the file cannot be torn, no enqueue is lost to a
157
+ * concurrent one, and a reader always observes one complete document.
158
+ * Writers contend, though, so throughput degrades as processes are added.
159
+ * - **NOT safe** — concurrent consumers. `process()` deliberately runs job
160
+ * handlers outside the lock, so two worker processes polling the same queue
161
+ * would both claim the same pending jobs and execute them twice. There is no
162
+ * per-job lease. Run exactly one worker process per queue; use the `async`
163
+ * strategy when you need more than one.
164
+ *
165
+ * Failed jobs are retried up to `DEFAULT_MAX_ATTEMPTS` times with exponential backoff.
166
+ * **This strategy keeps no failed-job store**: once attempts are exhausted the job is
167
+ * removed from `queue.json` and only counted in `state.failedCount`, so the payload is
168
+ * lost and the failure survives solely as an error log line. The `async` strategy keeps
169
+ * only a bounded inspection window: `removeOnFail: 1000` retains the most recent 1000
170
+ * failures and removes older ones as later failures arrive. Workflows that require
171
+ * no-loss persistence must write their own durable record before enqueueing, regardless
172
+ * of strategy.
173
+ *
174
+ * `DEFAULT_MAX_ATTEMPTS` is a module constant, not a per-job option — callers cannot
175
+ * request a different attempt count. (`async` likewise hard-codes `attempts: 3`.)
176
+ * See the retry handling in `process()` below.
177
+ *
178
+ * All file I/O is asynchronous (`fs.promises.*`) so queue operations do not
179
+ * block the Node.js event loop. A per-queue promise chain serializes
180
+ * read-modify-write sequences within one instance, and the `queue.lock`
181
+ * directory lock extends that serialization across instances and processes.
182
+ *
183
+ * @template T - The payload type for jobs
184
+ * @param name - Queue name (used for directory naming)
185
+ * @param options - Local queue options
186
+ */
187
+ export function createLocalQueue<T = unknown>(
188
+ name: string,
189
+ options?: LocalQueueOptions<T>
190
+ ): Queue<T> {
191
+ const nodeProcess = (globalThis as typeof globalThis & { process?: NodeJS.Process }).process
192
+ // Captured here because `enqueue`'s own `options` parameter shadows this one.
193
+ const coalesceBy = options?.coalesceBy
194
+ const baseDir = resolveLocalQueueBaseDir(options?.baseDir)
195
+ const queueDir = path.join(baseDir, name)
196
+ const queueFile = path.join(queueDir, 'queue.json')
197
+ const stateFile = path.join(queueDir, 'state.json')
198
+ const activeFile = path.join(queueDir, 'active.json')
199
+ const lockDir = path.join(queueDir, 'queue.lock')
200
+ const lockOwnerFile = path.join(lockDir, 'owner')
201
+ const logger = packageLogger.child({ queue: name })
202
+
203
+ /**
204
+ * Report a job failure outward, so the log line is not the only record of it.
205
+ * Wrapped: reporting is never worth a poll cycle.
206
+ */
207
+ function reportQueueError(
208
+ error: unknown,
209
+ code: string,
210
+ attributes?: Record<string, string | number | undefined>,
211
+ ): void {
212
+ try {
213
+ getTelemetryRuntime()?.reportError(error, {
214
+ module: 'queue',
215
+ code,
216
+ attributes: { queue: name, ...attributes },
217
+ })
218
+ } catch (telemetryError) {
219
+ // Reporting is never worth a worker — but a systematically broken bridge
220
+ // must not be silent either, or a worker stops reporting and nothing says so.
221
+ logger.warn('Failed to report a queue error to telemetry', { code, err: telemetryError as Error })
222
+ }
223
+ }
224
+ // Note: concurrency is stored for logging/compatibility but jobs are processed sequentially
225
+ const concurrency = options?.concurrency ?? 1
226
+ const pollInterval = options?.pollInterval ?? DEFAULT_POLL_INTERVAL
227
+ const fallbackPollInterval = Math.max(pollInterval, DEFAULT_FALLBACK_POLL_INTERVAL)
228
+
229
+ // Worker state for continuous polling
230
+ let pollingTimer: ReturnType<typeof setInterval> | null = null
231
+ let queuedPollTimer: ReturnType<typeof setTimeout> | null = null
232
+ let queueWatcher: fs.FSWatcher | null = null
233
+ let queueWatcherIdentity: QueueFileIdentity | null = null
234
+ let watcherRefreshChain: Promise<void> = Promise.resolve()
235
+ let hasQueuedJobs = false
236
+ let isProcessing = false
237
+ let pollRequested = false
238
+ let activeHandler: JobHandler<T> | null = null
239
+ const inFlightJobIds = new Set<string>()
240
+
241
+ // Per-queue mutex. Serializes read-modify-write segments so async fs calls
242
+ // cannot interleave and clobber each other's writes. It only covers this
243
+ // instance, so it also guarantees at most one outstanding `queue.lock`
244
+ // acquisition per instance — the directory lock below is not reentrant.
245
+ let fileOpChain: Promise<unknown> = Promise.resolve()
246
+ function withFileLock<R>(fn: () => Promise<R>): Promise<R> {
247
+ const run = fileOpChain.then(
248
+ () => runExclusively(fn),
249
+ () => runExclusively(fn),
250
+ )
251
+ fileOpChain = run.then(
252
+ () => undefined,
253
+ () => undefined,
254
+ )
255
+ return run
256
+ }
257
+
258
+ /**
259
+ * Runs `fn` while holding the cross-process `queue.lock`, so read-modify-write
260
+ * segments issued by other queue instances — in this process or another one —
261
+ * cannot interleave with it.
262
+ */
263
+ async function runExclusively<R>(fn: () => Promise<R>): Promise<R> {
264
+ await ensureDir()
265
+ const release = await acquireDirectoryLock()
266
+ try {
267
+ await createMissingQueueFiles()
268
+ return await fn()
269
+ } finally {
270
+ await release()
271
+ }
272
+ }
273
+
274
+ // -------------------------------------------------------------------------
275
+ // File Operations
276
+ // -------------------------------------------------------------------------
277
+
278
+ function sleep(ms: number): Promise<void> {
279
+ return new Promise((resolve) => { setTimeout(resolve, ms) })
280
+ }
281
+
282
+ async function lockHeldForMs(): Promise<number | null> {
283
+ try {
284
+ const stats = await fsp.stat(lockDir)
285
+ return Date.now() - stats.mtimeMs
286
+ } catch {
287
+ return null
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Reclaims a lock whose holder died. The rename is the serialization point:
293
+ * only one racer can move `queue.lock` aside, so two processes cannot both
294
+ * decide a stale lock is theirs to clear and then both create a fresh one.
295
+ */
296
+ async function reclaimStaleLock(heldForMs: number): Promise<void> {
297
+ const reclaimedPath = `${lockDir}.stale.${crypto.randomUUID()}`
298
+ try {
299
+ await fsp.rename(lockDir, reclaimedPath)
300
+ } catch {
301
+ return
302
+ }
303
+ logger.warn('Reclaimed a stale queue lock', { lockDir, heldForMs })
304
+ await fsp.rm(reclaimedPath, { recursive: true, force: true }).catch(() => {})
305
+ }
306
+
307
+ async function readLockOwner(): Promise<string | null> {
308
+ try {
309
+ return await fsp.readFile(lockOwnerFile, 'utf8')
310
+ } catch {
311
+ return null
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Releases the lock only when this acquisition still owns it. A holder that
317
+ * was suspended past `LOCK_STALE_MS` has had its lock reclaimed *and
318
+ * replaced* by whoever reclaimed it, so an unconditional removal here would
319
+ * delete the successor's lock and let a third caller into the critical
320
+ * section alongside it. A missing or mismatched token means someone else owns
321
+ * the path now, and the correct action is to leave it alone.
322
+ */
323
+ async function releaseDirectoryLock(token: string): Promise<void> {
324
+ if (await readLockOwner() !== token) return
325
+ await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {})
326
+ }
327
+
328
+ /**
329
+ * Acquires the cross-process advisory lock for this queue directory.
330
+ * `mkdir` without `recursive` is an atomic exclusive create on every platform
331
+ * Node.js supports, which makes it the portable primitive here — no runtime
332
+ * dependency, and no reliance on advisory `flock` semantics. The owner token
333
+ * written into the directory is what lets the release distinguish this
334
+ * acquisition from a successor's.
335
+ */
336
+ async function acquireDirectoryLock(): Promise<() => Promise<void>> {
337
+ const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS
338
+
339
+ for (;;) {
340
+ let acquired = false
341
+ try {
342
+ await fsp.mkdir(lockDir)
343
+ acquired = true
344
+ } catch (e: unknown) {
345
+ const error = e as NodeJS.ErrnoException
346
+ if (error.code !== 'EEXIST') throw error
347
+ }
348
+
349
+ if (acquired) {
350
+ const token = crypto.randomUUID()
351
+ try {
352
+ await fsp.writeFile(lockOwnerFile, token, 'utf8')
353
+ } catch (error: unknown) {
354
+ await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {})
355
+ throw error
356
+ }
357
+ return () => releaseDirectoryLock(token)
358
+ }
359
+
360
+ const heldForMs = await lockHeldForMs()
361
+ if (heldForMs !== null && heldForMs > LOCK_STALE_MS) {
362
+ await reclaimStaleLock(heldForMs)
363
+ continue
364
+ }
365
+
366
+ if (Date.now() >= deadline) {
367
+ throw new Error(
368
+ `[internal] Timed out after ${LOCK_ACQUIRE_TIMEOUT_MS}ms waiting for the queue lock at ${lockDir}`,
369
+ )
370
+ }
371
+
372
+ const jitter = LOCK_RETRY_MIN_MS + Math.random() * (LOCK_RETRY_MAX_MS - LOCK_RETRY_MIN_MS)
373
+ await sleep(jitter)
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Persists `content` by writing a unique sibling temp file and renaming it
379
+ * onto `targetFile`. `rename` within a directory is atomic, so a concurrent
380
+ * reader sees either the previous document or the new one in full — never the
381
+ * torn result of a truncate-then-write.
382
+ */
383
+ async function writeFileAtomic(targetFile: string, content: string): Promise<void> {
384
+ const tempFile = `${targetFile}.${crypto.randomUUID()}.tmp`
385
+ try {
386
+ await fsp.writeFile(tempFile, content, 'utf8')
387
+ await renameWithContentionRetry(tempFile, targetFile)
388
+ } catch (error: unknown) {
389
+ await fsp.rm(tempFile, { force: true }).catch(() => {})
390
+ throw error
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Windows rejects a rename onto a file another process currently has open,
396
+ * so retry briefly on the contention codes it raises. POSIX renames replace
397
+ * the target unconditionally and take the first attempt.
398
+ */
399
+ async function renameWithContentionRetry(fromFile: string, toFile: string): Promise<void> {
400
+ const contentionCodes = new Set(['EPERM', 'EBUSY', 'EACCES'])
401
+ for (let attempt = 0; ; attempt++) {
402
+ try {
403
+ await fsp.rename(fromFile, toFile)
404
+ return
405
+ } catch (e: unknown) {
406
+ const error = e as NodeJS.ErrnoException
407
+ if (attempt >= RENAME_MAX_RETRIES || !error.code || !contentionCodes.has(error.code)) throw error
408
+ await sleep(RENAME_RETRY_BASE_MS * (attempt + 1))
409
+ }
410
+ }
411
+ }
412
+
413
+ async function ensureDir(): Promise<void> {
414
+ try {
415
+ await fsp.mkdir(queueDir, { recursive: true })
416
+ } catch (e: unknown) {
417
+ const error = e as NodeJS.ErrnoException
418
+ if (error.code !== 'EEXIST') throw error
419
+ }
420
+ }
421
+
422
+ async function isFileMissing(targetFile: string): Promise<boolean> {
423
+ try {
424
+ await fsp.access(targetFile)
425
+ return false
426
+ } catch (e: unknown) {
427
+ const error = e as NodeJS.ErrnoException
428
+ if (error.code !== 'ENOENT') throw error
429
+ return true
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Publishes `queue.json` and `state.json` when absent. Call it only while
435
+ * holding `queue.lock`: the lock keeps another instance from writing the same
436
+ * file between the existence check and the rename, and the rename keeps every
437
+ * reader from seeing a half-created file.
438
+ */
439
+ async function createMissingQueueFiles(): Promise<void> {
440
+ if (await isFileMissing(queueFile)) await writeFileAtomic(queueFile, '[]')
441
+ if (await isFileMissing(stateFile)) await writeFileAtomic(stateFile, '{}')
442
+ }
443
+
444
+ /**
445
+ * Moves an unparsable queue file aside so its jobs stay recoverable. The
446
+ * caller is expected to surface the failure rather than continue on an empty
447
+ * queue: silently recreating `queue.json` here is what turned an unreadable
448
+ * file into permanent, unreported job loss.
449
+ */
450
+ async function quarantineCorruptedQueueFile(): Promise<string | null> {
451
+ const backupFile = path.join(queueDir, `queue.corrupted.${Date.now()}.${crypto.randomUUID()}.json`)
452
+ try {
453
+ await fsp.rename(queueFile, backupFile)
454
+ return backupFile
455
+ } catch (e: unknown) {
456
+ logger.error('Failed to quarantine the corrupted queue file', { err: e as Error })
457
+ return null
458
+ }
459
+ }
460
+
461
+ async function readQueue(): Promise<StoredJob<T>[]> {
462
+ await ensureDir()
463
+ let content: string
464
+
465
+ try {
466
+ content = await fsp.readFile(queueFile, 'utf8')
467
+ } catch (error: unknown) {
468
+ const readError = error as NodeJS.ErrnoException
469
+ if (readError.code === 'ENOENT') {
470
+ return []
471
+ }
472
+ logger.error('Failed to read queue file', { err: readError })
473
+ throw new Error(`Queue file unreadable: ${readError.message}`)
474
+ }
475
+
476
+ try {
477
+ const parsed = JSON.parse(content) as unknown
478
+
479
+ if (!Array.isArray(parsed)) {
480
+ throw new Error('Queue file must contain a JSON array')
481
+ }
482
+
483
+ return parsed as StoredJob<T>[]
484
+ } catch (error: unknown) {
485
+ const parseError = error as Error
486
+ logger.error('Failed to parse queue file', { err: parseError })
487
+ const backupFile = await quarantineCorruptedQueueFile()
488
+ if (backupFile) {
489
+ logger.error('Quarantined corrupted queue file; its jobs are recoverable from the backup', { backupFile })
490
+ }
491
+ const recoveryHint = backupFile
492
+ ? `has been quarantined as ${backupFile}`
493
+ : 'could not be quarantined and was left in place'
494
+ throw new Error(
495
+ `[internal] Queue file ${queueFile} was unparsable and ${recoveryHint}: ${parseError.message}`,
496
+ )
497
+ }
498
+ }
499
+
500
+ async function writeQueue(jobs: StoredJob<T>[]): Promise<void> {
501
+ await ensureDir()
502
+ await writeFileAtomic(queueFile, JSON.stringify(jobs, null, 2))
503
+ }
504
+
505
+ async function readState(): Promise<LocalState> {
506
+ await ensureDir()
507
+ try {
508
+ const content = await fsp.readFile(stateFile, 'utf8')
509
+ return JSON.parse(content) as LocalState
510
+ } catch {
511
+ return {}
512
+ }
513
+ }
514
+
515
+ async function writeState(state: LocalState): Promise<void> {
516
+ await ensureDir()
517
+ await writeFileAtomic(stateFile, JSON.stringify(state, null, 2))
518
+ }
519
+
520
+ function generateId(): string {
521
+ return crypto.randomUUID()
522
+ }
523
+
524
+ // -------------------------------------------------------------------------
525
+ // Active lease
526
+ // -------------------------------------------------------------------------
527
+
528
+ /**
529
+ * Reads the consumer's lease.
530
+ *
531
+ * Unreadable or unparsable content is discarded rather than quarantined, the mirror image of
532
+ * `readQueue`'s fail-closed handling: a lease holds no payload anyone could recover, and the worst
533
+ * consequence of losing one is a job that runs twice — which is the pre-feature behaviour and
534
+ * within the queue's at-least-once contract. Refusing to enqueue over a damaged lease, by
535
+ * contrast, would turn a cosmetic file into an outage.
536
+ */
537
+ async function readActiveLease(): Promise<ActiveLease | null> {
538
+ let content: string
539
+ try {
540
+ content = await fsp.readFile(activeFile, 'utf8')
541
+ } catch (e: unknown) {
542
+ const readError = e as NodeJS.ErrnoException
543
+ if (readError.code !== 'ENOENT') {
544
+ logger.error('Failed to read the active-job lease; treating it as empty', { err: readError })
545
+ reportQueueError(readError, 'queue.active_lease_read_failed')
546
+ }
547
+ return null
548
+ }
549
+
550
+ try {
551
+ const parsed = JSON.parse(content) as Partial<ActiveLease>
552
+ if (!parsed || !Array.isArray(parsed.jobIds)) {
553
+ throw new Error('Active-job lease must be an object with a jobIds array')
554
+ }
555
+ return {
556
+ jobIds: parsed.jobIds.filter((id): id is string => typeof id === 'string'),
557
+ since: typeof parsed.since === 'number' ? parsed.since : 0,
558
+ pid: typeof parsed.pid === 'number' ? parsed.pid : 0,
559
+ host: typeof parsed.host === 'string' ? parsed.host : '',
560
+ }
561
+ } catch (e: unknown) {
562
+ const parseError = e as Error
563
+ logger.error('Failed to parse the active-job lease; discarding it', { err: parseError })
564
+ reportQueueError(parseError, 'queue.active_lease_parse_failed')
565
+ await fsp.rm(activeFile, { force: true }).catch(() => {})
566
+ return null
567
+ }
568
+ }
569
+
570
+ /**
571
+ * Whether a lease still describes a running consumer. A lease left behind by a crash must not
572
+ * deduplicate enqueues forever, and the strategy has no per-job heartbeat to fall back on.
573
+ */
574
+ function isLeaseLive(lease: ActiveLease | null): lease is ActiveLease {
575
+ if (!lease || lease.jobIds.length === 0) return false
576
+ if (lease.host !== os.hostname()) {
577
+ return Date.now() - lease.since <= ACTIVE_LEASE_FOREIGN_HOST_STALE_MS
578
+ }
579
+ if (!nodeProcess?.kill || !lease.pid) return true
580
+ try {
581
+ nodeProcess.kill(lease.pid, 0)
582
+ return true
583
+ } catch (e: unknown) {
584
+ // EPERM means the pid exists but belongs to another user, so the owner is alive.
585
+ return (e as NodeJS.ErrnoException).code === 'EPERM'
586
+ }
587
+ }
588
+
589
+ async function readLiveLeaseJobIds(): Promise<Set<string>> {
590
+ const lease = await readActiveLease()
591
+ return new Set(isLeaseLive(lease) ? lease.jobIds : [])
592
+ }
593
+
594
+ /**
595
+ * Publishes the lease with an atomic rename while the queue lock still protects job selection,
596
+ * closing the gap where a producer could mistake a selected job for a waiting one.
597
+ */
598
+ async function writeActiveLease(jobIds: string[]): Promise<void> {
599
+ await ensureDir()
600
+ const lease: ActiveLease = {
601
+ jobIds,
602
+ since: Date.now(),
603
+ pid: nodeProcess?.pid ?? 0,
604
+ host: os.hostname(),
605
+ }
606
+ await writeFileAtomic(activeFile, JSON.stringify(lease, null, 2))
607
+ }
608
+
609
+ async function releaseActiveLease(): Promise<void> {
610
+ await fsp.rm(activeFile, { force: true }).catch((err: unknown) => {
611
+ logger.error('Failed to release the active-job lease', { err })
612
+ reportQueueError(err, 'queue.active_lease_release_failed')
613
+ })
614
+ }
615
+
616
+ /**
617
+ * Builds the follow-up job parked on a finalized record by `keepLastIfActive`.
618
+ *
619
+ * Everything except the delay comes from the latest producer enqueue. Only `availableAt` is
620
+ * recomputed, because a delay means "after the enqueue is acted on", and that moment is now.
621
+ */
622
+ function buildFollowUpJob(record: StoredJob<T>): StoredJob<T> | null {
623
+ const next = record.coalesceNext
624
+ if (!next) return null
625
+ const availableAt = next.delayMs && next.delayMs > 0
626
+ ? new Date(Date.now() + next.delayMs).toISOString()
627
+ : undefined
628
+ return {
629
+ id: next.id,
630
+ payload: next.payload,
631
+ createdAt: next.createdAt,
632
+ ...(availableAt ? { availableAt } : {}),
633
+ ...(next.metadata ? { metadata: next.metadata } : {}),
634
+ ...(record.coalesceKey ? { coalesceKey: record.coalesceKey } : {}),
635
+ }
636
+ }
637
+
638
+ function warnAboutDiscardedFollowUps(records: StoredJob<T>[]): void {
639
+ const coalesceKeys = records
640
+ .filter((record) => record.coalesceNext)
641
+ .map((record) => record.coalesceKey ?? record.id)
642
+ if (coalesceKeys.length === 0) return
643
+ logger.warn(
644
+ 'Discarded coalesced follow-up jobs while clearing the queue',
645
+ { coalesceKeys },
646
+ )
647
+ }
648
+
649
+ // -------------------------------------------------------------------------
650
+ // Queue Implementation
651
+ // -------------------------------------------------------------------------
652
+
653
+ async function enqueue(data: T, options?: EnqueueOptions): Promise<string> {
654
+ validateEnqueueOptions(options)
655
+ return publishWithTimeout(() => publish(data, options), options?.timeoutMs)
656
+ }
657
+
658
+ async function publish(data: T, options?: EnqueueOptions): Promise<string> {
659
+ const delayMs = options?.delayMs && options.delayMs > 0 ? options.delayMs : undefined
660
+ const availableAt = delayMs ? new Date(Date.now() + delayMs).toISOString() : undefined
661
+ const traceMetadata = attachTraceMetadata(undefined)
662
+ // Payload-free job type for the status dashboard (same contract as the async strategy).
663
+ const jobType = resolveJobType({ payload: data, metadata: { jobType: options?.jobType } })
664
+ const metadata = jobType ? { ...(traceMetadata ?? {}), jobType } : traceMetadata
665
+ const coalesceKey = resolveCoalesceKey(data, options, coalesceBy)
666
+ const job: StoredJob<T> = {
667
+ id: options?.jobId ?? generateId(),
668
+ payload: data,
669
+ createdAt: new Date().toISOString(),
670
+ ...(availableAt ? { availableAt } : {}),
671
+ ...(metadata ? { metadata } : {}),
672
+ ...(coalesceKey ? { coalesceKey } : {}),
673
+ }
674
+
675
+ if (!coalesceKey) {
676
+ await withFileLock(async () => {
677
+ const jobs = await readQueue()
678
+ if (options?.jobId && jobs.some((existing) => existing.id === job.id)) return
679
+ jobs.push(job)
680
+ await writeQueue(jobs)
681
+ })
682
+ return job.id
683
+ }
684
+
685
+ // The whole decision runs inside one locked segment, so a concurrent producer cannot slip an
686
+ // enqueue between the lookup and the write, and the consumer cannot finalize the job being
687
+ // examined halfway through.
688
+ return withFileLock(async () => {
689
+ const jobs = await readQueue()
690
+ if (options?.jobId && jobs.some((existing) => existing.id === job.id)) return job.id
691
+ const current = jobs.find((candidate) => candidate.coalesceKey === coalesceKey)
692
+ if (!current) {
693
+ jobs.push(job)
694
+ await writeQueue(jobs)
695
+ return job.id
696
+ }
697
+
698
+ if ((await readLiveLeaseJobIds()).has(current.id)) {
699
+ // The running job read its input before this enqueue existed, so dropping the enqueue would
700
+ // lose the write it represents. Park it; the consumer promotes it when the current run ends.
701
+ current.coalesceNext = {
702
+ id: job.id,
703
+ payload: data,
704
+ createdAt: job.createdAt,
705
+ ...(metadata ? { metadata } : {}),
706
+ ...(delayMs ? { delayMs } : {}),
707
+ }
708
+ await writeQueue(jobs)
709
+ return current.id
710
+ }
711
+
712
+ // The twin is merely waiting, so it has read nothing and will observe this enqueue's writes
713
+ // when it runs — but only if it runs no later than this enqueue asked for. Carrying the
714
+ // earlier of the two moments keeps the guarantee one-directional: collapsing may cost a
715
+ // caller a run that happens sooner than it asked, never one that never comes. Dropping the
716
+ // incoming schedule instead would defer an immediate enqueue behind a delayed twin, which is
717
+ // the silently-lost write this feature exists to prevent.
718
+ //
719
+ // A record in retry backoff is excluded: there `availableAt` is not a schedule any caller
720
+ // asked for but the failure handler's spacing, and pulling it forward would let a burst of
721
+ // triggers hot-loop a job that is failing. A retry keeps its key and its backoff both.
722
+ const inRetryBackoff = (current.attemptCount ?? 0) > 0
723
+ const currentAvailableAtMs = current.availableAt ? new Date(current.availableAt).getTime() : 0
724
+ const incomingAvailableAtMs = availableAt ? new Date(availableAt).getTime() : 0
725
+ if (!inRetryBackoff && currentAvailableAtMs > incomingAvailableAtMs) {
726
+ if (availableAt) current.availableAt = availableAt
727
+ else delete current.availableAt
728
+ await writeQueue(jobs)
729
+ return current.id
730
+ }
731
+
732
+ // Coalesced with nothing to record: deliberately no write at all. Rewriting `queue.json`
733
+ // here would rename the file and wake the consumer's watcher for a job that does not exist,
734
+ // which is precisely the work coalescing exists to avoid.
735
+ return current.id
736
+ })
737
+ }
738
+
739
+ /**
740
+ * Process pending jobs in a single batch (internal helper).
741
+ */
742
+ async function processBatch(
743
+ handler: JobHandler<T>,
744
+ options?: ProcessOptions
745
+ ): Promise<ProcessResult> {
746
+ const { state, jobs, jobsToProcess } = await withFileLock(async () => {
747
+ const stateRead = await readState()
748
+ const jobsRead = await readQueue()
749
+ const pendingJobs = jobsRead.filter((job) => {
750
+ if (!job.availableAt) return true
751
+ return new Date(job.availableAt).getTime() <= Date.now()
752
+ })
753
+ const selectedJobs = options?.limit
754
+ ? pendingJobs.slice(0, options.limit)
755
+ : pendingJobs
756
+ if (selectedJobs.length > 0) {
757
+ await writeActiveLease(selectedJobs.map((job) => job.id))
758
+ }
759
+ return { state: stateRead, jobs: jobsRead, jobsToProcess: selectedJobs }
760
+ })
761
+ hasQueuedJobs = jobs.length > 0
762
+
763
+ for (const job of jobsToProcess) {
764
+ inFlightJobIds.add(job.id)
765
+ }
766
+
767
+ let processed = 0
768
+ let failed = 0
769
+ let lastJobId: string | undefined
770
+ const completedJobIds = new Set<string>()
771
+ const deadJobIds = new Set<string>()
772
+ // Patches rather than whole records: the record is re-read below, and a producer may have parked
773
+ // a `coalesceNext` on it while the handler ran. Rewriting it from the pre-run snapshot
774
+ // would silently discard that enqueue.
775
+ const retryPatches = new Map<string, { attemptCount: number; availableAt: string }>()
776
+ const leaseWritten = jobsToProcess.length > 0
777
+
778
+ try {
779
+ for (const job of jobsToProcess) {
780
+ const attemptNumber = (job.attemptCount ?? 0) + 1
781
+ try {
782
+ await runJobInTrace(name, job.metadata, () =>
783
+ Promise.resolve(
784
+ handler(job, {
785
+ jobId: job.id,
786
+ attemptNumber,
787
+ queueName: name,
788
+ })
789
+ )
790
+ )
791
+ processed++
792
+ lastJobId = job.id
793
+ completedJobIds.add(job.id)
794
+ logger.info('Job completed', { jobId: job.id })
795
+ } catch (error) {
796
+ logger.error('Job failed', { jobId: job.id, attemptNumber, maxAttempts: DEFAULT_MAX_ATTEMPTS, err: error })
797
+ const exhausted = attemptNumber >= DEFAULT_MAX_ATTEMPTS
798
+ // One report per failure, coded by what the failure means: a job that
799
+ // has burned every retry is dead, which is the condition an operator
800
+ // pages on, and it must be distinguishable from a first attempt that
801
+ // will simply be retried. Reporting both would double-count `om.errors`
802
+ // on the final attempt.
803
+ reportQueueError(error, exhausted ? 'queue.job_exhausted' : 'queue.job_failed', {
804
+ jobId: job.id,
805
+ attemptNumber,
806
+ })
807
+ failed++
808
+ lastJobId = job.id
809
+ if (exhausted) {
810
+ logger.error('Job exhausted all attempts; dropping it (no dead-letter store)', { jobId: job.id, maxAttempts: DEFAULT_MAX_ATTEMPTS })
811
+ deadJobIds.add(job.id)
812
+ } else {
813
+ const backoffMs = RETRY_BACKOFF_BASE_MS * Math.pow(2, attemptNumber - 1)
814
+ retryPatches.set(job.id, {
815
+ attemptCount: attemptNumber,
816
+ availableAt: new Date(Date.now() + backoffMs).toISOString(),
817
+ })
818
+ }
819
+ }
820
+ }
821
+
822
+ const hasChanges = completedJobIds.size > 0 || deadJobIds.size > 0 || retryPatches.size > 0
823
+ if (hasChanges) {
824
+ await withFileLock(async () => {
825
+ // Re-read so jobs enqueued during handler execution are preserved.
826
+ const currentJobs = await readQueue()
827
+ const finalizedJobIds = new Set([...completedJobIds, ...deadJobIds])
828
+ // A job that exhausted its attempts is finalized too, exactly as a completed one is.
829
+ // Leaving its key behind would deduplicate every later enqueue onto a record that no
830
+ // longer exists, and would strand its follow-up.
831
+ const followUpJobs = currentJobs
832
+ .filter((j) => finalizedJobIds.has(j.id))
833
+ .map((j) => buildFollowUpJob(j))
834
+ .filter((j): j is StoredJob<T> => j !== null)
835
+ const updatedJobs = currentJobs
836
+ .filter((j) => !finalizedJobIds.has(j.id))
837
+ .map((j) => {
838
+ const patch = retryPatches.get(j.id)
839
+ return patch ? { ...j, ...patch } : j
840
+ })
841
+ // Appended in the same write that removes the job they were parked on, so there is never a
842
+ // moment where a burst could produce a third job for one coalescing key.
843
+ updatedJobs.push(...followUpJobs)
844
+ await writeQueue(updatedJobs)
845
+ hasQueuedJobs = updatedJobs.length > 0
846
+
847
+ const newState: LocalState = {
848
+ lastProcessedId: lastJobId,
849
+ completedCount: (state.completedCount ?? 0) + processed,
850
+ failedCount: (state.failedCount ?? 0) + deadJobIds.size,
851
+ }
852
+ await writeState(newState)
853
+ })
854
+ }
855
+
856
+ return { processed, failed, lastJobId }
857
+ } finally {
858
+ for (const job of jobsToProcess) {
859
+ inFlightJobIds.delete(job.id)
860
+ }
861
+ // After the closing write, so a job is never both stored and unleased.
862
+ if (leaseWritten) {
863
+ await releaseActiveLease()
864
+ }
865
+ }
866
+ }
867
+
868
+ /**
869
+ * Poll for and process new jobs.
870
+ */
871
+ async function pollAndProcess(rethrow = false): Promise<void> {
872
+ if (!activeHandler) return
873
+ if (isProcessing) {
874
+ pollRequested = true
875
+ return
876
+ }
877
+
878
+ isProcessing = true
879
+ try {
880
+ do {
881
+ pollRequested = false
882
+ const handler = activeHandler
883
+ if (!handler) break
884
+ await processBatch(handler)
885
+ } while (pollRequested)
886
+ } catch (error) {
887
+ if (rethrow) throw error
888
+ logger.error('Polling error', { err: error })
889
+ } finally {
890
+ isProcessing = false
891
+ scheduleQueuedPoll()
892
+ }
893
+ }
894
+
895
+ function scheduleQueuedPoll(): void {
896
+ if (!activeHandler || !hasQueuedJobs) {
897
+ if (queuedPollTimer) {
898
+ clearTimeout(queuedPollTimer)
899
+ queuedPollTimer = null
900
+ }
901
+ return
902
+ }
903
+ if (queuedPollTimer) return
904
+ queuedPollTimer = setTimeout(() => {
905
+ queuedPollTimer = null
906
+ void pollAndProcess()
907
+ }, pollInterval)
908
+ }
909
+
910
+ function closeQueueWatcher(): void {
911
+ if (queueWatcher) {
912
+ queueWatcher.close()
913
+ queueWatcher = null
914
+ }
915
+ queueWatcherIdentity = null
916
+ }
917
+
918
+ function refreshQueueWatcher(): Promise<void> {
919
+ const refresh = watcherRefreshChain.then(async () => {
920
+ if (!activeHandler) return
921
+ try {
922
+ if (await isFileMissing(queueFile)) await withFileLock(createMissingQueueFiles)
923
+ const stats = await fsp.stat(queueFile)
924
+ const nextIdentity = { device: stats.dev, inode: stats.ino }
925
+ if (
926
+ queueWatcher
927
+ && queueWatcherIdentity?.device === nextIdentity.device
928
+ && queueWatcherIdentity.inode === nextIdentity.inode
929
+ ) {
930
+ return
931
+ }
932
+
933
+ closeQueueWatcher()
934
+ const watcher = fs.watch(queueFile, (eventType) => {
935
+ if (eventType === 'rename') {
936
+ queueWatcherIdentity = null
937
+ void refreshQueueWatcher()
938
+ }
939
+ void pollAndProcess()
940
+ })
941
+ watcher.on('error', (err) => {
942
+ logger.error('Queue watch error; fallback polling remains active', { err })
943
+ if (queueWatcher === watcher) {
944
+ closeQueueWatcher()
945
+ }
946
+ })
947
+ if (!activeHandler) {
948
+ watcher.close()
949
+ return
950
+ }
951
+ queueWatcher = watcher
952
+ queueWatcherIdentity = nextIdentity
953
+ } catch (err) {
954
+ logger.error('Failed to watch queue file; fallback polling remains active', { err })
955
+ }
956
+ })
957
+ watcherRefreshChain = refresh.catch(() => undefined)
958
+ return refresh
959
+ }
960
+
961
+ async function process(
962
+ handler: JobHandler<T>,
963
+ options?: ProcessOptions
964
+ ): Promise<ProcessResult> {
965
+ // If limit is specified, do a single batch (backward compatibility)
966
+ if (options?.limit) {
967
+ await releaseActiveLease()
968
+ return processBatch(handler, options)
969
+ }
970
+
971
+ if (activeHandler) {
972
+ await close()
973
+ }
974
+
975
+ // A consumer is starting, and this strategy admits exactly one consumer per queue, so any lease
976
+ // still on disk belongs to a run that will never finish. Clearing it is the authoritative
977
+ // recovery from a crashed consumer: the jobs it named are still stored, so they simply run
978
+ // again, carrying any parked follow-up with them. The alternative — ageing leases out — would
979
+ // have to guess a ceiling on how long a handler may legitimately take.
980
+ await releaseActiveLease()
981
+
982
+ // Start continuous polling mode (like BullMQ Worker)
983
+ activeHandler = handler
984
+
985
+ try {
986
+ await refreshQueueWatcher()
987
+ await pollAndProcess(true)
988
+ } catch (error) {
989
+ await close()
990
+ throw error
991
+ }
992
+
993
+ pollingTimer = setInterval(() => {
994
+ refreshQueueWatcher().then(() => pollAndProcess()).catch((err) => {
995
+ logger.error('Poll cycle error', { err })
996
+ })
997
+ }, fallbackPollInterval)
998
+
999
+ logger.info('Worker started', { concurrency })
1000
+
1001
+ // Return sentinel value indicating continuous worker mode (like async strategy)
1002
+ return { processed: -1, failed: -1, lastJobId: undefined }
1003
+ }
1004
+
1005
+ async function clear(): Promise<{ removed: number }> {
1006
+ return withFileLock(async () => {
1007
+ const jobs = await readQueue()
1008
+ const removed = jobs.length
1009
+ warnAboutDiscardedFollowUps(jobs)
1010
+ await writeQueue([])
1011
+ hasQueuedJobs = false
1012
+ scheduleQueuedPoll()
1013
+ // Reset state but preserve counts for historical tracking
1014
+ const state = await readState()
1015
+ await writeState({
1016
+ completedCount: state.completedCount,
1017
+ failedCount: state.failedCount,
1018
+ })
1019
+ return { removed }
1020
+ })
1021
+ }
1022
+
1023
+ async function removeQueuedJobsByScope(scope: QueueJobScope): Promise<{ removed: number }> {
1024
+ return withFileLock(async () => {
1025
+ const jobs = await readQueue()
1026
+ const retainedJobs = jobs.filter((job) => inFlightJobIds.has(job.id) || !payloadMatchesScope(job.payload, scope))
1027
+ const removed = jobs.length - retainedJobs.length
1028
+ if (removed > 0) {
1029
+ const retainedIds = new Set(retainedJobs.map((job) => job.id))
1030
+ warnAboutDiscardedFollowUps(jobs.filter((job) => !retainedIds.has(job.id)))
1031
+ await writeQueue(retainedJobs)
1032
+ }
1033
+ hasQueuedJobs = retainedJobs.length > 0
1034
+ scheduleQueuedPoll()
1035
+ return { removed }
1036
+ })
1037
+ }
1038
+
1039
+ async function close(): Promise<void> {
1040
+ activeHandler = null
1041
+ if (queuedPollTimer) {
1042
+ clearTimeout(queuedPollTimer)
1043
+ queuedPollTimer = null
1044
+ }
1045
+ closeQueueWatcher()
1046
+
1047
+ // Stop polling timer
1048
+ if (pollingTimer) {
1049
+ clearInterval(pollingTimer)
1050
+ pollingTimer = null
1051
+ }
1052
+ // Wait for any in-progress processing to complete (with timeout)
1053
+ const SHUTDOWN_TIMEOUT = 5000
1054
+ const startTime = Date.now()
1055
+
1056
+ while (isProcessing) {
1057
+ if (Date.now() - startTime > SHUTDOWN_TIMEOUT) {
1058
+ logger.warn('Force closing after shutdown timeout', { timeoutMs: SHUTDOWN_TIMEOUT })
1059
+ break
1060
+ }
1061
+ await new Promise((resolve) => setTimeout(resolve, 50))
1062
+ }
1063
+ }
1064
+
1065
+ async function getJobCounts(): Promise<{
1066
+ waiting: number
1067
+ active: number
1068
+ completed: number
1069
+ failed: number
1070
+ }> {
1071
+ return withFileLock(async () => {
1072
+ const state = await readState()
1073
+ const jobs = await readQueue()
1074
+ // Intersected with the stored jobs rather than trusted outright, so a lease naming a job that
1075
+ // has since been cleared away cannot inflate the count or push `waiting` negative.
1076
+ const leasedJobIds = await readLiveLeaseJobIds()
1077
+ const active = jobs.filter((job) => leasedJobIds.has(job.id)).length
1078
+
1079
+ return {
1080
+ // A job stays stored while it runs, so waiting is what is left once the active ones are
1081
+ // discounted.
1082
+ waiting: jobs.length - active,
1083
+ active,
1084
+ completed: state.completedCount ?? 0,
1085
+ failed: state.failedCount ?? 0,
1086
+ // `delayed` omitted: this strategy keeps no delayed-job state distinct from waiting.
1087
+ }
1088
+ })
1089
+ }
1090
+
1091
+ const MAX_IN_FLIGHT_LIMIT = 50
1092
+ const DEFAULT_IN_FLIGHT_LIMIT = 20
1093
+ const MAX_RECENT_JOBS_LIMIT = 100
1094
+ const DEFAULT_RECENT_JOBS_LIMIT = 20
1095
+ /**
1096
+ * Largest `queue.json` the introspection reads will parse. The local strategy stores payloads
1097
+ * inline in one JSON document, so there is no index to window over: a read costs a full parse of
1098
+ * the file. Past this size the optional summaries report "unavailable" instead of scanning — the
1099
+ * (existing) counts stay available, and the `async` strategy is the one meant for real backlogs.
1100
+ */
1101
+ const MAX_INTROSPECTION_FILE_BYTES = 8 * 1024 * 1024
1102
+ /** One dashboard refresh issues several introspection calls; they share a single parse of an unchanged file. */
1103
+ const INTROSPECTION_CACHE_TTL_MS = 2000
1104
+ let introspectionCache: { key: string; at: number; jobs: StoredJob<T>[] } | null = null
1105
+
1106
+ function jobEnqueuedAtMs(job: StoredJob<T>): number | undefined {
1107
+ const parsed = Date.parse(job.createdAt)
1108
+ return Number.isFinite(parsed) ? parsed : undefined
1109
+ }
1110
+
1111
+ /**
1112
+ * A pending job is `delayed` while its `availableAt` (a delayed enqueue or a retry backoff) is in
1113
+ * the future, `waiting` otherwise. Every introspection method classifies through here, so a job
1114
+ * is never reported as both.
1115
+ */
1116
+ function classifyPending(job: StoredJob<T>, now: number): 'waiting' | 'delayed' {
1117
+ if (!job.availableAt) return 'waiting'
1118
+ const availableAt = Date.parse(job.availableAt)
1119
+ return Number.isFinite(availableAt) && availableAt > now ? 'delayed' : 'waiting'
1120
+ }
1121
+
1122
+ /**
1123
+ * Reads `queue.json` for introspection WITHOUT the worker file lock: every persist is an atomic
1124
+ * rename, so a reader always sees one complete document, and an admin dashboard must not stall
1125
+ * the worker's read-modify-write segments. Never quarantines a corrupt file (that is the worker
1126
+ * path's job) — it just reports the section unavailable.
1127
+ */
1128
+ async function readIntrospectionSnapshot(): Promise<StoredJob<T>[]> {
1129
+ let stats: fs.Stats
1130
+ try {
1131
+ stats = await fsp.stat(queueFile)
1132
+ } catch (error: unknown) {
1133
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
1134
+ throw new QueueIntrospectionUnavailableError('Local queue file is not readable')
1135
+ }
1136
+ if (stats.size > MAX_INTROSPECTION_FILE_BYTES) {
1137
+ throw new QueueIntrospectionUnavailableError('Local queue backlog is too large to introspect')
1138
+ }
1139
+
1140
+ const key = `${stats.ino}:${stats.size}:${stats.mtimeMs}`
1141
+ const now = Date.now()
1142
+ if (introspectionCache && introspectionCache.key === key && now - introspectionCache.at < INTROSPECTION_CACHE_TTL_MS) {
1143
+ return introspectionCache.jobs
1144
+ }
1145
+
1146
+ let parsed: unknown
1147
+ try {
1148
+ parsed = JSON.parse(await fsp.readFile(queueFile, 'utf8'))
1149
+ } catch (error: unknown) {
1150
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
1151
+ throw new QueueIntrospectionUnavailableError('Local queue file could not be parsed')
1152
+ }
1153
+ if (!Array.isArray(parsed)) throw new QueueIntrospectionUnavailableError('Local queue file is malformed')
1154
+
1155
+ introspectionCache = { key, at: now, jobs: parsed as StoredJob<T>[] }
1156
+ return introspectionCache.jobs
1157
+ }
1158
+
1159
+ /**
1160
+ * No completed-job records are retained (`state.json` holds only a count), so
1161
+ * there is no sample to derive durations from. Reporting an honestly-empty
1162
+ * `partial` result — rather than a fabricated number — is this strategy's
1163
+ * documented fallback (see the class doc comment on retention).
1164
+ */
1165
+ async function getProcessingStats(): Promise<QueueProcessingStats> {
1166
+ return { sampleSize: 0, fidelity: 'partial' }
1167
+ }
1168
+
1169
+ /**
1170
+ * Best-effort from the pending-job file. `active` has no cross-process
1171
+ * meaning here — a worker's `inFlightJobIds` is private, in-memory state in
1172
+ * whichever process is actually polling, invisible to this call from an
1173
+ * admin-surface process — so it always reports empty for that state.
1174
+ * `waiting` and `delayed` partition the pending jobs (see `classifyPending`).
1175
+ */
1176
+ async function getInFlightJobsSummary(opts: {
1177
+ state?: 'active' | 'waiting' | 'delayed'
1178
+ type?: string
1179
+ limit: number
1180
+ }): Promise<InFlightJobSummary[]> {
1181
+ const state = opts.state ?? 'active'
1182
+ if (state === 'active') return []
1183
+ const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_IN_FLIGHT_LIMIT, MAX_IN_FLIGHT_LIMIT)
1184
+ if (cappedLimit === 0) return []
1185
+
1186
+ const jobs = await readIntrospectionSnapshot()
1187
+ const now = Date.now()
1188
+ // `queue.json` is append-ordered, so file order IS oldest-first (the head of the queue — the
1189
+ // jobs that look stuck). Delayed jobs are ordered by when they become available instead.
1190
+ const matching = jobs.filter(
1191
+ (job) => classifyPending(job, now) === state && (!opts.type || resolveJobType(job) === opts.type),
1192
+ )
1193
+ const head = state === 'delayed'
1194
+ ? matching.sort((a, b) => (Date.parse(a.availableAt ?? '') || 0) - (Date.parse(b.availableAt ?? '') || 0))
1195
+ : matching
1196
+
1197
+ return head.slice(0, cappedLimit).map((job) => {
1198
+ const enqueuedAt = jobEnqueuedAtMs(job)
1199
+ return {
1200
+ id: job.id,
1201
+ queue: name,
1202
+ type: resolveJobType(job),
1203
+ state,
1204
+ enqueuedAt,
1205
+ ageMs: enqueuedAt !== undefined ? now - enqueuedAt : undefined,
1206
+ attemptsMade: job.attemptCount,
1207
+ }
1208
+ })
1209
+ }
1210
+
1211
+ function toRecentJob(job: StoredJob<T>, state: 'waiting' | 'delayed'): RecentJob {
1212
+ return {
1213
+ id: job.id,
1214
+ queue: name,
1215
+ state,
1216
+ type: resolveJobType(job),
1217
+ timestamp: jobEnqueuedAtMs(job),
1218
+ attemptsMade: job.attemptCount,
1219
+ data: job.payload,
1220
+ }
1221
+ }
1222
+
1223
+ /**
1224
+ * Tier 2 (privileged) ONLY. This strategy keeps no retained completed/failed
1225
+ * store and cannot see active jobs, so only the pending `waiting` / `delayed`
1226
+ * states exist; every other requested state is an honest empty result rather
1227
+ * than pending jobs relabelled.
1228
+ */
1229
+ async function getRecentJobs(opts: {
1230
+ state?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed'
1231
+ type?: string
1232
+ id?: string
1233
+ limit: number
1234
+ offset?: number
1235
+ }): Promise<RecentJob[]> {
1236
+ if (opts.id) {
1237
+ const jobs = await readIntrospectionSnapshot()
1238
+ const job = jobs.find((candidate) => candidate.id === opts.id)
1239
+ return job ? [toRecentJob(job, classifyPending(job, Date.now()))] : []
1240
+ }
1241
+
1242
+ if (opts.state && opts.state !== 'waiting' && opts.state !== 'delayed') return []
1243
+ const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_RECENT_JOBS_LIMIT, MAX_RECENT_JOBS_LIMIT)
1244
+ if (cappedLimit === 0) return []
1245
+ const boundedOffset = resolveOffset(opts.offset)
1246
+
1247
+ const jobs = await readIntrospectionSnapshot()
1248
+ const now = Date.now()
1249
+ const result: RecentJob[] = []
1250
+ let skipped = 0
1251
+ // Newest-first, mirroring the async strategy's ordering contract: walk the append-ordered file backwards.
1252
+ for (let index = jobs.length - 1; index >= 0 && result.length < cappedLimit; index--) {
1253
+ const job = jobs[index]
1254
+ const state = classifyPending(job, now)
1255
+ if (opts.state && state !== opts.state) continue
1256
+ if (opts.type && resolveJobType(job) !== opts.type) continue
1257
+ if (skipped < boundedOffset) {
1258
+ skipped++
1259
+ continue
1260
+ }
1261
+ result.push(toRecentJob(job, state))
1262
+ }
1263
+ return result
1264
+ }
1265
+
1266
+ return {
1267
+ name,
1268
+ strategy: 'local',
1269
+ enqueue,
1270
+ process,
1271
+ clear,
1272
+ removeQueuedJobsByScope,
1273
+ close,
1274
+ getJobCounts,
1275
+ getProcessingStats,
1276
+ getInFlightJobsSummary,
1277
+ getRecentJobs,
1278
+ }
1279
+ }