@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.
- package/.turbo/turbo-build.log +2 -0
- package/README.md +6 -2
- package/build.mjs +11 -0
- package/dist/base-dir.js +10 -0
- package/dist/base-dir.js.map +7 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +7 -0
- package/dist/probe.js +49 -0
- package/dist/probe.js.map +7 -0
- package/dist/strategy.js +820 -0
- package/dist/strategy.js.map +7 -0
- package/package.json +40 -3
- package/src/base-dir.ts +8 -0
- package/src/index.ts +53 -0
- package/src/probe.ts +55 -0
- package/src/strategy.ts +1279 -0
- package/tsconfig.json +10 -0
- package/watch.mjs +6 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/strategy.ts"],
|
|
4
|
+
"sourcesContent": ["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport crypto from 'node:crypto'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport type {\n Queue,\n QueuedJob,\n JobHandler,\n LocalQueueOptions,\n ProcessOptions,\n ProcessResult,\n EnqueueOptions,\n QueueJobScope,\n QueueProcessingStats,\n InFlightJobSummary,\n RecentJob,\n} from '@open-mercato/queue-provider-kit/types'\nimport { resolveCoalesceKey } from '@open-mercato/queue-provider-kit/coalescing'\nimport { attachTraceMetadata, runJobInTrace } from '@open-mercato/queue-provider-kit/tracing'\nimport {\n QueueIntrospectionUnavailableError,\n resolveJobType,\n resolveOffset,\n resolveWindowSize,\n} from '@open-mercato/queue-provider-kit/introspection'\nimport { publishWithTimeout, validateEnqueueOptions } from '@open-mercato/queue-provider-kit/publication'\nimport { resolveLocalQueueBaseDir } from './base-dir'\n\nconst packageLogger = createLogger('queue')\n\ntype LocalState = {\n lastProcessedId?: string\n completedCount?: number\n failedCount?: number\n}\n\n/**\n * The enqueue that arrived while its coalescing twin was already running, parked on that twin's\n * record until it finishes. At most one exists per record: a later arrival overwrites it, so the\n * follow-up run always carries the latest payload.\n *\n * It keeps the id minted for the latest enqueue in the active burst, matching BullMQ's stored\n * proto-job. The caller receives the active job's id because that is the outstanding job BullMQ\n * reports for a deduplicated add; the follow-up id is internal until the job is promoted.\n */\ntype CoalescedNextJob<T> = {\n id: string\n payload: T\n createdAt: string\n metadata?: Record<string, unknown>\n delayMs?: number\n}\n\ntype StoredJob<T> = QueuedJob<T> & {\n availableAt?: string\n attemptCount?: number\n /** Coalescing key. While a record carries it, further enqueues for that key collapse into it. */\n coalesceKey?: string\n coalesceNext?: CoalescedNextJob<T>\n}\n\n/**\n * The consumer's record of which jobs it selected into the current batch and has not yet finalized\n * on disk. Selection captures the payload, so every selected id is leased before the lock opens \u2014\n * including jobs whose handlers have not started yet.\n *\n * Producers run in other processes, so `inFlightJobIds` cannot answer \"is this job running right\n * now?\" for them \u2014 and that question is the whole of `keepLastIfActive`. Hence a file. It has\n * exactly one writer (the strategy's single consumer, see the topology note above), so it needs an\n * atomic replacement.\n */\ntype ActiveLease = {\n jobIds: string[]\n since: number\n pid: number\n host: string\n}\n\ntype QueueFileIdentity = {\n device: number\n inode: number\n}\n\nfunction payloadMatchesScope(payload: unknown, scope: QueueJobScope): boolean {\n if (!payload || typeof payload !== 'object') return false\n const scopedPayload = payload as { tenantId?: unknown; organizationId?: unknown; jobType?: unknown }\n if (scopedPayload.tenantId !== scope.tenantId) return false\n if (scope.organizationId !== undefined) {\n if ((scopedPayload.organizationId ?? null) !== scope.organizationId) return false\n }\n if (scope.jobTypes?.length) {\n return typeof scopedPayload.jobType === 'string' && scope.jobTypes.includes(scopedPayload.jobType)\n }\n return true\n}\n\n/** Polling interval while delayed or retrying work remains queued. */\nconst DEFAULT_POLL_INTERVAL = 1000\n/** Idle safety interval for missed filesystem watcher events. */\nconst DEFAULT_FALLBACK_POLL_INTERVAL = 5000\nconst DEFAULT_MAX_ATTEMPTS = 3\nconst RETRY_BACKOFF_BASE_MS = 1000\n\n/**\n * Cross-process lock tuning. A held lock only ever spans local file I/O \u2014 job\n * handlers run outside it \u2014 so realistic hold times are milliseconds and the\n * stale threshold sits orders of magnitude above them. It exists solely so a\n * process that dies mid-segment cannot wedge the queue forever. A holder that\n * was merely suspended rather than dead can still be reclaimed, which is why\n * every acquisition carries an owner token and releases only its own lock.\n */\n/**\n * How long a lease written by a *different host* is believed. On the same host a lease is checked\n * against its owner's pid instead, which is exact and imposes no ceiling on how long a job may run.\n * A file-backed queue shared across hosts is outside this strategy's contract, so this is only a\n * backstop that keeps such a setup from wedging on a lease nobody will ever clear.\n */\nconst ACTIVE_LEASE_FOREIGN_HOST_STALE_MS = 15 * 60 * 1000\n\nconst LOCK_STALE_MS = 15_000\nconst LOCK_ACQUIRE_TIMEOUT_MS = 30_000\nconst LOCK_RETRY_MIN_MS = 2\nconst LOCK_RETRY_MAX_MS = 20\nconst RENAME_MAX_RETRIES = 5\nconst RENAME_RETRY_BASE_MS = 10\n\nconst fsp = fs.promises\n\n/**\n * Creates a file-based local queue.\n *\n * Jobs are stored in JSON files within a directory structure:\n * - `.mercato/queue/<name>/queue.json` - Array of queued jobs\n * - `.mercato/queue/<name>/state.json` - Processing state (last processed ID)\n * - `.mercato/queue/<name>/active.json` - Which jobs the consumer selected (created on demand)\n *\n * `EnqueueOptions.coalesce` is honoured here, not just by the `async` strategy, so development and\n * integration runs collapse bursts the way production does. A record carrying `coalesceKey` *is* the\n * key \u2014 no separate index, because a local job stays stored for its whole life. Coalescing needs one\n * thing that cannot be derived from `queue.json`, namely whether a job is running right now, and\n * `active.json` supplies it across processes.\n *\n * **Limitations:**\n * - Jobs are processed sequentially (concurrency option is for logging/compatibility only)\n * - Not suitable for production: there is no dead-letter store, no throughput\n * beyond one job at a time, and every operation rewrites the whole queue file\n *\n * Multiple processes MAY share a queue directory, which is the default\n * development topology: the dev worker runs in its own process alongside the\n * Next.js server. What that buys you, and what it does not:\n *\n * - **Safe** \u2014 concurrent producers. Every read-modify-write segment takes the\n * `queue.lock` directory lock and every persist swaps the file in with an\n * atomic rename, so the file cannot be torn, no enqueue is lost to a\n * concurrent one, and a reader always observes one complete document.\n * Writers contend, though, so throughput degrades as processes are added.\n * - **NOT safe** \u2014 concurrent consumers. `process()` deliberately runs job\n * handlers outside the lock, so two worker processes polling the same queue\n * would both claim the same pending jobs and execute them twice. There is no\n * per-job lease. Run exactly one worker process per queue; use the `async`\n * strategy when you need more than one.\n *\n * Failed jobs are retried up to `DEFAULT_MAX_ATTEMPTS` times with exponential backoff.\n * **This strategy keeps no failed-job store**: once attempts are exhausted the job is\n * removed from `queue.json` and only counted in `state.failedCount`, so the payload is\n * lost and the failure survives solely as an error log line. The `async` strategy keeps\n * only a bounded inspection window: `removeOnFail: 1000` retains the most recent 1000\n * failures and removes older ones as later failures arrive. Workflows that require\n * no-loss persistence must write their own durable record before enqueueing, regardless\n * of strategy.\n *\n * `DEFAULT_MAX_ATTEMPTS` is a module constant, not a per-job option \u2014 callers cannot\n * request a different attempt count. (`async` likewise hard-codes `attempts: 3`.)\n * See the retry handling in `process()` below.\n *\n * All file I/O is asynchronous (`fs.promises.*`) so queue operations do not\n * block the Node.js event loop. A per-queue promise chain serializes\n * read-modify-write sequences within one instance, and the `queue.lock`\n * directory lock extends that serialization across instances and processes.\n *\n * @template T - The payload type for jobs\n * @param name - Queue name (used for directory naming)\n * @param options - Local queue options\n */\nexport function createLocalQueue<T = unknown>(\n name: string,\n options?: LocalQueueOptions<T>\n): Queue<T> {\n const nodeProcess = (globalThis as typeof globalThis & { process?: NodeJS.Process }).process\n // Captured here because `enqueue`'s own `options` parameter shadows this one.\n const coalesceBy = options?.coalesceBy\n const baseDir = resolveLocalQueueBaseDir(options?.baseDir)\n const queueDir = path.join(baseDir, name)\n const queueFile = path.join(queueDir, 'queue.json')\n const stateFile = path.join(queueDir, 'state.json')\n const activeFile = path.join(queueDir, 'active.json')\n const lockDir = path.join(queueDir, 'queue.lock')\n const lockOwnerFile = path.join(lockDir, 'owner')\n const logger = packageLogger.child({ queue: name })\n\n /**\n * Report a job failure outward, so the log line is not the only record of it.\n * Wrapped: reporting is never worth a poll cycle.\n */\n function reportQueueError(\n error: unknown,\n code: string,\n attributes?: Record<string, string | number | undefined>,\n ): void {\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'queue',\n code,\n attributes: { queue: name, ...attributes },\n })\n } catch (telemetryError) {\n // Reporting is never worth a worker \u2014 but a systematically broken bridge\n // must not be silent either, or a worker stops reporting and nothing says so.\n logger.warn('Failed to report a queue error to telemetry', { code, err: telemetryError as Error })\n }\n }\n // Note: concurrency is stored for logging/compatibility but jobs are processed sequentially\n const concurrency = options?.concurrency ?? 1\n const pollInterval = options?.pollInterval ?? DEFAULT_POLL_INTERVAL\n const fallbackPollInterval = Math.max(pollInterval, DEFAULT_FALLBACK_POLL_INTERVAL)\n\n // Worker state for continuous polling\n let pollingTimer: ReturnType<typeof setInterval> | null = null\n let queuedPollTimer: ReturnType<typeof setTimeout> | null = null\n let queueWatcher: fs.FSWatcher | null = null\n let queueWatcherIdentity: QueueFileIdentity | null = null\n let watcherRefreshChain: Promise<void> = Promise.resolve()\n let hasQueuedJobs = false\n let isProcessing = false\n let pollRequested = false\n let activeHandler: JobHandler<T> | null = null\n const inFlightJobIds = new Set<string>()\n\n // Per-queue mutex. Serializes read-modify-write segments so async fs calls\n // cannot interleave and clobber each other's writes. It only covers this\n // instance, so it also guarantees at most one outstanding `queue.lock`\n // acquisition per instance \u2014 the directory lock below is not reentrant.\n let fileOpChain: Promise<unknown> = Promise.resolve()\n function withFileLock<R>(fn: () => Promise<R>): Promise<R> {\n const run = fileOpChain.then(\n () => runExclusively(fn),\n () => runExclusively(fn),\n )\n fileOpChain = run.then(\n () => undefined,\n () => undefined,\n )\n return run\n }\n\n /**\n * Runs `fn` while holding the cross-process `queue.lock`, so read-modify-write\n * segments issued by other queue instances \u2014 in this process or another one \u2014\n * cannot interleave with it.\n */\n async function runExclusively<R>(fn: () => Promise<R>): Promise<R> {\n await ensureDir()\n const release = await acquireDirectoryLock()\n try {\n await createMissingQueueFiles()\n return await fn()\n } finally {\n await release()\n }\n }\n\n // -------------------------------------------------------------------------\n // File Operations\n // -------------------------------------------------------------------------\n\n function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => { setTimeout(resolve, ms) })\n }\n\n async function lockHeldForMs(): Promise<number | null> {\n try {\n const stats = await fsp.stat(lockDir)\n return Date.now() - stats.mtimeMs\n } catch {\n return null\n }\n }\n\n /**\n * Reclaims a lock whose holder died. The rename is the serialization point:\n * only one racer can move `queue.lock` aside, so two processes cannot both\n * decide a stale lock is theirs to clear and then both create a fresh one.\n */\n async function reclaimStaleLock(heldForMs: number): Promise<void> {\n const reclaimedPath = `${lockDir}.stale.${crypto.randomUUID()}`\n try {\n await fsp.rename(lockDir, reclaimedPath)\n } catch {\n return\n }\n logger.warn('Reclaimed a stale queue lock', { lockDir, heldForMs })\n await fsp.rm(reclaimedPath, { recursive: true, force: true }).catch(() => {})\n }\n\n async function readLockOwner(): Promise<string | null> {\n try {\n return await fsp.readFile(lockOwnerFile, 'utf8')\n } catch {\n return null\n }\n }\n\n /**\n * Releases the lock only when this acquisition still owns it. A holder that\n * was suspended past `LOCK_STALE_MS` has had its lock reclaimed *and\n * replaced* by whoever reclaimed it, so an unconditional removal here would\n * delete the successor's lock and let a third caller into the critical\n * section alongside it. A missing or mismatched token means someone else owns\n * the path now, and the correct action is to leave it alone.\n */\n async function releaseDirectoryLock(token: string): Promise<void> {\n if (await readLockOwner() !== token) return\n await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {})\n }\n\n /**\n * Acquires the cross-process advisory lock for this queue directory.\n * `mkdir` without `recursive` is an atomic exclusive create on every platform\n * Node.js supports, which makes it the portable primitive here \u2014 no runtime\n * dependency, and no reliance on advisory `flock` semantics. The owner token\n * written into the directory is what lets the release distinguish this\n * acquisition from a successor's.\n */\n async function acquireDirectoryLock(): Promise<() => Promise<void>> {\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS\n\n for (;;) {\n let acquired = false\n try {\n await fsp.mkdir(lockDir)\n acquired = true\n } catch (e: unknown) {\n const error = e as NodeJS.ErrnoException\n if (error.code !== 'EEXIST') throw error\n }\n\n if (acquired) {\n const token = crypto.randomUUID()\n try {\n await fsp.writeFile(lockOwnerFile, token, 'utf8')\n } catch (error: unknown) {\n await fsp.rm(lockDir, { recursive: true, force: true }).catch(() => {})\n throw error\n }\n return () => releaseDirectoryLock(token)\n }\n\n const heldForMs = await lockHeldForMs()\n if (heldForMs !== null && heldForMs > LOCK_STALE_MS) {\n await reclaimStaleLock(heldForMs)\n continue\n }\n\n if (Date.now() >= deadline) {\n throw new Error(\n `[internal] Timed out after ${LOCK_ACQUIRE_TIMEOUT_MS}ms waiting for the queue lock at ${lockDir}`,\n )\n }\n\n const jitter = LOCK_RETRY_MIN_MS + Math.random() * (LOCK_RETRY_MAX_MS - LOCK_RETRY_MIN_MS)\n await sleep(jitter)\n }\n }\n\n /**\n * Persists `content` by writing a unique sibling temp file and renaming it\n * onto `targetFile`. `rename` within a directory is atomic, so a concurrent\n * reader sees either the previous document or the new one in full \u2014 never the\n * torn result of a truncate-then-write.\n */\n async function writeFileAtomic(targetFile: string, content: string): Promise<void> {\n const tempFile = `${targetFile}.${crypto.randomUUID()}.tmp`\n try {\n await fsp.writeFile(tempFile, content, 'utf8')\n await renameWithContentionRetry(tempFile, targetFile)\n } catch (error: unknown) {\n await fsp.rm(tempFile, { force: true }).catch(() => {})\n throw error\n }\n }\n\n /**\n * Windows rejects a rename onto a file another process currently has open,\n * so retry briefly on the contention codes it raises. POSIX renames replace\n * the target unconditionally and take the first attempt.\n */\n async function renameWithContentionRetry(fromFile: string, toFile: string): Promise<void> {\n const contentionCodes = new Set(['EPERM', 'EBUSY', 'EACCES'])\n for (let attempt = 0; ; attempt++) {\n try {\n await fsp.rename(fromFile, toFile)\n return\n } catch (e: unknown) {\n const error = e as NodeJS.ErrnoException\n if (attempt >= RENAME_MAX_RETRIES || !error.code || !contentionCodes.has(error.code)) throw error\n await sleep(RENAME_RETRY_BASE_MS * (attempt + 1))\n }\n }\n }\n\n async function ensureDir(): Promise<void> {\n try {\n await fsp.mkdir(queueDir, { recursive: true })\n } catch (e: unknown) {\n const error = e as NodeJS.ErrnoException\n if (error.code !== 'EEXIST') throw error\n }\n }\n\n async function isFileMissing(targetFile: string): Promise<boolean> {\n try {\n await fsp.access(targetFile)\n return false\n } catch (e: unknown) {\n const error = e as NodeJS.ErrnoException\n if (error.code !== 'ENOENT') throw error\n return true\n }\n }\n\n /**\n * Publishes `queue.json` and `state.json` when absent. Call it only while\n * holding `queue.lock`: the lock keeps another instance from writing the same\n * file between the existence check and the rename, and the rename keeps every\n * reader from seeing a half-created file.\n */\n async function createMissingQueueFiles(): Promise<void> {\n if (await isFileMissing(queueFile)) await writeFileAtomic(queueFile, '[]')\n if (await isFileMissing(stateFile)) await writeFileAtomic(stateFile, '{}')\n }\n\n /**\n * Moves an unparsable queue file aside so its jobs stay recoverable. The\n * caller is expected to surface the failure rather than continue on an empty\n * queue: silently recreating `queue.json` here is what turned an unreadable\n * file into permanent, unreported job loss.\n */\n async function quarantineCorruptedQueueFile(): Promise<string | null> {\n const backupFile = path.join(queueDir, `queue.corrupted.${Date.now()}.${crypto.randomUUID()}.json`)\n try {\n await fsp.rename(queueFile, backupFile)\n return backupFile\n } catch (e: unknown) {\n logger.error('Failed to quarantine the corrupted queue file', { err: e as Error })\n return null\n }\n }\n\n async function readQueue(): Promise<StoredJob<T>[]> {\n await ensureDir()\n let content: string\n\n try {\n content = await fsp.readFile(queueFile, 'utf8')\n } catch (error: unknown) {\n const readError = error as NodeJS.ErrnoException\n if (readError.code === 'ENOENT') {\n return []\n }\n logger.error('Failed to read queue file', { err: readError })\n throw new Error(`Queue file unreadable: ${readError.message}`)\n }\n\n try {\n const parsed = JSON.parse(content) as unknown\n\n if (!Array.isArray(parsed)) {\n throw new Error('Queue file must contain a JSON array')\n }\n\n return parsed as StoredJob<T>[]\n } catch (error: unknown) {\n const parseError = error as Error\n logger.error('Failed to parse queue file', { err: parseError })\n const backupFile = await quarantineCorruptedQueueFile()\n if (backupFile) {\n logger.error('Quarantined corrupted queue file; its jobs are recoverable from the backup', { backupFile })\n }\n const recoveryHint = backupFile\n ? `has been quarantined as ${backupFile}`\n : 'could not be quarantined and was left in place'\n throw new Error(\n `[internal] Queue file ${queueFile} was unparsable and ${recoveryHint}: ${parseError.message}`,\n )\n }\n }\n\n async function writeQueue(jobs: StoredJob<T>[]): Promise<void> {\n await ensureDir()\n await writeFileAtomic(queueFile, JSON.stringify(jobs, null, 2))\n }\n\n async function readState(): Promise<LocalState> {\n await ensureDir()\n try {\n const content = await fsp.readFile(stateFile, 'utf8')\n return JSON.parse(content) as LocalState\n } catch {\n return {}\n }\n }\n\n async function writeState(state: LocalState): Promise<void> {\n await ensureDir()\n await writeFileAtomic(stateFile, JSON.stringify(state, null, 2))\n }\n\n function generateId(): string {\n return crypto.randomUUID()\n }\n\n // -------------------------------------------------------------------------\n // Active lease\n // -------------------------------------------------------------------------\n\n /**\n * Reads the consumer's lease.\n *\n * Unreadable or unparsable content is discarded rather than quarantined, the mirror image of\n * `readQueue`'s fail-closed handling: a lease holds no payload anyone could recover, and the worst\n * consequence of losing one is a job that runs twice \u2014 which is the pre-feature behaviour and\n * within the queue's at-least-once contract. Refusing to enqueue over a damaged lease, by\n * contrast, would turn a cosmetic file into an outage.\n */\n async function readActiveLease(): Promise<ActiveLease | null> {\n let content: string\n try {\n content = await fsp.readFile(activeFile, 'utf8')\n } catch (e: unknown) {\n const readError = e as NodeJS.ErrnoException\n if (readError.code !== 'ENOENT') {\n logger.error('Failed to read the active-job lease; treating it as empty', { err: readError })\n reportQueueError(readError, 'queue.active_lease_read_failed')\n }\n return null\n }\n\n try {\n const parsed = JSON.parse(content) as Partial<ActiveLease>\n if (!parsed || !Array.isArray(parsed.jobIds)) {\n throw new Error('Active-job lease must be an object with a jobIds array')\n }\n return {\n jobIds: parsed.jobIds.filter((id): id is string => typeof id === 'string'),\n since: typeof parsed.since === 'number' ? parsed.since : 0,\n pid: typeof parsed.pid === 'number' ? parsed.pid : 0,\n host: typeof parsed.host === 'string' ? parsed.host : '',\n }\n } catch (e: unknown) {\n const parseError = e as Error\n logger.error('Failed to parse the active-job lease; discarding it', { err: parseError })\n reportQueueError(parseError, 'queue.active_lease_parse_failed')\n await fsp.rm(activeFile, { force: true }).catch(() => {})\n return null\n }\n }\n\n /**\n * Whether a lease still describes a running consumer. A lease left behind by a crash must not\n * deduplicate enqueues forever, and the strategy has no per-job heartbeat to fall back on.\n */\n function isLeaseLive(lease: ActiveLease | null): lease is ActiveLease {\n if (!lease || lease.jobIds.length === 0) return false\n if (lease.host !== os.hostname()) {\n return Date.now() - lease.since <= ACTIVE_LEASE_FOREIGN_HOST_STALE_MS\n }\n if (!nodeProcess?.kill || !lease.pid) return true\n try {\n nodeProcess.kill(lease.pid, 0)\n return true\n } catch (e: unknown) {\n // EPERM means the pid exists but belongs to another user, so the owner is alive.\n return (e as NodeJS.ErrnoException).code === 'EPERM'\n }\n }\n\n async function readLiveLeaseJobIds(): Promise<Set<string>> {\n const lease = await readActiveLease()\n return new Set(isLeaseLive(lease) ? lease.jobIds : [])\n }\n\n /**\n * Publishes the lease with an atomic rename while the queue lock still protects job selection,\n * closing the gap where a producer could mistake a selected job for a waiting one.\n */\n async function writeActiveLease(jobIds: string[]): Promise<void> {\n await ensureDir()\n const lease: ActiveLease = {\n jobIds,\n since: Date.now(),\n pid: nodeProcess?.pid ?? 0,\n host: os.hostname(),\n }\n await writeFileAtomic(activeFile, JSON.stringify(lease, null, 2))\n }\n\n async function releaseActiveLease(): Promise<void> {\n await fsp.rm(activeFile, { force: true }).catch((err: unknown) => {\n logger.error('Failed to release the active-job lease', { err })\n reportQueueError(err, 'queue.active_lease_release_failed')\n })\n }\n\n /**\n * Builds the follow-up job parked on a finalized record by `keepLastIfActive`.\n *\n * Everything except the delay comes from the latest producer enqueue. Only `availableAt` is\n * recomputed, because a delay means \"after the enqueue is acted on\", and that moment is now.\n */\n function buildFollowUpJob(record: StoredJob<T>): StoredJob<T> | null {\n const next = record.coalesceNext\n if (!next) return null\n const availableAt = next.delayMs && next.delayMs > 0\n ? new Date(Date.now() + next.delayMs).toISOString()\n : undefined\n return {\n id: next.id,\n payload: next.payload,\n createdAt: next.createdAt,\n ...(availableAt ? { availableAt } : {}),\n ...(next.metadata ? { metadata: next.metadata } : {}),\n ...(record.coalesceKey ? { coalesceKey: record.coalesceKey } : {}),\n }\n }\n\n function warnAboutDiscardedFollowUps(records: StoredJob<T>[]): void {\n const coalesceKeys = records\n .filter((record) => record.coalesceNext)\n .map((record) => record.coalesceKey ?? record.id)\n if (coalesceKeys.length === 0) return\n logger.warn(\n 'Discarded coalesced follow-up jobs while clearing the queue',\n { coalesceKeys },\n )\n }\n\n // -------------------------------------------------------------------------\n // Queue Implementation\n // -------------------------------------------------------------------------\n\n async function enqueue(data: T, options?: EnqueueOptions): Promise<string> {\n validateEnqueueOptions(options)\n return publishWithTimeout(() => publish(data, options), options?.timeoutMs)\n }\n\n async function publish(data: T, options?: EnqueueOptions): Promise<string> {\n const delayMs = options?.delayMs && options.delayMs > 0 ? options.delayMs : undefined\n const availableAt = delayMs ? new Date(Date.now() + delayMs).toISOString() : undefined\n const traceMetadata = attachTraceMetadata(undefined)\n // Payload-free job type for the status dashboard (same contract as the async strategy).\n const jobType = resolveJobType({ payload: data, metadata: { jobType: options?.jobType } })\n const metadata = jobType ? { ...(traceMetadata ?? {}), jobType } : traceMetadata\n const coalesceKey = resolveCoalesceKey(data, options, coalesceBy)\n const job: StoredJob<T> = {\n id: options?.jobId ?? generateId(),\n payload: data,\n createdAt: new Date().toISOString(),\n ...(availableAt ? { availableAt } : {}),\n ...(metadata ? { metadata } : {}),\n ...(coalesceKey ? { coalesceKey } : {}),\n }\n\n if (!coalesceKey) {\n await withFileLock(async () => {\n const jobs = await readQueue()\n if (options?.jobId && jobs.some((existing) => existing.id === job.id)) return\n jobs.push(job)\n await writeQueue(jobs)\n })\n return job.id\n }\n\n // The whole decision runs inside one locked segment, so a concurrent producer cannot slip an\n // enqueue between the lookup and the write, and the consumer cannot finalize the job being\n // examined halfway through.\n return withFileLock(async () => {\n const jobs = await readQueue()\n if (options?.jobId && jobs.some((existing) => existing.id === job.id)) return job.id\n const current = jobs.find((candidate) => candidate.coalesceKey === coalesceKey)\n if (!current) {\n jobs.push(job)\n await writeQueue(jobs)\n return job.id\n }\n\n if ((await readLiveLeaseJobIds()).has(current.id)) {\n // The running job read its input before this enqueue existed, so dropping the enqueue would\n // lose the write it represents. Park it; the consumer promotes it when the current run ends.\n current.coalesceNext = {\n id: job.id,\n payload: data,\n createdAt: job.createdAt,\n ...(metadata ? { metadata } : {}),\n ...(delayMs ? { delayMs } : {}),\n }\n await writeQueue(jobs)\n return current.id\n }\n\n // The twin is merely waiting, so it has read nothing and will observe this enqueue's writes\n // when it runs \u2014 but only if it runs no later than this enqueue asked for. Carrying the\n // earlier of the two moments keeps the guarantee one-directional: collapsing may cost a\n // caller a run that happens sooner than it asked, never one that never comes. Dropping the\n // incoming schedule instead would defer an immediate enqueue behind a delayed twin, which is\n // the silently-lost write this feature exists to prevent.\n //\n // A record in retry backoff is excluded: there `availableAt` is not a schedule any caller\n // asked for but the failure handler's spacing, and pulling it forward would let a burst of\n // triggers hot-loop a job that is failing. A retry keeps its key and its backoff both.\n const inRetryBackoff = (current.attemptCount ?? 0) > 0\n const currentAvailableAtMs = current.availableAt ? new Date(current.availableAt).getTime() : 0\n const incomingAvailableAtMs = availableAt ? new Date(availableAt).getTime() : 0\n if (!inRetryBackoff && currentAvailableAtMs > incomingAvailableAtMs) {\n if (availableAt) current.availableAt = availableAt\n else delete current.availableAt\n await writeQueue(jobs)\n return current.id\n }\n\n // Coalesced with nothing to record: deliberately no write at all. Rewriting `queue.json`\n // here would rename the file and wake the consumer's watcher for a job that does not exist,\n // which is precisely the work coalescing exists to avoid.\n return current.id\n })\n }\n\n /**\n * Process pending jobs in a single batch (internal helper).\n */\n async function processBatch(\n handler: JobHandler<T>,\n options?: ProcessOptions\n ): Promise<ProcessResult> {\n const { state, jobs, jobsToProcess } = await withFileLock(async () => {\n const stateRead = await readState()\n const jobsRead = await readQueue()\n const pendingJobs = jobsRead.filter((job) => {\n if (!job.availableAt) return true\n return new Date(job.availableAt).getTime() <= Date.now()\n })\n const selectedJobs = options?.limit\n ? pendingJobs.slice(0, options.limit)\n : pendingJobs\n if (selectedJobs.length > 0) {\n await writeActiveLease(selectedJobs.map((job) => job.id))\n }\n return { state: stateRead, jobs: jobsRead, jobsToProcess: selectedJobs }\n })\n hasQueuedJobs = jobs.length > 0\n\n for (const job of jobsToProcess) {\n inFlightJobIds.add(job.id)\n }\n\n let processed = 0\n let failed = 0\n let lastJobId: string | undefined\n const completedJobIds = new Set<string>()\n const deadJobIds = new Set<string>()\n // Patches rather than whole records: the record is re-read below, and a producer may have parked\n // a `coalesceNext` on it while the handler ran. Rewriting it from the pre-run snapshot\n // would silently discard that enqueue.\n const retryPatches = new Map<string, { attemptCount: number; availableAt: string }>()\n const leaseWritten = jobsToProcess.length > 0\n\n try {\n for (const job of jobsToProcess) {\n const attemptNumber = (job.attemptCount ?? 0) + 1\n try {\n await runJobInTrace(name, job.metadata, () =>\n Promise.resolve(\n handler(job, {\n jobId: job.id,\n attemptNumber,\n queueName: name,\n })\n )\n )\n processed++\n lastJobId = job.id\n completedJobIds.add(job.id)\n logger.info('Job completed', { jobId: job.id })\n } catch (error) {\n logger.error('Job failed', { jobId: job.id, attemptNumber, maxAttempts: DEFAULT_MAX_ATTEMPTS, err: error })\n const exhausted = attemptNumber >= DEFAULT_MAX_ATTEMPTS\n // One report per failure, coded by what the failure means: a job that\n // has burned every retry is dead, which is the condition an operator\n // pages on, and it must be distinguishable from a first attempt that\n // will simply be retried. Reporting both would double-count `om.errors`\n // on the final attempt.\n reportQueueError(error, exhausted ? 'queue.job_exhausted' : 'queue.job_failed', {\n jobId: job.id,\n attemptNumber,\n })\n failed++\n lastJobId = job.id\n if (exhausted) {\n logger.error('Job exhausted all attempts; dropping it (no dead-letter store)', { jobId: job.id, maxAttempts: DEFAULT_MAX_ATTEMPTS })\n deadJobIds.add(job.id)\n } else {\n const backoffMs = RETRY_BACKOFF_BASE_MS * Math.pow(2, attemptNumber - 1)\n retryPatches.set(job.id, {\n attemptCount: attemptNumber,\n availableAt: new Date(Date.now() + backoffMs).toISOString(),\n })\n }\n }\n }\n\n const hasChanges = completedJobIds.size > 0 || deadJobIds.size > 0 || retryPatches.size > 0\n if (hasChanges) {\n await withFileLock(async () => {\n // Re-read so jobs enqueued during handler execution are preserved.\n const currentJobs = await readQueue()\n const finalizedJobIds = new Set([...completedJobIds, ...deadJobIds])\n // A job that exhausted its attempts is finalized too, exactly as a completed one is.\n // Leaving its key behind would deduplicate every later enqueue onto a record that no\n // longer exists, and would strand its follow-up.\n const followUpJobs = currentJobs\n .filter((j) => finalizedJobIds.has(j.id))\n .map((j) => buildFollowUpJob(j))\n .filter((j): j is StoredJob<T> => j !== null)\n const updatedJobs = currentJobs\n .filter((j) => !finalizedJobIds.has(j.id))\n .map((j) => {\n const patch = retryPatches.get(j.id)\n return patch ? { ...j, ...patch } : j\n })\n // Appended in the same write that removes the job they were parked on, so there is never a\n // moment where a burst could produce a third job for one coalescing key.\n updatedJobs.push(...followUpJobs)\n await writeQueue(updatedJobs)\n hasQueuedJobs = updatedJobs.length > 0\n\n const newState: LocalState = {\n lastProcessedId: lastJobId,\n completedCount: (state.completedCount ?? 0) + processed,\n failedCount: (state.failedCount ?? 0) + deadJobIds.size,\n }\n await writeState(newState)\n })\n }\n\n return { processed, failed, lastJobId }\n } finally {\n for (const job of jobsToProcess) {\n inFlightJobIds.delete(job.id)\n }\n // After the closing write, so a job is never both stored and unleased.\n if (leaseWritten) {\n await releaseActiveLease()\n }\n }\n }\n\n /**\n * Poll for and process new jobs.\n */\n async function pollAndProcess(rethrow = false): Promise<void> {\n if (!activeHandler) return\n if (isProcessing) {\n pollRequested = true\n return\n }\n\n isProcessing = true\n try {\n do {\n pollRequested = false\n const handler = activeHandler\n if (!handler) break\n await processBatch(handler)\n } while (pollRequested)\n } catch (error) {\n if (rethrow) throw error\n logger.error('Polling error', { err: error })\n } finally {\n isProcessing = false\n scheduleQueuedPoll()\n }\n }\n\n function scheduleQueuedPoll(): void {\n if (!activeHandler || !hasQueuedJobs) {\n if (queuedPollTimer) {\n clearTimeout(queuedPollTimer)\n queuedPollTimer = null\n }\n return\n }\n if (queuedPollTimer) return\n queuedPollTimer = setTimeout(() => {\n queuedPollTimer = null\n void pollAndProcess()\n }, pollInterval)\n }\n\n function closeQueueWatcher(): void {\n if (queueWatcher) {\n queueWatcher.close()\n queueWatcher = null\n }\n queueWatcherIdentity = null\n }\n\n function refreshQueueWatcher(): Promise<void> {\n const refresh = watcherRefreshChain.then(async () => {\n if (!activeHandler) return\n try {\n if (await isFileMissing(queueFile)) await withFileLock(createMissingQueueFiles)\n const stats = await fsp.stat(queueFile)\n const nextIdentity = { device: stats.dev, inode: stats.ino }\n if (\n queueWatcher\n && queueWatcherIdentity?.device === nextIdentity.device\n && queueWatcherIdentity.inode === nextIdentity.inode\n ) {\n return\n }\n\n closeQueueWatcher()\n const watcher = fs.watch(queueFile, (eventType) => {\n if (eventType === 'rename') {\n queueWatcherIdentity = null\n void refreshQueueWatcher()\n }\n void pollAndProcess()\n })\n watcher.on('error', (err) => {\n logger.error('Queue watch error; fallback polling remains active', { err })\n if (queueWatcher === watcher) {\n closeQueueWatcher()\n }\n })\n if (!activeHandler) {\n watcher.close()\n return\n }\n queueWatcher = watcher\n queueWatcherIdentity = nextIdentity\n } catch (err) {\n logger.error('Failed to watch queue file; fallback polling remains active', { err })\n }\n })\n watcherRefreshChain = refresh.catch(() => undefined)\n return refresh\n }\n\n async function process(\n handler: JobHandler<T>,\n options?: ProcessOptions\n ): Promise<ProcessResult> {\n // If limit is specified, do a single batch (backward compatibility)\n if (options?.limit) {\n await releaseActiveLease()\n return processBatch(handler, options)\n }\n\n if (activeHandler) {\n await close()\n }\n\n // A consumer is starting, and this strategy admits exactly one consumer per queue, so any lease\n // still on disk belongs to a run that will never finish. Clearing it is the authoritative\n // recovery from a crashed consumer: the jobs it named are still stored, so they simply run\n // again, carrying any parked follow-up with them. The alternative \u2014 ageing leases out \u2014 would\n // have to guess a ceiling on how long a handler may legitimately take.\n await releaseActiveLease()\n\n // Start continuous polling mode (like BullMQ Worker)\n activeHandler = handler\n\n try {\n await refreshQueueWatcher()\n await pollAndProcess(true)\n } catch (error) {\n await close()\n throw error\n }\n\n pollingTimer = setInterval(() => {\n refreshQueueWatcher().then(() => pollAndProcess()).catch((err) => {\n logger.error('Poll cycle error', { err })\n })\n }, fallbackPollInterval)\n\n logger.info('Worker started', { concurrency })\n\n // Return sentinel value indicating continuous worker mode (like async strategy)\n return { processed: -1, failed: -1, lastJobId: undefined }\n }\n\n async function clear(): Promise<{ removed: number }> {\n return withFileLock(async () => {\n const jobs = await readQueue()\n const removed = jobs.length\n warnAboutDiscardedFollowUps(jobs)\n await writeQueue([])\n hasQueuedJobs = false\n scheduleQueuedPoll()\n // Reset state but preserve counts for historical tracking\n const state = await readState()\n await writeState({\n completedCount: state.completedCount,\n failedCount: state.failedCount,\n })\n return { removed }\n })\n }\n\n async function removeQueuedJobsByScope(scope: QueueJobScope): Promise<{ removed: number }> {\n return withFileLock(async () => {\n const jobs = await readQueue()\n const retainedJobs = jobs.filter((job) => inFlightJobIds.has(job.id) || !payloadMatchesScope(job.payload, scope))\n const removed = jobs.length - retainedJobs.length\n if (removed > 0) {\n const retainedIds = new Set(retainedJobs.map((job) => job.id))\n warnAboutDiscardedFollowUps(jobs.filter((job) => !retainedIds.has(job.id)))\n await writeQueue(retainedJobs)\n }\n hasQueuedJobs = retainedJobs.length > 0\n scheduleQueuedPoll()\n return { removed }\n })\n }\n\n async function close(): Promise<void> {\n activeHandler = null\n if (queuedPollTimer) {\n clearTimeout(queuedPollTimer)\n queuedPollTimer = null\n }\n closeQueueWatcher()\n\n // Stop polling timer\n if (pollingTimer) {\n clearInterval(pollingTimer)\n pollingTimer = null\n }\n // Wait for any in-progress processing to complete (with timeout)\n const SHUTDOWN_TIMEOUT = 5000\n const startTime = Date.now()\n\n while (isProcessing) {\n if (Date.now() - startTime > SHUTDOWN_TIMEOUT) {\n logger.warn('Force closing after shutdown timeout', { timeoutMs: SHUTDOWN_TIMEOUT })\n break\n }\n await new Promise((resolve) => setTimeout(resolve, 50))\n }\n }\n\n async function getJobCounts(): Promise<{\n waiting: number\n active: number\n completed: number\n failed: number\n }> {\n return withFileLock(async () => {\n const state = await readState()\n const jobs = await readQueue()\n // Intersected with the stored jobs rather than trusted outright, so a lease naming a job that\n // has since been cleared away cannot inflate the count or push `waiting` negative.\n const leasedJobIds = await readLiveLeaseJobIds()\n const active = jobs.filter((job) => leasedJobIds.has(job.id)).length\n\n return {\n // A job stays stored while it runs, so waiting is what is left once the active ones are\n // discounted.\n waiting: jobs.length - active,\n active,\n completed: state.completedCount ?? 0,\n failed: state.failedCount ?? 0,\n // `delayed` omitted: this strategy keeps no delayed-job state distinct from waiting.\n }\n })\n }\n\n const MAX_IN_FLIGHT_LIMIT = 50\n const DEFAULT_IN_FLIGHT_LIMIT = 20\n const MAX_RECENT_JOBS_LIMIT = 100\n const DEFAULT_RECENT_JOBS_LIMIT = 20\n /**\n * Largest `queue.json` the introspection reads will parse. The local strategy stores payloads\n * inline in one JSON document, so there is no index to window over: a read costs a full parse of\n * the file. Past this size the optional summaries report \"unavailable\" instead of scanning \u2014 the\n * (existing) counts stay available, and the `async` strategy is the one meant for real backlogs.\n */\n const MAX_INTROSPECTION_FILE_BYTES = 8 * 1024 * 1024\n /** One dashboard refresh issues several introspection calls; they share a single parse of an unchanged file. */\n const INTROSPECTION_CACHE_TTL_MS = 2000\n let introspectionCache: { key: string; at: number; jobs: StoredJob<T>[] } | null = null\n\n function jobEnqueuedAtMs(job: StoredJob<T>): number | undefined {\n const parsed = Date.parse(job.createdAt)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n\n /**\n * A pending job is `delayed` while its `availableAt` (a delayed enqueue or a retry backoff) is in\n * the future, `waiting` otherwise. Every introspection method classifies through here, so a job\n * is never reported as both.\n */\n function classifyPending(job: StoredJob<T>, now: number): 'waiting' | 'delayed' {\n if (!job.availableAt) return 'waiting'\n const availableAt = Date.parse(job.availableAt)\n return Number.isFinite(availableAt) && availableAt > now ? 'delayed' : 'waiting'\n }\n\n /**\n * Reads `queue.json` for introspection WITHOUT the worker file lock: every persist is an atomic\n * rename, so a reader always sees one complete document, and an admin dashboard must not stall\n * the worker's read-modify-write segments. Never quarantines a corrupt file (that is the worker\n * path's job) \u2014 it just reports the section unavailable.\n */\n async function readIntrospectionSnapshot(): Promise<StoredJob<T>[]> {\n let stats: fs.Stats\n try {\n stats = await fsp.stat(queueFile)\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw new QueueIntrospectionUnavailableError('Local queue file is not readable')\n }\n if (stats.size > MAX_INTROSPECTION_FILE_BYTES) {\n throw new QueueIntrospectionUnavailableError('Local queue backlog is too large to introspect')\n }\n\n const key = `${stats.ino}:${stats.size}:${stats.mtimeMs}`\n const now = Date.now()\n if (introspectionCache && introspectionCache.key === key && now - introspectionCache.at < INTROSPECTION_CACHE_TTL_MS) {\n return introspectionCache.jobs\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(await fsp.readFile(queueFile, 'utf8'))\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw new QueueIntrospectionUnavailableError('Local queue file could not be parsed')\n }\n if (!Array.isArray(parsed)) throw new QueueIntrospectionUnavailableError('Local queue file is malformed')\n\n introspectionCache = { key, at: now, jobs: parsed as StoredJob<T>[] }\n return introspectionCache.jobs\n }\n\n /**\n * No completed-job records are retained (`state.json` holds only a count), so\n * there is no sample to derive durations from. Reporting an honestly-empty\n * `partial` result \u2014 rather than a fabricated number \u2014 is this strategy's\n * documented fallback (see the class doc comment on retention).\n */\n async function getProcessingStats(): Promise<QueueProcessingStats> {\n return { sampleSize: 0, fidelity: 'partial' }\n }\n\n /**\n * Best-effort from the pending-job file. `active` has no cross-process\n * meaning here \u2014 a worker's `inFlightJobIds` is private, in-memory state in\n * whichever process is actually polling, invisible to this call from an\n * admin-surface process \u2014 so it always reports empty for that state.\n * `waiting` and `delayed` partition the pending jobs (see `classifyPending`).\n */\n async function getInFlightJobsSummary(opts: {\n state?: 'active' | 'waiting' | 'delayed'\n type?: string\n limit: number\n }): Promise<InFlightJobSummary[]> {\n const state = opts.state ?? 'active'\n if (state === 'active') return []\n const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_IN_FLIGHT_LIMIT, MAX_IN_FLIGHT_LIMIT)\n if (cappedLimit === 0) return []\n\n const jobs = await readIntrospectionSnapshot()\n const now = Date.now()\n // `queue.json` is append-ordered, so file order IS oldest-first (the head of the queue \u2014 the\n // jobs that look stuck). Delayed jobs are ordered by when they become available instead.\n const matching = jobs.filter(\n (job) => classifyPending(job, now) === state && (!opts.type || resolveJobType(job) === opts.type),\n )\n const head = state === 'delayed'\n ? matching.sort((a, b) => (Date.parse(a.availableAt ?? '') || 0) - (Date.parse(b.availableAt ?? '') || 0))\n : matching\n\n return head.slice(0, cappedLimit).map((job) => {\n const enqueuedAt = jobEnqueuedAtMs(job)\n return {\n id: job.id,\n queue: name,\n type: resolveJobType(job),\n state,\n enqueuedAt,\n ageMs: enqueuedAt !== undefined ? now - enqueuedAt : undefined,\n attemptsMade: job.attemptCount,\n }\n })\n }\n\n function toRecentJob(job: StoredJob<T>, state: 'waiting' | 'delayed'): RecentJob {\n return {\n id: job.id,\n queue: name,\n state,\n type: resolveJobType(job),\n timestamp: jobEnqueuedAtMs(job),\n attemptsMade: job.attemptCount,\n data: job.payload,\n }\n }\n\n /**\n * Tier 2 (privileged) ONLY. This strategy keeps no retained completed/failed\n * store and cannot see active jobs, so only the pending `waiting` / `delayed`\n * states exist; every other requested state is an honest empty result rather\n * than pending jobs relabelled.\n */\n async function getRecentJobs(opts: {\n state?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed'\n type?: string\n id?: string\n limit: number\n offset?: number\n }): Promise<RecentJob[]> {\n if (opts.id) {\n const jobs = await readIntrospectionSnapshot()\n const job = jobs.find((candidate) => candidate.id === opts.id)\n return job ? [toRecentJob(job, classifyPending(job, Date.now()))] : []\n }\n\n if (opts.state && opts.state !== 'waiting' && opts.state !== 'delayed') return []\n const cappedLimit = resolveWindowSize(opts.limit, DEFAULT_RECENT_JOBS_LIMIT, MAX_RECENT_JOBS_LIMIT)\n if (cappedLimit === 0) return []\n const boundedOffset = resolveOffset(opts.offset)\n\n const jobs = await readIntrospectionSnapshot()\n const now = Date.now()\n const result: RecentJob[] = []\n let skipped = 0\n // Newest-first, mirroring the async strategy's ordering contract: walk the append-ordered file backwards.\n for (let index = jobs.length - 1; index >= 0 && result.length < cappedLimit; index--) {\n const job = jobs[index]\n const state = classifyPending(job, now)\n if (opts.state && state !== opts.state) continue\n if (opts.type && resolveJobType(job) !== opts.type) continue\n if (skipped < boundedOffset) {\n skipped++\n continue\n }\n result.push(toRecentJob(job, state))\n }\n return result\n }\n\n return {\n name,\n strategy: 'local',\n enqueue,\n process,\n clear,\n removeQueuedJobsByScope,\n close,\n getJobCounts,\n getProcessingStats,\n getInFlightJobsSummary,\n getRecentJobs,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAcpC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB,qBAAqB;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,E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
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/queue-provider-local",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.11.1-develop.8983.1.8f477e3f83",
|
|
4
|
+
"description": "Default file-backed queue provider for Open Mercato",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "node build.mjs",
|
|
17
|
+
"watch": "node watch.mjs",
|
|
18
|
+
"typecheck": "tsc --noEmit"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^26.4.0",
|
|
22
|
+
"typescript": "7.0.2"
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "https://github.com/open-mercato/open-mercato",
|
|
30
|
+
"directory": "packages/queue-provider-local"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@open-mercato/queue-provider-kit": "0.11.1-develop.8983.1.8f477e3f83",
|
|
34
|
+
"@open-mercato/shared": "0.11.1-develop.8983.1.8f477e3f83"
|
|
35
|
+
},
|
|
36
|
+
"openMercato": {
|
|
37
|
+
"queueDriver": {
|
|
38
|
+
"contractVersion": 1,
|
|
39
|
+
"edition": "oss"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"stableVersion": "0.11.0"
|
|
6
43
|
}
|
package/src/base-dir.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
|
|
3
|
+
const DEFAULT_LOCAL_QUEUE_BASE_DIR = '.mercato/queue'
|
|
4
|
+
|
|
5
|
+
export function resolveLocalQueueBaseDir(baseDir?: string): string {
|
|
6
|
+
const nodeProcess = (globalThis as typeof globalThis & { process?: NodeJS.Process }).process
|
|
7
|
+
return baseDir ?? path.resolve(nodeProcess?.env?.QUEUE_BASE_DIR || DEFAULT_LOCAL_QUEUE_BASE_DIR)
|
|
8
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { link, mkdir, readFile, realpath, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import packageMetadata from '../package.json' with { type: 'json' }
|
|
5
|
+
import type { DefaultQueueDriver } from '@open-mercato/queue-provider-kit/default-provider'
|
|
6
|
+
import { resolveLocalQueueBaseDir } from './base-dir'
|
|
7
|
+
import { probeLocalQueue } from './probe'
|
|
8
|
+
import { createLocalQueue } from './strategy'
|
|
9
|
+
|
|
10
|
+
const storageIdFile = '.queue-storage-id'
|
|
11
|
+
|
|
12
|
+
async function readOrCreateStorageId(baseDir: string): Promise<string> {
|
|
13
|
+
const filename = path.join(baseDir, storageIdFile)
|
|
14
|
+
let identity: string
|
|
15
|
+
try {
|
|
16
|
+
identity = await readFile(filename, 'utf8')
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
19
|
+
const candidate = randomUUID()
|
|
20
|
+
const temporary = path.join(baseDir, `${storageIdFile}.${candidate}.tmp`)
|
|
21
|
+
await writeFile(temporary, candidate, { flag: 'wx', mode: 0o600 })
|
|
22
|
+
try {
|
|
23
|
+
await link(temporary, filename)
|
|
24
|
+
} catch (linkError) {
|
|
25
|
+
if ((linkError as NodeJS.ErrnoException).code !== 'EEXIST') throw linkError
|
|
26
|
+
} finally {
|
|
27
|
+
await unlink(temporary)
|
|
28
|
+
}
|
|
29
|
+
identity = await readFile(filename, 'utf8')
|
|
30
|
+
}
|
|
31
|
+
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(identity)) {
|
|
32
|
+
throw new Error('[internal] Invalid local queue storage identity')
|
|
33
|
+
}
|
|
34
|
+
return identity
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const queueDriver: DefaultQueueDriver<'local'> = {
|
|
38
|
+
contractVersion: 1,
|
|
39
|
+
edition: 'oss',
|
|
40
|
+
strategy: 'local',
|
|
41
|
+
packageVersion: packageMetadata.version,
|
|
42
|
+
createQueue: createLocalQueue,
|
|
43
|
+
probe: probeLocalQueue,
|
|
44
|
+
async resourceIdentity(name, options) {
|
|
45
|
+
const baseDir = path.resolve(resolveLocalQueueBaseDir(options?.baseDir))
|
|
46
|
+
await mkdir(baseDir, { recursive: true })
|
|
47
|
+
const canonical = await realpath(baseDir)
|
|
48
|
+
const storageId = await readOrCreateStorageId(canonical)
|
|
49
|
+
return createHash('sha256').update(JSON.stringify([storageId, path.join(canonical, name)])).digest('hex')
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { createLocalQueue }
|
package/src/probe.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { emptyProbe, failedProbe, type QueuePendingProbeOptions, type QueuePendingProbeResult } from '@open-mercato/queue-provider-kit/default-provider'
|
|
4
|
+
import { resolveLocalQueueBaseDir } from './base-dir'
|
|
5
|
+
|
|
6
|
+
export async function probeLocalQueue(
|
|
7
|
+
queueName: string,
|
|
8
|
+
options?: QueuePendingProbeOptions,
|
|
9
|
+
): Promise<QueuePendingProbeResult> {
|
|
10
|
+
const baseDir = resolveLocalQueueBaseDir(options?.baseDir)
|
|
11
|
+
const queueFile = path.join(baseDir, queueName, 'queue.json')
|
|
12
|
+
|
|
13
|
+
let raw: string
|
|
14
|
+
try {
|
|
15
|
+
raw = await readFile(queueFile, 'utf8')
|
|
16
|
+
} catch (err) {
|
|
17
|
+
const fsErr = err as NodeJS.ErrnoException
|
|
18
|
+
if (fsErr?.code === 'ENOENT') {
|
|
19
|
+
return emptyProbe(queueName, 'local')
|
|
20
|
+
}
|
|
21
|
+
return failedProbe(queueName, 'local', err)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let parsed: unknown
|
|
25
|
+
try {
|
|
26
|
+
parsed = JSON.parse(raw)
|
|
27
|
+
} catch (err) {
|
|
28
|
+
return failedProbe(queueName, 'local', err)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!Array.isArray(parsed)) {
|
|
32
|
+
return emptyProbe(queueName, 'local')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const now = Date.now()
|
|
36
|
+
let ready = 0
|
|
37
|
+
let delayedFuture = 0
|
|
38
|
+
|
|
39
|
+
for (const entry of parsed) {
|
|
40
|
+
if (!entry || typeof entry !== 'object') continue
|
|
41
|
+
const availableAt = (entry as { availableAt?: unknown }).availableAt
|
|
42
|
+
if (typeof availableAt !== 'string' || availableAt.length === 0) {
|
|
43
|
+
ready++
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
const ts = Date.parse(availableAt)
|
|
47
|
+
if (!Number.isFinite(ts) || ts <= now) {
|
|
48
|
+
ready++
|
|
49
|
+
} else {
|
|
50
|
+
delayedFuture++
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { queueName, strategy: 'local', ready, delayedFuture, active: 0, error: false }
|
|
55
|
+
}
|