@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,820 @@
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 { resolveCoalesceKey } from "@open-mercato/queue-provider-kit/coalescing";
8
+ import { attachTraceMetadata, runJobInTrace } from "@open-mercato/queue-provider-kit/tracing";
9
+ import {
10
+ QueueIntrospectionUnavailableError,
11
+ resolveJobType,
12
+ resolveOffset,
13
+ resolveWindowSize
14
+ } from "@open-mercato/queue-provider-kit/introspection";
15
+ import { publishWithTimeout, validateEnqueueOptions } from "@open-mercato/queue-provider-kit/publication";
16
+ import { resolveLocalQueueBaseDir } from "./base-dir.js";
17
+ const packageLogger = createLogger("queue");
18
+ function payloadMatchesScope(payload, scope) {
19
+ if (!payload || typeof payload !== "object") return false;
20
+ const scopedPayload = payload;
21
+ if (scopedPayload.tenantId !== scope.tenantId) return false;
22
+ if (scope.organizationId !== void 0) {
23
+ if ((scopedPayload.organizationId ?? null) !== scope.organizationId) return false;
24
+ }
25
+ if (scope.jobTypes?.length) {
26
+ return typeof scopedPayload.jobType === "string" && scope.jobTypes.includes(scopedPayload.jobType);
27
+ }
28
+ return true;
29
+ }
30
+ const DEFAULT_POLL_INTERVAL = 1e3;
31
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 5e3;
32
+ const DEFAULT_MAX_ATTEMPTS = 3;
33
+ const RETRY_BACKOFF_BASE_MS = 1e3;
34
+ const ACTIVE_LEASE_FOREIGN_HOST_STALE_MS = 15 * 60 * 1e3;
35
+ const LOCK_STALE_MS = 15e3;
36
+ const LOCK_ACQUIRE_TIMEOUT_MS = 3e4;
37
+ const LOCK_RETRY_MIN_MS = 2;
38
+ const LOCK_RETRY_MAX_MS = 20;
39
+ const RENAME_MAX_RETRIES = 5;
40
+ const RENAME_RETRY_BASE_MS = 10;
41
+ const fsp = fs.promises;
42
+ function createLocalQueue(name, options) {
43
+ const nodeProcess = globalThis.process;
44
+ const coalesceBy = options?.coalesceBy;
45
+ const baseDir = resolveLocalQueueBaseDir(options?.baseDir);
46
+ const queueDir = path.join(baseDir, name);
47
+ const queueFile = path.join(queueDir, "queue.json");
48
+ const stateFile = path.join(queueDir, "state.json");
49
+ const activeFile = path.join(queueDir, "active.json");
50
+ const lockDir = path.join(queueDir, "queue.lock");
51
+ const lockOwnerFile = path.join(lockDir, "owner");
52
+ const logger = packageLogger.child({ queue: name });
53
+ function reportQueueError(error, code, attributes) {
54
+ try {
55
+ getTelemetryRuntime()?.reportError(error, {
56
+ module: "queue",
57
+ code,
58
+ attributes: { queue: name, ...attributes }
59
+ });
60
+ } catch (telemetryError) {
61
+ logger.warn("Failed to report a queue error to telemetry", { code, err: telemetryError });
62
+ }
63
+ }
64
+ const concurrency = options?.concurrency ?? 1;
65
+ const pollInterval = options?.pollInterval ?? DEFAULT_POLL_INTERVAL;
66
+ const fallbackPollInterval = Math.max(pollInterval, DEFAULT_FALLBACK_POLL_INTERVAL);
67
+ let pollingTimer = null;
68
+ let queuedPollTimer = null;
69
+ let queueWatcher = null;
70
+ let queueWatcherIdentity = null;
71
+ let watcherRefreshChain = Promise.resolve();
72
+ let hasQueuedJobs = false;
73
+ let isProcessing = false;
74
+ let pollRequested = false;
75
+ let activeHandler = null;
76
+ const inFlightJobIds = /* @__PURE__ */ new Set();
77
+ let fileOpChain = Promise.resolve();
78
+ function withFileLock(fn) {
79
+ const run = fileOpChain.then(
80
+ () => runExclusively(fn),
81
+ () => runExclusively(fn)
82
+ );
83
+ fileOpChain = run.then(
84
+ () => void 0,
85
+ () => void 0
86
+ );
87
+ return run;
88
+ }
89
+ async function runExclusively(fn) {
90
+ await ensureDir();
91
+ const release = await acquireDirectoryLock();
92
+ try {
93
+ await createMissingQueueFiles();
94
+ return await fn();
95
+ } finally {
96
+ await release();
97
+ }
98
+ }
99
+ function sleep(ms) {
100
+ return new Promise((resolve) => {
101
+ setTimeout(resolve, ms);
102
+ });
103
+ }
104
+ async function lockHeldForMs() {
105
+ try {
106
+ const stats = await fsp.stat(lockDir);
107
+ return Date.now() - stats.mtimeMs;
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+ async function reclaimStaleLock(heldForMs) {
113
+ const reclaimedPath = `${lockDir}.stale.${crypto.randomUUID()}`;
114
+ try {
115
+ await fsp.rename(lockDir, reclaimedPath);
116
+ } catch {
117
+ return;
118
+ }
119
+ logger.warn("Reclaimed a stale queue lock", { lockDir, heldForMs });
120
+ await fsp.rm(reclaimedPath, { recursive: true, force: true }).catch(() => {
121
+ });
122
+ }
123
+ async function readLockOwner() {
124
+ try {
125
+ return await fsp.readFile(lockOwnerFile, "utf8");
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+ async function releaseDirectoryLock(token) {
131
+ if (await readLockOwner() !== token) return;
132
+ await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {
133
+ });
134
+ }
135
+ async function acquireDirectoryLock() {
136
+ const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;
137
+ for (; ; ) {
138
+ let acquired = false;
139
+ try {
140
+ await fsp.mkdir(lockDir);
141
+ acquired = true;
142
+ } catch (e) {
143
+ const error = e;
144
+ if (error.code !== "EEXIST") throw error;
145
+ }
146
+ if (acquired) {
147
+ const token = crypto.randomUUID();
148
+ try {
149
+ await fsp.writeFile(lockOwnerFile, token, "utf8");
150
+ } catch (error) {
151
+ await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {
152
+ });
153
+ throw error;
154
+ }
155
+ return () => releaseDirectoryLock(token);
156
+ }
157
+ const heldForMs = await lockHeldForMs();
158
+ if (heldForMs !== null && heldForMs > LOCK_STALE_MS) {
159
+ await reclaimStaleLock(heldForMs);
160
+ continue;
161
+ }
162
+ if (Date.now() >= deadline) {
163
+ throw new Error(
164
+ `[internal] Timed out after ${LOCK_ACQUIRE_TIMEOUT_MS}ms waiting for the queue lock at ${lockDir}`
165
+ );
166
+ }
167
+ const jitter = LOCK_RETRY_MIN_MS + Math.random() * (LOCK_RETRY_MAX_MS - LOCK_RETRY_MIN_MS);
168
+ await sleep(jitter);
169
+ }
170
+ }
171
+ async function writeFileAtomic(targetFile, content) {
172
+ const tempFile = `${targetFile}.${crypto.randomUUID()}.tmp`;
173
+ try {
174
+ await fsp.writeFile(tempFile, content, "utf8");
175
+ await renameWithContentionRetry(tempFile, targetFile);
176
+ } catch (error) {
177
+ await fsp.rm(tempFile, { force: true }).catch(() => {
178
+ });
179
+ throw error;
180
+ }
181
+ }
182
+ async function renameWithContentionRetry(fromFile, toFile) {
183
+ const contentionCodes = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
184
+ for (let attempt = 0; ; attempt++) {
185
+ try {
186
+ await fsp.rename(fromFile, toFile);
187
+ return;
188
+ } catch (e) {
189
+ const error = e;
190
+ if (attempt >= RENAME_MAX_RETRIES || !error.code || !contentionCodes.has(error.code)) throw error;
191
+ await sleep(RENAME_RETRY_BASE_MS * (attempt + 1));
192
+ }
193
+ }
194
+ }
195
+ async function ensureDir() {
196
+ try {
197
+ await fsp.mkdir(queueDir, { recursive: true });
198
+ } catch (e) {
199
+ const error = e;
200
+ if (error.code !== "EEXIST") throw error;
201
+ }
202
+ }
203
+ async function isFileMissing(targetFile) {
204
+ try {
205
+ await fsp.access(targetFile);
206
+ return false;
207
+ } catch (e) {
208
+ const error = e;
209
+ if (error.code !== "ENOENT") throw error;
210
+ return true;
211
+ }
212
+ }
213
+ async function createMissingQueueFiles() {
214
+ if (await isFileMissing(queueFile)) await writeFileAtomic(queueFile, "[]");
215
+ if (await isFileMissing(stateFile)) await writeFileAtomic(stateFile, "{}");
216
+ }
217
+ async function quarantineCorruptedQueueFile() {
218
+ const backupFile = path.join(queueDir, `queue.corrupted.${Date.now()}.${crypto.randomUUID()}.json`);
219
+ try {
220
+ await fsp.rename(queueFile, backupFile);
221
+ return backupFile;
222
+ } catch (e) {
223
+ logger.error("Failed to quarantine the corrupted queue file", { err: e });
224
+ return null;
225
+ }
226
+ }
227
+ async function readQueue() {
228
+ await ensureDir();
229
+ let content;
230
+ try {
231
+ content = await fsp.readFile(queueFile, "utf8");
232
+ } catch (error) {
233
+ const readError = error;
234
+ if (readError.code === "ENOENT") {
235
+ return [];
236
+ }
237
+ logger.error("Failed to read queue file", { err: readError });
238
+ throw new Error(`Queue file unreadable: ${readError.message}`);
239
+ }
240
+ try {
241
+ const parsed = JSON.parse(content);
242
+ if (!Array.isArray(parsed)) {
243
+ throw new Error("Queue file must contain a JSON array");
244
+ }
245
+ return parsed;
246
+ } catch (error) {
247
+ const parseError = error;
248
+ logger.error("Failed to parse queue file", { err: parseError });
249
+ const backupFile = await quarantineCorruptedQueueFile();
250
+ if (backupFile) {
251
+ logger.error("Quarantined corrupted queue file; its jobs are recoverable from the backup", { backupFile });
252
+ }
253
+ const recoveryHint = backupFile ? `has been quarantined as ${backupFile}` : "could not be quarantined and was left in place";
254
+ throw new Error(
255
+ `[internal] Queue file ${queueFile} was unparsable and ${recoveryHint}: ${parseError.message}`
256
+ );
257
+ }
258
+ }
259
+ async function writeQueue(jobs) {
260
+ await ensureDir();
261
+ await writeFileAtomic(queueFile, JSON.stringify(jobs, null, 2));
262
+ }
263
+ async function readState() {
264
+ await ensureDir();
265
+ try {
266
+ const content = await fsp.readFile(stateFile, "utf8");
267
+ return JSON.parse(content);
268
+ } catch {
269
+ return {};
270
+ }
271
+ }
272
+ async function writeState(state) {
273
+ await ensureDir();
274
+ await writeFileAtomic(stateFile, JSON.stringify(state, null, 2));
275
+ }
276
+ function generateId() {
277
+ return crypto.randomUUID();
278
+ }
279
+ async function readActiveLease() {
280
+ let content;
281
+ try {
282
+ content = await fsp.readFile(activeFile, "utf8");
283
+ } catch (e) {
284
+ const readError = e;
285
+ if (readError.code !== "ENOENT") {
286
+ logger.error("Failed to read the active-job lease; treating it as empty", { err: readError });
287
+ reportQueueError(readError, "queue.active_lease_read_failed");
288
+ }
289
+ return null;
290
+ }
291
+ try {
292
+ const parsed = JSON.parse(content);
293
+ if (!parsed || !Array.isArray(parsed.jobIds)) {
294
+ throw new Error("Active-job lease must be an object with a jobIds array");
295
+ }
296
+ return {
297
+ jobIds: parsed.jobIds.filter((id) => typeof id === "string"),
298
+ since: typeof parsed.since === "number" ? parsed.since : 0,
299
+ pid: typeof parsed.pid === "number" ? parsed.pid : 0,
300
+ host: typeof parsed.host === "string" ? parsed.host : ""
301
+ };
302
+ } catch (e) {
303
+ const parseError = e;
304
+ logger.error("Failed to parse the active-job lease; discarding it", { err: parseError });
305
+ reportQueueError(parseError, "queue.active_lease_parse_failed");
306
+ await fsp.rm(activeFile, { force: true }).catch(() => {
307
+ });
308
+ return null;
309
+ }
310
+ }
311
+ function isLeaseLive(lease) {
312
+ if (!lease || lease.jobIds.length === 0) return false;
313
+ if (lease.host !== os.hostname()) {
314
+ return Date.now() - lease.since <= ACTIVE_LEASE_FOREIGN_HOST_STALE_MS;
315
+ }
316
+ if (!nodeProcess?.kill || !lease.pid) return true;
317
+ try {
318
+ nodeProcess.kill(lease.pid, 0);
319
+ return true;
320
+ } catch (e) {
321
+ return e.code === "EPERM";
322
+ }
323
+ }
324
+ async function readLiveLeaseJobIds() {
325
+ const lease = await readActiveLease();
326
+ return new Set(isLeaseLive(lease) ? lease.jobIds : []);
327
+ }
328
+ async function writeActiveLease(jobIds) {
329
+ await ensureDir();
330
+ const lease = {
331
+ jobIds,
332
+ since: Date.now(),
333
+ pid: nodeProcess?.pid ?? 0,
334
+ host: os.hostname()
335
+ };
336
+ await writeFileAtomic(activeFile, JSON.stringify(lease, null, 2));
337
+ }
338
+ async function releaseActiveLease() {
339
+ await fsp.rm(activeFile, { force: true }).catch((err) => {
340
+ logger.error("Failed to release the active-job lease", { err });
341
+ reportQueueError(err, "queue.active_lease_release_failed");
342
+ });
343
+ }
344
+ function buildFollowUpJob(record) {
345
+ const next = record.coalesceNext;
346
+ if (!next) return null;
347
+ const availableAt = next.delayMs && next.delayMs > 0 ? new Date(Date.now() + next.delayMs).toISOString() : void 0;
348
+ return {
349
+ id: next.id,
350
+ payload: next.payload,
351
+ createdAt: next.createdAt,
352
+ ...availableAt ? { availableAt } : {},
353
+ ...next.metadata ? { metadata: next.metadata } : {},
354
+ ...record.coalesceKey ? { coalesceKey: record.coalesceKey } : {}
355
+ };
356
+ }
357
+ function warnAboutDiscardedFollowUps(records) {
358
+ const coalesceKeys = records.filter((record) => record.coalesceNext).map((record) => record.coalesceKey ?? record.id);
359
+ if (coalesceKeys.length === 0) return;
360
+ logger.warn(
361
+ "Discarded coalesced follow-up jobs while clearing the queue",
362
+ { coalesceKeys }
363
+ );
364
+ }
365
+ async function enqueue(data, options2) {
366
+ validateEnqueueOptions(options2);
367
+ return publishWithTimeout(() => publish(data, options2), options2?.timeoutMs);
368
+ }
369
+ async function publish(data, options2) {
370
+ const delayMs = options2?.delayMs && options2.delayMs > 0 ? options2.delayMs : void 0;
371
+ const availableAt = delayMs ? new Date(Date.now() + delayMs).toISOString() : void 0;
372
+ const traceMetadata = attachTraceMetadata(void 0);
373
+ const jobType = resolveJobType({ payload: data, metadata: { jobType: options2?.jobType } });
374
+ const metadata = jobType ? { ...traceMetadata ?? {}, jobType } : traceMetadata;
375
+ const coalesceKey = resolveCoalesceKey(data, options2, coalesceBy);
376
+ const job = {
377
+ id: options2?.jobId ?? generateId(),
378
+ payload: data,
379
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
380
+ ...availableAt ? { availableAt } : {},
381
+ ...metadata ? { metadata } : {},
382
+ ...coalesceKey ? { coalesceKey } : {}
383
+ };
384
+ if (!coalesceKey) {
385
+ await withFileLock(async () => {
386
+ const jobs = await readQueue();
387
+ if (options2?.jobId && jobs.some((existing) => existing.id === job.id)) return;
388
+ jobs.push(job);
389
+ await writeQueue(jobs);
390
+ });
391
+ return job.id;
392
+ }
393
+ return withFileLock(async () => {
394
+ const jobs = await readQueue();
395
+ if (options2?.jobId && jobs.some((existing) => existing.id === job.id)) return job.id;
396
+ const current = jobs.find((candidate) => candidate.coalesceKey === coalesceKey);
397
+ if (!current) {
398
+ jobs.push(job);
399
+ await writeQueue(jobs);
400
+ return job.id;
401
+ }
402
+ if ((await readLiveLeaseJobIds()).has(current.id)) {
403
+ current.coalesceNext = {
404
+ id: job.id,
405
+ payload: data,
406
+ createdAt: job.createdAt,
407
+ ...metadata ? { metadata } : {},
408
+ ...delayMs ? { delayMs } : {}
409
+ };
410
+ await writeQueue(jobs);
411
+ return current.id;
412
+ }
413
+ const inRetryBackoff = (current.attemptCount ?? 0) > 0;
414
+ const currentAvailableAtMs = current.availableAt ? new Date(current.availableAt).getTime() : 0;
415
+ const incomingAvailableAtMs = availableAt ? new Date(availableAt).getTime() : 0;
416
+ if (!inRetryBackoff && currentAvailableAtMs > incomingAvailableAtMs) {
417
+ if (availableAt) current.availableAt = availableAt;
418
+ else delete current.availableAt;
419
+ await writeQueue(jobs);
420
+ return current.id;
421
+ }
422
+ return current.id;
423
+ });
424
+ }
425
+ async function processBatch(handler, options2) {
426
+ const { state, jobs, jobsToProcess } = await withFileLock(async () => {
427
+ const stateRead = await readState();
428
+ const jobsRead = await readQueue();
429
+ const pendingJobs = jobsRead.filter((job) => {
430
+ if (!job.availableAt) return true;
431
+ return new Date(job.availableAt).getTime() <= Date.now();
432
+ });
433
+ const selectedJobs = options2?.limit ? pendingJobs.slice(0, options2.limit) : pendingJobs;
434
+ if (selectedJobs.length > 0) {
435
+ await writeActiveLease(selectedJobs.map((job) => job.id));
436
+ }
437
+ return { state: stateRead, jobs: jobsRead, jobsToProcess: selectedJobs };
438
+ });
439
+ hasQueuedJobs = jobs.length > 0;
440
+ for (const job of jobsToProcess) {
441
+ inFlightJobIds.add(job.id);
442
+ }
443
+ let processed = 0;
444
+ let failed = 0;
445
+ let lastJobId;
446
+ const completedJobIds = /* @__PURE__ */ new Set();
447
+ const deadJobIds = /* @__PURE__ */ new Set();
448
+ const retryPatches = /* @__PURE__ */ new Map();
449
+ const leaseWritten = jobsToProcess.length > 0;
450
+ try {
451
+ for (const job of jobsToProcess) {
452
+ const attemptNumber = (job.attemptCount ?? 0) + 1;
453
+ try {
454
+ await runJobInTrace(
455
+ name,
456
+ job.metadata,
457
+ () => Promise.resolve(
458
+ handler(job, {
459
+ jobId: job.id,
460
+ attemptNumber,
461
+ queueName: name
462
+ })
463
+ )
464
+ );
465
+ processed++;
466
+ lastJobId = job.id;
467
+ completedJobIds.add(job.id);
468
+ logger.info("Job completed", { jobId: job.id });
469
+ } catch (error) {
470
+ logger.error("Job failed", { jobId: job.id, attemptNumber, maxAttempts: DEFAULT_MAX_ATTEMPTS, err: error });
471
+ const exhausted = attemptNumber >= DEFAULT_MAX_ATTEMPTS;
472
+ reportQueueError(error, exhausted ? "queue.job_exhausted" : "queue.job_failed", {
473
+ jobId: job.id,
474
+ attemptNumber
475
+ });
476
+ failed++;
477
+ lastJobId = job.id;
478
+ if (exhausted) {
479
+ logger.error("Job exhausted all attempts; dropping it (no dead-letter store)", { jobId: job.id, maxAttempts: DEFAULT_MAX_ATTEMPTS });
480
+ deadJobIds.add(job.id);
481
+ } else {
482
+ const backoffMs = RETRY_BACKOFF_BASE_MS * Math.pow(2, attemptNumber - 1);
483
+ retryPatches.set(job.id, {
484
+ attemptCount: attemptNumber,
485
+ availableAt: new Date(Date.now() + backoffMs).toISOString()
486
+ });
487
+ }
488
+ }
489
+ }
490
+ const hasChanges = completedJobIds.size > 0 || deadJobIds.size > 0 || retryPatches.size > 0;
491
+ if (hasChanges) {
492
+ await withFileLock(async () => {
493
+ const currentJobs = await readQueue();
494
+ const finalizedJobIds = /* @__PURE__ */ new Set([...completedJobIds, ...deadJobIds]);
495
+ const followUpJobs = currentJobs.filter((j) => finalizedJobIds.has(j.id)).map((j) => buildFollowUpJob(j)).filter((j) => j !== null);
496
+ const updatedJobs = currentJobs.filter((j) => !finalizedJobIds.has(j.id)).map((j) => {
497
+ const patch = retryPatches.get(j.id);
498
+ return patch ? { ...j, ...patch } : j;
499
+ });
500
+ updatedJobs.push(...followUpJobs);
501
+ await writeQueue(updatedJobs);
502
+ hasQueuedJobs = updatedJobs.length > 0;
503
+ const newState = {
504
+ lastProcessedId: lastJobId,
505
+ completedCount: (state.completedCount ?? 0) + processed,
506
+ failedCount: (state.failedCount ?? 0) + deadJobIds.size
507
+ };
508
+ await writeState(newState);
509
+ });
510
+ }
511
+ return { processed, failed, lastJobId };
512
+ } finally {
513
+ for (const job of jobsToProcess) {
514
+ inFlightJobIds.delete(job.id);
515
+ }
516
+ if (leaseWritten) {
517
+ await releaseActiveLease();
518
+ }
519
+ }
520
+ }
521
+ async function pollAndProcess(rethrow = false) {
522
+ if (!activeHandler) return;
523
+ if (isProcessing) {
524
+ pollRequested = true;
525
+ return;
526
+ }
527
+ isProcessing = true;
528
+ try {
529
+ do {
530
+ pollRequested = false;
531
+ const handler = activeHandler;
532
+ if (!handler) break;
533
+ await processBatch(handler);
534
+ } while (pollRequested);
535
+ } catch (error) {
536
+ if (rethrow) throw error;
537
+ logger.error("Polling error", { err: error });
538
+ } finally {
539
+ isProcessing = false;
540
+ scheduleQueuedPoll();
541
+ }
542
+ }
543
+ function scheduleQueuedPoll() {
544
+ if (!activeHandler || !hasQueuedJobs) {
545
+ if (queuedPollTimer) {
546
+ clearTimeout(queuedPollTimer);
547
+ queuedPollTimer = null;
548
+ }
549
+ return;
550
+ }
551
+ if (queuedPollTimer) return;
552
+ queuedPollTimer = setTimeout(() => {
553
+ queuedPollTimer = null;
554
+ void pollAndProcess();
555
+ }, pollInterval);
556
+ }
557
+ function closeQueueWatcher() {
558
+ if (queueWatcher) {
559
+ queueWatcher.close();
560
+ queueWatcher = null;
561
+ }
562
+ queueWatcherIdentity = null;
563
+ }
564
+ function refreshQueueWatcher() {
565
+ const refresh = watcherRefreshChain.then(async () => {
566
+ if (!activeHandler) return;
567
+ try {
568
+ if (await isFileMissing(queueFile)) await withFileLock(createMissingQueueFiles);
569
+ const stats = await fsp.stat(queueFile);
570
+ const nextIdentity = { device: stats.dev, inode: stats.ino };
571
+ if (queueWatcher && queueWatcherIdentity?.device === nextIdentity.device && queueWatcherIdentity.inode === nextIdentity.inode) {
572
+ return;
573
+ }
574
+ closeQueueWatcher();
575
+ const watcher = fs.watch(queueFile, (eventType) => {
576
+ if (eventType === "rename") {
577
+ queueWatcherIdentity = null;
578
+ void refreshQueueWatcher();
579
+ }
580
+ void pollAndProcess();
581
+ });
582
+ watcher.on("error", (err) => {
583
+ logger.error("Queue watch error; fallback polling remains active", { err });
584
+ if (queueWatcher === watcher) {
585
+ closeQueueWatcher();
586
+ }
587
+ });
588
+ if (!activeHandler) {
589
+ watcher.close();
590
+ return;
591
+ }
592
+ queueWatcher = watcher;
593
+ queueWatcherIdentity = nextIdentity;
594
+ } catch (err) {
595
+ logger.error("Failed to watch queue file; fallback polling remains active", { err });
596
+ }
597
+ });
598
+ watcherRefreshChain = refresh.catch(() => void 0);
599
+ return refresh;
600
+ }
601
+ async function process(handler, options2) {
602
+ if (options2?.limit) {
603
+ await releaseActiveLease();
604
+ return processBatch(handler, options2);
605
+ }
606
+ if (activeHandler) {
607
+ await close();
608
+ }
609
+ await releaseActiveLease();
610
+ activeHandler = handler;
611
+ try {
612
+ await refreshQueueWatcher();
613
+ await pollAndProcess(true);
614
+ } catch (error) {
615
+ await close();
616
+ throw error;
617
+ }
618
+ pollingTimer = setInterval(() => {
619
+ refreshQueueWatcher().then(() => pollAndProcess()).catch((err) => {
620
+ logger.error("Poll cycle error", { err });
621
+ });
622
+ }, fallbackPollInterval);
623
+ logger.info("Worker started", { concurrency });
624
+ return { processed: -1, failed: -1, lastJobId: void 0 };
625
+ }
626
+ async function clear() {
627
+ return withFileLock(async () => {
628
+ const jobs = await readQueue();
629
+ const removed = jobs.length;
630
+ warnAboutDiscardedFollowUps(jobs);
631
+ await writeQueue([]);
632
+ hasQueuedJobs = false;
633
+ scheduleQueuedPoll();
634
+ const state = await readState();
635
+ await writeState({
636
+ completedCount: state.completedCount,
637
+ failedCount: state.failedCount
638
+ });
639
+ return { removed };
640
+ });
641
+ }
642
+ async function removeQueuedJobsByScope(scope) {
643
+ return withFileLock(async () => {
644
+ const jobs = await readQueue();
645
+ const retainedJobs = jobs.filter((job) => inFlightJobIds.has(job.id) || !payloadMatchesScope(job.payload, scope));
646
+ const removed = jobs.length - retainedJobs.length;
647
+ if (removed > 0) {
648
+ const retainedIds = new Set(retainedJobs.map((job) => job.id));
649
+ warnAboutDiscardedFollowUps(jobs.filter((job) => !retainedIds.has(job.id)));
650
+ await writeQueue(retainedJobs);
651
+ }
652
+ hasQueuedJobs = retainedJobs.length > 0;
653
+ scheduleQueuedPoll();
654
+ return { removed };
655
+ });
656
+ }
657
+ async function close() {
658
+ activeHandler = null;
659
+ if (queuedPollTimer) {
660
+ clearTimeout(queuedPollTimer);
661
+ queuedPollTimer = null;
662
+ }
663
+ closeQueueWatcher();
664
+ if (pollingTimer) {
665
+ clearInterval(pollingTimer);
666
+ pollingTimer = null;
667
+ }
668
+ const SHUTDOWN_TIMEOUT = 5e3;
669
+ const startTime = Date.now();
670
+ while (isProcessing) {
671
+ if (Date.now() - startTime > SHUTDOWN_TIMEOUT) {
672
+ logger.warn("Force closing after shutdown timeout", { timeoutMs: SHUTDOWN_TIMEOUT });
673
+ break;
674
+ }
675
+ await new Promise((resolve) => setTimeout(resolve, 50));
676
+ }
677
+ }
678
+ async function getJobCounts() {
679
+ return withFileLock(async () => {
680
+ const state = await readState();
681
+ const jobs = await readQueue();
682
+ const leasedJobIds = await readLiveLeaseJobIds();
683
+ const active = jobs.filter((job) => leasedJobIds.has(job.id)).length;
684
+ return {
685
+ // A job stays stored while it runs, so waiting is what is left once the active ones are
686
+ // discounted.
687
+ waiting: jobs.length - active,
688
+ active,
689
+ completed: state.completedCount ?? 0,
690
+ failed: state.failedCount ?? 0
691
+ // `delayed` omitted: this strategy keeps no delayed-job state distinct from waiting.
692
+ };
693
+ });
694
+ }
695
+ const MAX_IN_FLIGHT_LIMIT = 50;
696
+ const DEFAULT_IN_FLIGHT_LIMIT = 20;
697
+ const MAX_RECENT_JOBS_LIMIT = 100;
698
+ const DEFAULT_RECENT_JOBS_LIMIT = 20;
699
+ const MAX_INTROSPECTION_FILE_BYTES = 8 * 1024 * 1024;
700
+ const INTROSPECTION_CACHE_TTL_MS = 2e3;
701
+ let introspectionCache = null;
702
+ function jobEnqueuedAtMs(job) {
703
+ const parsed = Date.parse(job.createdAt);
704
+ return Number.isFinite(parsed) ? parsed : void 0;
705
+ }
706
+ function classifyPending(job, now) {
707
+ if (!job.availableAt) return "waiting";
708
+ const availableAt = Date.parse(job.availableAt);
709
+ return Number.isFinite(availableAt) && availableAt > now ? "delayed" : "waiting";
710
+ }
711
+ async function readIntrospectionSnapshot() {
712
+ let stats;
713
+ try {
714
+ stats = await fsp.stat(queueFile);
715
+ } catch (error) {
716
+ if (error.code === "ENOENT") return [];
717
+ throw new QueueIntrospectionUnavailableError("Local queue file is not readable");
718
+ }
719
+ if (stats.size > MAX_INTROSPECTION_FILE_BYTES) {
720
+ throw new QueueIntrospectionUnavailableError("Local queue backlog is too large to introspect");
721
+ }
722
+ const key = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
723
+ const now = Date.now();
724
+ if (introspectionCache && introspectionCache.key === key && now - introspectionCache.at < INTROSPECTION_CACHE_TTL_MS) {
725
+ return introspectionCache.jobs;
726
+ }
727
+ let parsed;
728
+ try {
729
+ parsed = JSON.parse(await fsp.readFile(queueFile, "utf8"));
730
+ } catch (error) {
731
+ if (error.code === "ENOENT") return [];
732
+ throw new QueueIntrospectionUnavailableError("Local queue file could not be parsed");
733
+ }
734
+ if (!Array.isArray(parsed)) throw new QueueIntrospectionUnavailableError("Local queue file is malformed");
735
+ introspectionCache = { key, at: now, jobs: parsed };
736
+ return introspectionCache.jobs;
737
+ }
738
+ async function getProcessingStats() {
739
+ return { sampleSize: 0, fidelity: "partial" };
740
+ }
741
+ async function getInFlightJobsSummary(opts) {
742
+ const state = opts.state ?? "active";
743
+ if (state === "active") return [];
744
+ const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_IN_FLIGHT_LIMIT, MAX_IN_FLIGHT_LIMIT);
745
+ if (cappedLimit === 0) return [];
746
+ const jobs = await readIntrospectionSnapshot();
747
+ const now = Date.now();
748
+ const matching = jobs.filter(
749
+ (job) => classifyPending(job, now) === state && (!opts.type || resolveJobType(job) === opts.type)
750
+ );
751
+ const head = state === "delayed" ? matching.sort((a, b) => (Date.parse(a.availableAt ?? "") || 0) - (Date.parse(b.availableAt ?? "") || 0)) : matching;
752
+ return head.slice(0, cappedLimit).map((job) => {
753
+ const enqueuedAt = jobEnqueuedAtMs(job);
754
+ return {
755
+ id: job.id,
756
+ queue: name,
757
+ type: resolveJobType(job),
758
+ state,
759
+ enqueuedAt,
760
+ ageMs: enqueuedAt !== void 0 ? now - enqueuedAt : void 0,
761
+ attemptsMade: job.attemptCount
762
+ };
763
+ });
764
+ }
765
+ function toRecentJob(job, state) {
766
+ return {
767
+ id: job.id,
768
+ queue: name,
769
+ state,
770
+ type: resolveJobType(job),
771
+ timestamp: jobEnqueuedAtMs(job),
772
+ attemptsMade: job.attemptCount,
773
+ data: job.payload
774
+ };
775
+ }
776
+ async function getRecentJobs(opts) {
777
+ if (opts.id) {
778
+ const jobs2 = await readIntrospectionSnapshot();
779
+ const job = jobs2.find((candidate) => candidate.id === opts.id);
780
+ return job ? [toRecentJob(job, classifyPending(job, Date.now()))] : [];
781
+ }
782
+ if (opts.state && opts.state !== "waiting" && opts.state !== "delayed") return [];
783
+ const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_RECENT_JOBS_LIMIT, MAX_RECENT_JOBS_LIMIT);
784
+ if (cappedLimit === 0) return [];
785
+ const boundedOffset = resolveOffset(opts.offset);
786
+ const jobs = await readIntrospectionSnapshot();
787
+ const now = Date.now();
788
+ const result = [];
789
+ let skipped = 0;
790
+ for (let index = jobs.length - 1; index >= 0 && result.length < cappedLimit; index--) {
791
+ const job = jobs[index];
792
+ const state = classifyPending(job, now);
793
+ if (opts.state && state !== opts.state) continue;
794
+ if (opts.type && resolveJobType(job) !== opts.type) continue;
795
+ if (skipped < boundedOffset) {
796
+ skipped++;
797
+ continue;
798
+ }
799
+ result.push(toRecentJob(job, state));
800
+ }
801
+ return result;
802
+ }
803
+ return {
804
+ name,
805
+ strategy: "local",
806
+ enqueue,
807
+ process,
808
+ clear,
809
+ removeQueuedJobsByScope,
810
+ close,
811
+ getJobCounts,
812
+ getProcessingStats,
813
+ getInFlightJobsSummary,
814
+ getRecentJobs
815
+ };
816
+ }
817
+ export {
818
+ createLocalQueue
819
+ };
820
+ //# sourceMappingURL=strategy.js.map