@open-mercato/queue-provider-kit 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/build.mjs +10 -0
- package/dist/coalescing.js +8 -0
- package/dist/coalescing.js.map +7 -0
- package/dist/default-provider.js +15 -0
- package/dist/default-provider.js.map +7 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +7 -0
- package/dist/introspection.js +89 -0
- package/dist/introspection.js.map +7 -0
- package/dist/publication.js +27 -0
- package/dist/publication.js.map +7 -0
- package/dist/tracing.js +27 -0
- package/dist/tracing.js.map +7 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +7 -0
- package/package.json +56 -3
- package/src/coalescing.ts +18 -0
- package/src/default-provider.ts +42 -0
- package/src/index.ts +2 -0
- package/src/introspection.ts +131 -0
- package/src/publication.ts +29 -0
- package/src/tracing.ts +58 -0
- package/src/types.ts +561 -0
- package/tsconfig.json +10 -0
- package/watch.mjs +6 -0
- package/README.md +0 -3
package/build.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { dirname } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { buildPackage } from '../../scripts/build-package.mjs'
|
|
4
|
+
|
|
5
|
+
const packageDir = dirname(fileURLToPath(import.meta.url))
|
|
6
|
+
|
|
7
|
+
await buildPackage(packageDir, {
|
|
8
|
+
name: 'queue-provider-kit',
|
|
9
|
+
entryPoints: 'src/**/*.ts',
|
|
10
|
+
})
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/coalescing.ts"],
|
|
4
|
+
"sourcesContent": ["import type { CoalesceKeyResolver, EnqueueOptions } from './types'\n\n/**\n * Resolves the coalescing key for one enqueue.\n *\n * A key passed at the call site wins over the queue's own `coalesceBy`, so a caller can coalesce\n * something the queue does not, or key one enqueue differently. Falsy results mean \"do not\n * coalesce\": a resolver returning `null` for payloads it has no opinion about is the documented way\n * to leave them alone, and an empty string is never a usable key.\n */\nexport function resolveCoalesceKey<T>(\n payload: T,\n options?: EnqueueOptions,\n coalesceBy?: CoalesceKeyResolver<T>,\n): string | undefined {\n if (options?.coalesce) return options.coalesce.key || undefined\n return coalesceBy?.(payload) || undefined\n}\n"],
|
|
5
|
+
"mappings": "AAUO,SAAS,mBACd,SACA,SACA,YACoB;AACpB,MAAI,SAAS,SAAU,QAAO,QAAQ,SAAS,OAAO;AACtD,SAAO,aAAa,OAAO,KAAK;AAClC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
function emptyProbe(queueName, strategy) {
|
|
2
|
+
return { queueName, strategy, ready: 0, delayedFuture: 0, active: 0, error: false };
|
|
3
|
+
}
|
|
4
|
+
function failedProbe(queueName, strategy, error) {
|
|
5
|
+
return {
|
|
6
|
+
...emptyProbe(queueName, strategy),
|
|
7
|
+
error: true,
|
|
8
|
+
errorMessage: error instanceof Error ? error.message : String(error)
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export {
|
|
12
|
+
emptyProbe,
|
|
13
|
+
failedProbe
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=default-provider.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/default-provider.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Queue, QueueOptions, QueueStrategyType, RedisConnectionOptions } from './types'\n\nexport type QueuePendingProbeOptions = {\n connection?: RedisConnectionOptions\n baseDir?: string\n}\n\nexport type QueuePendingProbeResult = {\n queueName: string\n strategy: QueueStrategyType\n /** Number of jobs ready to process now. */\n ready: number\n /** Number of jobs scheduled for the future. */\n delayedFuture: number\n /** Number of active jobs visible to the probe. */\n active: number\n /** The probe could not query storage. */\n error: boolean\n errorMessage?: string\n}\n\nexport type DefaultQueueDriver<Strategy extends QueueStrategyType> = {\n contractVersion: 1\n edition: 'oss'\n strategy: Strategy\n packageVersion: string\n createQueue<T = unknown>(name: string, options?: QueueOptions<Strategy, T>): Queue<T>\n probe(name: string, options?: QueuePendingProbeOptions): Promise<QueuePendingProbeResult>\n resourceIdentity<T = unknown>(name: string, options?: QueueOptions<Strategy, T>): Promise<string>\n}\n\nexport function emptyProbe(queueName: string, strategy: QueueStrategyType): QueuePendingProbeResult {\n return { queueName, strategy, ready: 0, delayedFuture: 0, active: 0, error: false }\n}\n\nexport function failedProbe(queueName: string, strategy: QueueStrategyType, error: unknown): QueuePendingProbeResult {\n return {\n ...emptyProbe(queueName, strategy),\n error: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n}\n"],
|
|
5
|
+
"mappings": "AA+BO,SAAS,WAAW,WAAmB,UAAsD;AAClG,SAAO,EAAE,WAAW,UAAU,OAAO,GAAG,eAAe,GAAG,QAAQ,GAAG,OAAO,MAAM;AACpF;AAEO,SAAS,YAAY,WAAmB,UAA6B,OAAyC;AACnH,SAAO;AAAA,IACL,GAAG,WAAW,WAAW,QAAQ;AAAA,IACjC,OAAO;AAAA,IACP,cAAc,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,EACrE;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const MAX_INTROSPECTION_OFFSET = 1e3;
|
|
2
|
+
const MAX_TYPE_FILTER_CANDIDATES = 200;
|
|
3
|
+
const MAX_JOB_TYPE_LENGTH = 128;
|
|
4
|
+
class QueueIntrospectionUnavailableError extends Error {
|
|
5
|
+
constructor(message = "[internal] Queue introspection is unavailable for this queue") {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = "queue.introspection_unavailable";
|
|
8
|
+
this.name = "QueueIntrospectionUnavailableError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function resolveWindowSize(value, fallback, max) {
|
|
12
|
+
const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : fallback;
|
|
13
|
+
return Math.max(0, Math.min(n, max));
|
|
14
|
+
}
|
|
15
|
+
function resolveOffset(value) {
|
|
16
|
+
const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : 0;
|
|
17
|
+
return Math.max(0, Math.min(n, MAX_INTROSPECTION_OFFSET));
|
|
18
|
+
}
|
|
19
|
+
function readStringField(source, key) {
|
|
20
|
+
if (!source || typeof source !== "object") return void 0;
|
|
21
|
+
const value = source[key];
|
|
22
|
+
if (typeof value !== "string") return void 0;
|
|
23
|
+
const trimmed = value.trim();
|
|
24
|
+
if (!trimmed || trimmed.length > MAX_JOB_TYPE_LENGTH) return void 0;
|
|
25
|
+
return trimmed;
|
|
26
|
+
}
|
|
27
|
+
function resolveJobType(envelope) {
|
|
28
|
+
if (!envelope) return void 0;
|
|
29
|
+
return readStringField(envelope.metadata, "jobType") ?? readStringField(envelope.payload, "jobType");
|
|
30
|
+
}
|
|
31
|
+
const QUEUE_FAILURE_CODES = [
|
|
32
|
+
"queue.job_stalled",
|
|
33
|
+
"queue.job_start_limit",
|
|
34
|
+
"queue.timeout",
|
|
35
|
+
"queue.connection_error",
|
|
36
|
+
"queue.handler_error"
|
|
37
|
+
];
|
|
38
|
+
function classifyFailureReason(reason) {
|
|
39
|
+
if (typeof reason !== "string" || reason.length === 0) return void 0;
|
|
40
|
+
if (reason === "job stalled more than allowable limit") return "queue.job_stalled";
|
|
41
|
+
if (reason === "job started more than allowable limit") return "queue.job_start_limit";
|
|
42
|
+
if (/\b(timed? ?out|timeout|ETIMEDOUT|deadline exceeded)\b/i.test(reason)) return "queue.timeout";
|
|
43
|
+
if (/\b(ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up)\b/i.test(reason)) {
|
|
44
|
+
return "queue.connection_error";
|
|
45
|
+
}
|
|
46
|
+
return "queue.handler_error";
|
|
47
|
+
}
|
|
48
|
+
const MAX_RAW_FAILED_REASON_LENGTH = 500;
|
|
49
|
+
function buildCompletedRetentionEnvelope(envelope) {
|
|
50
|
+
const payload = envelope.payload;
|
|
51
|
+
const kept = {};
|
|
52
|
+
if (payload && typeof payload === "object") {
|
|
53
|
+
const source = payload;
|
|
54
|
+
for (const key of ["tenantId", "organizationId", "jobType"]) {
|
|
55
|
+
if (typeof source[key] === "string") kept[key] = source[key];
|
|
56
|
+
else if (key === "organizationId" && source[key] === null) kept[key] = null;
|
|
57
|
+
}
|
|
58
|
+
const scope = source.scope;
|
|
59
|
+
if (scope && typeof scope === "object") {
|
|
60
|
+
const nested = {};
|
|
61
|
+
for (const key of ["tenantId", "organizationId"]) {
|
|
62
|
+
const value = scope[key];
|
|
63
|
+
if (typeof value === "string" || value === null) nested[key] = value;
|
|
64
|
+
}
|
|
65
|
+
if (Object.keys(nested).length > 0) kept.scope = nested;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const jobType = resolveJobType(envelope);
|
|
69
|
+
if (jobType && kept.jobType === void 0) kept.jobType = jobType;
|
|
70
|
+
return {
|
|
71
|
+
id: envelope.id,
|
|
72
|
+
payload: kept,
|
|
73
|
+
createdAt: envelope.createdAt,
|
|
74
|
+
...envelope.metadata ? { metadata: envelope.metadata } : {}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export {
|
|
78
|
+
MAX_INTROSPECTION_OFFSET,
|
|
79
|
+
MAX_RAW_FAILED_REASON_LENGTH,
|
|
80
|
+
MAX_TYPE_FILTER_CANDIDATES,
|
|
81
|
+
QUEUE_FAILURE_CODES,
|
|
82
|
+
QueueIntrospectionUnavailableError,
|
|
83
|
+
buildCompletedRetentionEnvelope,
|
|
84
|
+
classifyFailureReason,
|
|
85
|
+
resolveJobType,
|
|
86
|
+
resolveOffset,
|
|
87
|
+
resolveWindowSize
|
|
88
|
+
};
|
|
89
|
+
//# sourceMappingURL=introspection.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/introspection.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Shared, strategy-independent helpers for the payload-free queue introspection\n * contract (Queue Status Dashboard, #3105). Nothing here touches I/O.\n */\n\nimport type { QueuedJob } from './types'\n\n/** Hard cap on how far a caller may page into a window. */\nexport const MAX_INTROSPECTION_OFFSET = 1000\n/** How many candidates a strategy inspects when a job-type filter forces post-filtering. */\nexport const MAX_TYPE_FILTER_CANDIDATES = 200\nconst MAX_JOB_TYPE_LENGTH = 128\n\n/**\n * Thrown by a strategy when an optional introspection read cannot be served\n * within its documented bounds (for example a local queue file too large to scan\n * cheaply). Callers treat it as \"this section is unavailable\", never as \"empty\".\n */\nexport class QueueIntrospectionUnavailableError extends Error {\n readonly code = 'queue.introspection_unavailable'\n\n constructor(message = '[internal] Queue introspection is unavailable for this queue') {\n super(message)\n this.name = 'QueueIntrospectionUnavailableError'\n }\n}\n\n/**\n * Resolves a requested window size. `undefined` / non-finite falls back to the\n * default; zero and negative values resolve to `0`, which callers MUST treat as\n * an empty window *before* talking to the backend (BullMQ reads range `0..-1`\n * as \"everything\").\n */\nexport function resolveWindowSize(value: number | undefined, fallback: number, max: number): number {\n const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback\n return Math.max(0, Math.min(n, max))\n}\n\n/** Offsets are never negative, never fractional and never unbounded. */\nexport function resolveOffset(value: number | undefined): number {\n const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 0\n return Math.max(0, Math.min(n, MAX_INTROSPECTION_OFFSET))\n}\n\nfunction readStringField(source: unknown, key: string): string | undefined {\n if (!source || typeof source !== 'object') return undefined\n const value = (source as Record<string, unknown>)[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (!trimmed || trimmed.length > MAX_JOB_TYPE_LENGTH) return undefined\n return trimmed\n}\n\n/**\n * The payload-free job type of a stored job: the `jobType` stamped into the\n * envelope metadata at enqueue time, falling back to the producer's own\n * `payload.jobType` discriminator (the same field `removeQueuedJobsByScope`\n * already scopes on). The BullMQ job *name* is deliberately NOT used \u2014 enqueue\n * names every job with its random UUID.\n */\nexport function resolveJobType(envelope: Pick<QueuedJob<unknown>, 'payload' | 'metadata'> | undefined): string | undefined {\n if (!envelope) return undefined\n return readStringField(envelope.metadata, 'jobType') ?? readStringField(envelope.payload, 'jobType')\n}\n\n/**\n * Stable, payload-free failure codes exposed on the broadly-granted Tier 1\n * surface. Raw failure text can carry tenant data or credentials from the\n * handler's exception, so it is classified here and never forwarded.\n */\nexport const QUEUE_FAILURE_CODES = [\n 'queue.job_stalled',\n 'queue.job_start_limit',\n 'queue.timeout',\n 'queue.connection_error',\n 'queue.handler_error',\n] as const\nexport type QueueFailureCode = (typeof QUEUE_FAILURE_CODES)[number]\n\n/**\n * Maps a raw failure reason to a safe code. The raw text is only ever matched\n * against, never returned. Returns `undefined` when there is no reason at all.\n */\nexport function classifyFailureReason(reason: string | undefined | null): QueueFailureCode | undefined {\n if (typeof reason !== 'string' || reason.length === 0) return undefined\n if (reason === 'job stalled more than allowable limit') return 'queue.job_stalled'\n if (reason === 'job started more than allowable limit') return 'queue.job_start_limit'\n if (/\\b(timed? ?out|timeout|ETIMEDOUT|deadline exceeded)\\b/i.test(reason)) return 'queue.timeout'\n if (/\\b(ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up)\\b/i.test(reason)) {\n return 'queue.connection_error'\n }\n return 'queue.handler_error'\n}\n\n/** Max length of a raw failure reason kept for the privileged Tier 2 read. */\nexport const MAX_RAW_FAILED_REASON_LENGTH = 500\n\n/**\n * Reduces a completed job's envelope to the minimum a retained completed record\n * needs: ownership (tenant / organization) and the job type \u2014 no business data.\n * Used so bounded completed-job retention (needed for processing-time metrics)\n * never keeps handler payloads around.\n */\nexport function buildCompletedRetentionEnvelope<T>(envelope: QueuedJob<T>): QueuedJob<unknown> {\n const payload = envelope.payload as unknown\n const kept: Record<string, unknown> = {}\n if (payload && typeof payload === 'object') {\n const source = payload as Record<string, unknown>\n for (const key of ['tenantId', 'organizationId', 'jobType'] as const) {\n if (typeof source[key] === 'string') kept[key] = source[key]\n else if (key === 'organizationId' && source[key] === null) kept[key] = null\n }\n const scope = source.scope\n if (scope && typeof scope === 'object') {\n const nested: Record<string, unknown> = {}\n for (const key of ['tenantId', 'organizationId'] as const) {\n const value = (scope as Record<string, unknown>)[key]\n if (typeof value === 'string' || value === null) nested[key] = value\n }\n if (Object.keys(nested).length > 0) kept.scope = nested\n }\n }\n const jobType = resolveJobType(envelope)\n if (jobType && kept.jobType === undefined) kept.jobType = jobType\n return {\n id: envelope.id,\n payload: kept,\n createdAt: envelope.createdAt,\n ...(envelope.metadata ? { metadata: envelope.metadata } : {}),\n }\n}\n"],
|
|
5
|
+
"mappings": "AAQO,MAAM,2BAA2B;AAEjC,MAAM,6BAA6B;AAC1C,MAAM,sBAAsB;AAOrB,MAAM,2CAA2C,MAAM;AAAA,EAG5D,YAAY,UAAU,gEAAgE;AACpF,UAAM,OAAO;AAHf,SAAS,OAAO;AAId,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,kBAAkB,OAA2B,UAAkB,KAAqB;AAClG,QAAM,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,KAAK,MAAM,KAAK,IAAI;AACpF,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,GAAG,CAAC;AACrC;AAGO,SAAS,cAAc,OAAmC;AAC/D,QAAM,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,KAAK,MAAM,KAAK,IAAI;AACpF,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,wBAAwB,CAAC;AAC1D;AAEA,SAAS,gBAAgB,QAAiB,KAAiC;AACzE,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,QAAS,OAAmC,GAAG;AACrD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,WAAW,QAAQ,SAAS,oBAAqB,QAAO;AAC7D,SAAO;AACT;AASO,SAAS,eAAe,UAA4F;AACzH,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,gBAAgB,SAAS,UAAU,SAAS,KAAK,gBAAgB,SAAS,SAAS,SAAS;AACrG;AAOO,MAAM,sBAAsB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,sBAAsB,QAAiE;AACrG,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO;AAC9D,MAAI,WAAW,wCAAyC,QAAO;AAC/D,MAAI,WAAW,wCAAyC,QAAO;AAC/D,MAAI,yDAAyD,KAAK,MAAM,EAAG,QAAO;AAClF,MAAI,0EAA0E,KAAK,MAAM,GAAG;AAC1F,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAGO,MAAM,+BAA+B;AAQrC,SAAS,gCAAmC,UAA4C;AAC7F,QAAM,UAAU,SAAS;AACzB,QAAM,OAAgC,CAAC;AACvC,MAAI,WAAW,OAAO,YAAY,UAAU;AAC1C,UAAM,SAAS;AACf,eAAW,OAAO,CAAC,YAAY,kBAAkB,SAAS,GAAY;AACpE,UAAI,OAAO,OAAO,GAAG,MAAM,SAAU,MAAK,GAAG,IAAI,OAAO,GAAG;AAAA,eAClD,QAAQ,oBAAoB,OAAO,GAAG,MAAM,KAAM,MAAK,GAAG,IAAI;AAAA,IACzE;AACA,UAAM,QAAQ,OAAO;AACrB,QAAI,SAAS,OAAO,UAAU,UAAU;AACtC,YAAM,SAAkC,CAAC;AACzC,iBAAW,OAAO,CAAC,YAAY,gBAAgB,GAAY;AACzD,cAAM,QAAS,MAAkC,GAAG;AACpD,YAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO,GAAG,IAAI;AAAA,MACjE;AACA,UAAI,OAAO,KAAK,MAAM,EAAE,SAAS,EAAG,MAAK,QAAQ;AAAA,IACnD;AAAA,EACF;AACA,QAAM,UAAU,eAAe,QAAQ;AACvC,MAAI,WAAW,KAAK,YAAY,OAAW,MAAK,UAAU;AAC1D,SAAO;AAAA,IACL,IAAI,SAAS;AAAA,IACb,SAAS;AAAA,IACT,WAAW,SAAS;AAAA,IACpB,GAAI,SAAS,WAAW,EAAE,UAAU,SAAS,SAAS,IAAI,CAAC;AAAA,EAC7D;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
function validateEnqueueOptions(options) {
|
|
2
|
+
if (options?.jobId !== void 0 && (typeof options.jobId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(options.jobId) || /^\d+$/.test(options.jobId))) {
|
|
3
|
+
throw new Error("[internal] Queue jobId must contain letters, digits, underscores or hyphens and must not be an integer");
|
|
4
|
+
}
|
|
5
|
+
if (options?.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > 2147483647)) {
|
|
6
|
+
throw new Error("[internal] Queue timeoutMs must be a positive safe timer duration");
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
async function publishWithTimeout(operation, timeoutMs) {
|
|
10
|
+
if (timeoutMs === void 0) return operation();
|
|
11
|
+
let timer;
|
|
12
|
+
try {
|
|
13
|
+
return await Promise.race([
|
|
14
|
+
operation(),
|
|
15
|
+
new Promise((_resolve, reject) => {
|
|
16
|
+
timer = setTimeout(() => reject(new Error("[internal] Queue publication timed out; outcome is uncertain")), timeoutMs);
|
|
17
|
+
})
|
|
18
|
+
]);
|
|
19
|
+
} finally {
|
|
20
|
+
if (timer) clearTimeout(timer);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
publishWithTimeout,
|
|
25
|
+
validateEnqueueOptions
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=publication.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/publication.ts"],
|
|
4
|
+
"sourcesContent": ["import type { EnqueueOptions } from './types'\n\nexport function validateEnqueueOptions(options?: EnqueueOptions): void {\n if (options?.jobId !== undefined && (\n typeof options.jobId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(options.jobId) || /^\\d+$/.test(options.jobId)\n )) {\n throw new Error('[internal] Queue jobId must contain letters, digits, underscores or hyphens and must not be an integer')\n }\n if (options?.timeoutMs !== undefined && (\n !Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > 2_147_483_647\n )) {\n throw new Error('[internal] Queue timeoutMs must be a positive safe timer duration')\n }\n}\n\nexport async function publishWithTimeout<Result>(operation: () => Promise<Result>, timeoutMs?: number): Promise<Result> {\n if (timeoutMs === undefined) return operation()\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error('[internal] Queue publication timed out; outcome is uncertain')), timeoutMs)\n }),\n ])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEO,SAAS,uBAAuB,SAAgC;AACrE,MAAI,SAAS,UAAU,WACrB,OAAO,QAAQ,UAAU,YAAY,CAAC,mBAAmB,KAAK,QAAQ,KAAK,KAAK,QAAQ,KAAK,QAAQ,KAAK,IACzG;AACD,UAAM,IAAI,MAAM,wGAAwG;AAAA,EAC1H;AACA,MAAI,SAAS,cAAc,WACzB,CAAC,OAAO,cAAc,QAAQ,SAAS,KAAK,QAAQ,aAAa,KAAK,QAAQ,YAAY,aACzF;AACD,UAAM,IAAI,MAAM,mEAAmE;AAAA,EACrF;AACF;AAEA,eAAsB,mBAA2B,WAAkC,WAAqC;AACtH,MAAI,cAAc,OAAW,QAAO,UAAU;AAC9C,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK;AAAA,MACxB,UAAU;AAAA,MACV,IAAI,QAAe,CAAC,UAAU,WAAW;AACvC,gBAAQ,WAAW,MAAM,OAAO,IAAI,MAAM,8DAA8D,CAAC,GAAG,SAAS;AAAA,MACvH,CAAC;AAAA,IACH,CAAC;AAAA,EACH,UAAE;AACA,QAAI,MAAO,cAAa,KAAK;AAAA,EAC/B;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/tracing.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
|
|
2
|
+
const TRACE_META_KEY = "_trace";
|
|
3
|
+
function attachTraceMetadata(metadata) {
|
|
4
|
+
const carrier = getTelemetryRuntime()?.captureTraceContext() ?? {};
|
|
5
|
+
if (Object.keys(carrier).length === 0) return metadata;
|
|
6
|
+
return { ...metadata ?? {}, [TRACE_META_KEY]: carrier };
|
|
7
|
+
}
|
|
8
|
+
function runJobInTrace(queueName, metadata, fn) {
|
|
9
|
+
const runtime = getTelemetryRuntime();
|
|
10
|
+
if (!runtime) return fn();
|
|
11
|
+
return runtime.continueTrace(
|
|
12
|
+
readTraceCarrier(metadata),
|
|
13
|
+
`queue.${queueName}`,
|
|
14
|
+
fn,
|
|
15
|
+
{ kind: "consumer" }
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
function readTraceCarrier(metadata) {
|
|
19
|
+
const raw = metadata?.[TRACE_META_KEY];
|
|
20
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
21
|
+
return raw;
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
attachTraceMetadata,
|
|
25
|
+
runJobInTrace
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=tracing.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/tracing.ts"],
|
|
4
|
+
"sourcesContent": ["import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\n/**\n * Distributed-trace propagation across the enqueue \u2192 worker boundary.\n *\n * The W3C trace carrier rides on the job's `metadata._trace` (a first-class\n * metadata channel, not the user payload). Both halves are automatic \u2014 the\n * strategies call `attachTraceMetadata` at enqueue and `runJobInTrace` at\n * dispatch \u2014 so a worker joins the enqueuing request's trace with no per-worker\n * code. Everything here is a cheap no-op when telemetry is off.\n *\n * This also covers anything that rides the queue: persistent event subscribers\n * (the event bus enqueues) and outbound webhook delivery (queued) become part of\n * the originating request's trace for free.\n */\nconst TRACE_META_KEY = '_trace'\n\n/**\n * Attach the active trace context to a job's metadata. Returns `metadata`\n * unchanged when telemetry is off (no active span \u2192 empty carrier), so jobs stay\n * clean unless tracing is active.\n */\nexport function attachTraceMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n const carrier = getTelemetryRuntime()?.captureTraceContext() ?? {}\n if (Object.keys(carrier).length === 0) return metadata\n return { ...(metadata ?? {}), [TRACE_META_KEY]: carrier }\n}\n\n/**\n * Run a job handler inside a span (`queue.<queueName>`) that continues the\n * producer's trace from the carrier on `metadata`. With no carrier (or telemetry\n * off) it runs `fn` under a fresh root span \u2014 and a no-op when off. The span\n * ends when `fn` settles (sync or async).\n */\nexport function runJobInTrace<T>(\n queueName: string,\n metadata: Record<string, unknown> | undefined,\n fn: () => T,\n): T {\n const runtime = getTelemetryRuntime()\n if (!runtime) return fn()\n return runtime.continueTrace(\n readTraceCarrier(metadata),\n `queue.${queueName}`,\n fn,\n { kind: 'consumer' },\n )\n}\n\nfunction readTraceCarrier(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n const raw = metadata?.[TRACE_META_KEY]\n if (!raw || typeof raw !== 'object') return undefined\n return raw as Record<string, string>\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,2BAA2B;AAepC,MAAM,iBAAiB;AAOhB,SAAS,oBACd,UACqC;AACrC,QAAM,UAAU,oBAAoB,GAAG,oBAAoB,KAAK,CAAC;AACjE,MAAI,OAAO,KAAK,OAAO,EAAE,WAAW,EAAG,QAAO;AAC9C,SAAO,EAAE,GAAI,YAAY,CAAC,GAAI,CAAC,cAAc,GAAG,QAAQ;AAC1D;AAQO,SAAS,cACd,WACA,UACA,IACG;AACH,QAAM,UAAU,oBAAoB;AACpC,MAAI,CAAC,QAAS,QAAO,GAAG;AACxB,SAAO,QAAQ;AAAA,IACb,iBAAiB,QAAQ;AAAA,IACzB,SAAS,SAAS;AAAA,IAClB;AAAA,IACA,EAAE,MAAM,WAAW;AAAA,EACrB;AACF;AAEA,SAAS,iBACP,UACoC;AACpC,QAAM,MAAM,WAAW,cAAc;AACrC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=types.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/queue-provider-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.11.1-develop.8983.1.8f477e3f83",
|
|
4
|
+
"description": "Provider-neutral queue types, tracing and publication helpers 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
|
+
"./types": {
|
|
14
|
+
"types": "./src/types.ts",
|
|
15
|
+
"default": "./dist/types.js"
|
|
16
|
+
},
|
|
17
|
+
"./coalescing": {
|
|
18
|
+
"types": "./src/coalescing.ts",
|
|
19
|
+
"default": "./dist/coalescing.js"
|
|
20
|
+
},
|
|
21
|
+
"./publication": {
|
|
22
|
+
"types": "./src/publication.ts",
|
|
23
|
+
"default": "./dist/publication.js"
|
|
24
|
+
},
|
|
25
|
+
"./tracing": {
|
|
26
|
+
"types": "./src/tracing.ts",
|
|
27
|
+
"default": "./dist/tracing.js"
|
|
28
|
+
},
|
|
29
|
+
"./introspection": {
|
|
30
|
+
"types": "./src/introspection.ts",
|
|
31
|
+
"default": "./dist/introspection.js"
|
|
32
|
+
},
|
|
33
|
+
"./default-provider": {
|
|
34
|
+
"types": "./src/default-provider.ts",
|
|
35
|
+
"default": "./dist/default-provider.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "node build.mjs",
|
|
40
|
+
"watch": "node watch.mjs",
|
|
41
|
+
"typecheck": "tsc --noEmit"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "^26.4.0",
|
|
45
|
+
"typescript": "7.0.2"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "https://github.com/open-mercato/open-mercato",
|
|
53
|
+
"directory": "packages/queue-provider-kit"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@open-mercato/shared": "0.11.1-develop.8983.1.8f477e3f83"
|
|
57
|
+
},
|
|
58
|
+
"stableVersion": "0.11.0"
|
|
6
59
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CoalesceKeyResolver, EnqueueOptions } from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolves the coalescing key for one enqueue.
|
|
5
|
+
*
|
|
6
|
+
* A key passed at the call site wins over the queue's own `coalesceBy`, so a caller can coalesce
|
|
7
|
+
* something the queue does not, or key one enqueue differently. Falsy results mean "do not
|
|
8
|
+
* coalesce": a resolver returning `null` for payloads it has no opinion about is the documented way
|
|
9
|
+
* to leave them alone, and an empty string is never a usable key.
|
|
10
|
+
*/
|
|
11
|
+
export function resolveCoalesceKey<T>(
|
|
12
|
+
payload: T,
|
|
13
|
+
options?: EnqueueOptions,
|
|
14
|
+
coalesceBy?: CoalesceKeyResolver<T>,
|
|
15
|
+
): string | undefined {
|
|
16
|
+
if (options?.coalesce) return options.coalesce.key || undefined
|
|
17
|
+
return coalesceBy?.(payload) || undefined
|
|
18
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Queue, QueueOptions, QueueStrategyType, RedisConnectionOptions } from './types'
|
|
2
|
+
|
|
3
|
+
export type QueuePendingProbeOptions = {
|
|
4
|
+
connection?: RedisConnectionOptions
|
|
5
|
+
baseDir?: string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type QueuePendingProbeResult = {
|
|
9
|
+
queueName: string
|
|
10
|
+
strategy: QueueStrategyType
|
|
11
|
+
/** Number of jobs ready to process now. */
|
|
12
|
+
ready: number
|
|
13
|
+
/** Number of jobs scheduled for the future. */
|
|
14
|
+
delayedFuture: number
|
|
15
|
+
/** Number of active jobs visible to the probe. */
|
|
16
|
+
active: number
|
|
17
|
+
/** The probe could not query storage. */
|
|
18
|
+
error: boolean
|
|
19
|
+
errorMessage?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type DefaultQueueDriver<Strategy extends QueueStrategyType> = {
|
|
23
|
+
contractVersion: 1
|
|
24
|
+
edition: 'oss'
|
|
25
|
+
strategy: Strategy
|
|
26
|
+
packageVersion: string
|
|
27
|
+
createQueue<T = unknown>(name: string, options?: QueueOptions<Strategy, T>): Queue<T>
|
|
28
|
+
probe(name: string, options?: QueuePendingProbeOptions): Promise<QueuePendingProbeResult>
|
|
29
|
+
resourceIdentity<T = unknown>(name: string, options?: QueueOptions<Strategy, T>): Promise<string>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function emptyProbe(queueName: string, strategy: QueueStrategyType): QueuePendingProbeResult {
|
|
33
|
+
return { queueName, strategy, ready: 0, delayedFuture: 0, active: 0, error: false }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function failedProbe(queueName: string, strategy: QueueStrategyType, error: unknown): QueuePendingProbeResult {
|
|
37
|
+
return {
|
|
38
|
+
...emptyProbe(queueName, strategy),
|
|
39
|
+
error: true,
|
|
40
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared, strategy-independent helpers for the payload-free queue introspection
|
|
3
|
+
* contract (Queue Status Dashboard, #3105). Nothing here touches I/O.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { QueuedJob } from './types'
|
|
7
|
+
|
|
8
|
+
/** Hard cap on how far a caller may page into a window. */
|
|
9
|
+
export const MAX_INTROSPECTION_OFFSET = 1000
|
|
10
|
+
/** How many candidates a strategy inspects when a job-type filter forces post-filtering. */
|
|
11
|
+
export const MAX_TYPE_FILTER_CANDIDATES = 200
|
|
12
|
+
const MAX_JOB_TYPE_LENGTH = 128
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Thrown by a strategy when an optional introspection read cannot be served
|
|
16
|
+
* within its documented bounds (for example a local queue file too large to scan
|
|
17
|
+
* cheaply). Callers treat it as "this section is unavailable", never as "empty".
|
|
18
|
+
*/
|
|
19
|
+
export class QueueIntrospectionUnavailableError extends Error {
|
|
20
|
+
readonly code = 'queue.introspection_unavailable'
|
|
21
|
+
|
|
22
|
+
constructor(message = '[internal] Queue introspection is unavailable for this queue') {
|
|
23
|
+
super(message)
|
|
24
|
+
this.name = 'QueueIntrospectionUnavailableError'
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolves a requested window size. `undefined` / non-finite falls back to the
|
|
30
|
+
* default; zero and negative values resolve to `0`, which callers MUST treat as
|
|
31
|
+
* an empty window *before* talking to the backend (BullMQ reads range `0..-1`
|
|
32
|
+
* as "everything").
|
|
33
|
+
*/
|
|
34
|
+
export function resolveWindowSize(value: number | undefined, fallback: number, max: number): number {
|
|
35
|
+
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
|
36
|
+
return Math.max(0, Math.min(n, max))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Offsets are never negative, never fractional and never unbounded. */
|
|
40
|
+
export function resolveOffset(value: number | undefined): number {
|
|
41
|
+
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 0
|
|
42
|
+
return Math.max(0, Math.min(n, MAX_INTROSPECTION_OFFSET))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readStringField(source: unknown, key: string): string | undefined {
|
|
46
|
+
if (!source || typeof source !== 'object') return undefined
|
|
47
|
+
const value = (source as Record<string, unknown>)[key]
|
|
48
|
+
if (typeof value !== 'string') return undefined
|
|
49
|
+
const trimmed = value.trim()
|
|
50
|
+
if (!trimmed || trimmed.length > MAX_JOB_TYPE_LENGTH) return undefined
|
|
51
|
+
return trimmed
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The payload-free job type of a stored job: the `jobType` stamped into the
|
|
56
|
+
* envelope metadata at enqueue time, falling back to the producer's own
|
|
57
|
+
* `payload.jobType` discriminator (the same field `removeQueuedJobsByScope`
|
|
58
|
+
* already scopes on). The BullMQ job *name* is deliberately NOT used — enqueue
|
|
59
|
+
* names every job with its random UUID.
|
|
60
|
+
*/
|
|
61
|
+
export function resolveJobType(envelope: Pick<QueuedJob<unknown>, 'payload' | 'metadata'> | undefined): string | undefined {
|
|
62
|
+
if (!envelope) return undefined
|
|
63
|
+
return readStringField(envelope.metadata, 'jobType') ?? readStringField(envelope.payload, 'jobType')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Stable, payload-free failure codes exposed on the broadly-granted Tier 1
|
|
68
|
+
* surface. Raw failure text can carry tenant data or credentials from the
|
|
69
|
+
* handler's exception, so it is classified here and never forwarded.
|
|
70
|
+
*/
|
|
71
|
+
export const QUEUE_FAILURE_CODES = [
|
|
72
|
+
'queue.job_stalled',
|
|
73
|
+
'queue.job_start_limit',
|
|
74
|
+
'queue.timeout',
|
|
75
|
+
'queue.connection_error',
|
|
76
|
+
'queue.handler_error',
|
|
77
|
+
] as const
|
|
78
|
+
export type QueueFailureCode = (typeof QUEUE_FAILURE_CODES)[number]
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Maps a raw failure reason to a safe code. The raw text is only ever matched
|
|
82
|
+
* against, never returned. Returns `undefined` when there is no reason at all.
|
|
83
|
+
*/
|
|
84
|
+
export function classifyFailureReason(reason: string | undefined | null): QueueFailureCode | undefined {
|
|
85
|
+
if (typeof reason !== 'string' || reason.length === 0) return undefined
|
|
86
|
+
if (reason === 'job stalled more than allowable limit') return 'queue.job_stalled'
|
|
87
|
+
if (reason === 'job started more than allowable limit') return 'queue.job_start_limit'
|
|
88
|
+
if (/\b(timed? ?out|timeout|ETIMEDOUT|deadline exceeded)\b/i.test(reason)) return 'queue.timeout'
|
|
89
|
+
if (/\b(ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up)\b/i.test(reason)) {
|
|
90
|
+
return 'queue.connection_error'
|
|
91
|
+
}
|
|
92
|
+
return 'queue.handler_error'
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Max length of a raw failure reason kept for the privileged Tier 2 read. */
|
|
96
|
+
export const MAX_RAW_FAILED_REASON_LENGTH = 500
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Reduces a completed job's envelope to the minimum a retained completed record
|
|
100
|
+
* needs: ownership (tenant / organization) and the job type — no business data.
|
|
101
|
+
* Used so bounded completed-job retention (needed for processing-time metrics)
|
|
102
|
+
* never keeps handler payloads around.
|
|
103
|
+
*/
|
|
104
|
+
export function buildCompletedRetentionEnvelope<T>(envelope: QueuedJob<T>): QueuedJob<unknown> {
|
|
105
|
+
const payload = envelope.payload as unknown
|
|
106
|
+
const kept: Record<string, unknown> = {}
|
|
107
|
+
if (payload && typeof payload === 'object') {
|
|
108
|
+
const source = payload as Record<string, unknown>
|
|
109
|
+
for (const key of ['tenantId', 'organizationId', 'jobType'] as const) {
|
|
110
|
+
if (typeof source[key] === 'string') kept[key] = source[key]
|
|
111
|
+
else if (key === 'organizationId' && source[key] === null) kept[key] = null
|
|
112
|
+
}
|
|
113
|
+
const scope = source.scope
|
|
114
|
+
if (scope && typeof scope === 'object') {
|
|
115
|
+
const nested: Record<string, unknown> = {}
|
|
116
|
+
for (const key of ['tenantId', 'organizationId'] as const) {
|
|
117
|
+
const value = (scope as Record<string, unknown>)[key]
|
|
118
|
+
if (typeof value === 'string' || value === null) nested[key] = value
|
|
119
|
+
}
|
|
120
|
+
if (Object.keys(nested).length > 0) kept.scope = nested
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const jobType = resolveJobType(envelope)
|
|
124
|
+
if (jobType && kept.jobType === undefined) kept.jobType = jobType
|
|
125
|
+
return {
|
|
126
|
+
id: envelope.id,
|
|
127
|
+
payload: kept,
|
|
128
|
+
createdAt: envelope.createdAt,
|
|
129
|
+
...(envelope.metadata ? { metadata: envelope.metadata } : {}),
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { EnqueueOptions } from './types'
|
|
2
|
+
|
|
3
|
+
export function validateEnqueueOptions(options?: EnqueueOptions): void {
|
|
4
|
+
if (options?.jobId !== undefined && (
|
|
5
|
+
typeof options.jobId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(options.jobId) || /^\d+$/.test(options.jobId)
|
|
6
|
+
)) {
|
|
7
|
+
throw new Error('[internal] Queue jobId must contain letters, digits, underscores or hyphens and must not be an integer')
|
|
8
|
+
}
|
|
9
|
+
if (options?.timeoutMs !== undefined && (
|
|
10
|
+
!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > 2_147_483_647
|
|
11
|
+
)) {
|
|
12
|
+
throw new Error('[internal] Queue timeoutMs must be a positive safe timer duration')
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function publishWithTimeout<Result>(operation: () => Promise<Result>, timeoutMs?: number): Promise<Result> {
|
|
17
|
+
if (timeoutMs === undefined) return operation()
|
|
18
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
19
|
+
try {
|
|
20
|
+
return await Promise.race([
|
|
21
|
+
operation(),
|
|
22
|
+
new Promise<never>((_resolve, reject) => {
|
|
23
|
+
timer = setTimeout(() => reject(new Error('[internal] Queue publication timed out; outcome is uncertain')), timeoutMs)
|
|
24
|
+
}),
|
|
25
|
+
])
|
|
26
|
+
} finally {
|
|
27
|
+
if (timer) clearTimeout(timer)
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/tracing.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Distributed-trace propagation across the enqueue → worker boundary.
|
|
5
|
+
*
|
|
6
|
+
* The W3C trace carrier rides on the job's `metadata._trace` (a first-class
|
|
7
|
+
* metadata channel, not the user payload). Both halves are automatic — the
|
|
8
|
+
* strategies call `attachTraceMetadata` at enqueue and `runJobInTrace` at
|
|
9
|
+
* dispatch — so a worker joins the enqueuing request's trace with no per-worker
|
|
10
|
+
* code. Everything here is a cheap no-op when telemetry is off.
|
|
11
|
+
*
|
|
12
|
+
* This also covers anything that rides the queue: persistent event subscribers
|
|
13
|
+
* (the event bus enqueues) and outbound webhook delivery (queued) become part of
|
|
14
|
+
* the originating request's trace for free.
|
|
15
|
+
*/
|
|
16
|
+
const TRACE_META_KEY = '_trace'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Attach the active trace context to a job's metadata. Returns `metadata`
|
|
20
|
+
* unchanged when telemetry is off (no active span → empty carrier), so jobs stay
|
|
21
|
+
* clean unless tracing is active.
|
|
22
|
+
*/
|
|
23
|
+
export function attachTraceMetadata(
|
|
24
|
+
metadata: Record<string, unknown> | undefined,
|
|
25
|
+
): Record<string, unknown> | undefined {
|
|
26
|
+
const carrier = getTelemetryRuntime()?.captureTraceContext() ?? {}
|
|
27
|
+
if (Object.keys(carrier).length === 0) return metadata
|
|
28
|
+
return { ...(metadata ?? {}), [TRACE_META_KEY]: carrier }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Run a job handler inside a span (`queue.<queueName>`) that continues the
|
|
33
|
+
* producer's trace from the carrier on `metadata`. With no carrier (or telemetry
|
|
34
|
+
* off) it runs `fn` under a fresh root span — and a no-op when off. The span
|
|
35
|
+
* ends when `fn` settles (sync or async).
|
|
36
|
+
*/
|
|
37
|
+
export function runJobInTrace<T>(
|
|
38
|
+
queueName: string,
|
|
39
|
+
metadata: Record<string, unknown> | undefined,
|
|
40
|
+
fn: () => T,
|
|
41
|
+
): T {
|
|
42
|
+
const runtime = getTelemetryRuntime()
|
|
43
|
+
if (!runtime) return fn()
|
|
44
|
+
return runtime.continueTrace(
|
|
45
|
+
readTraceCarrier(metadata),
|
|
46
|
+
`queue.${queueName}`,
|
|
47
|
+
fn,
|
|
48
|
+
{ kind: 'consumer' },
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function readTraceCarrier(
|
|
53
|
+
metadata: Record<string, unknown> | undefined,
|
|
54
|
+
): Record<string, string> | undefined {
|
|
55
|
+
const raw = metadata?.[TRACE_META_KEY]
|
|
56
|
+
if (!raw || typeof raw !== 'object') return undefined
|
|
57
|
+
return raw as Record<string, string>
|
|
58
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Queue Package Type Definitions
|
|
3
|
+
*
|
|
4
|
+
* Provides type-safe abstractions for multi-strategy job queues.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// ============================================================================
|
|
8
|
+
// Core Job Types
|
|
9
|
+
// ============================================================================
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Represents a job stored in the queue.
|
|
13
|
+
* @template T - The payload type for this job
|
|
14
|
+
*/
|
|
15
|
+
export type QueuedJob<T = unknown> = {
|
|
16
|
+
/** Unique identifier for the job */
|
|
17
|
+
id: string
|
|
18
|
+
/** The job payload data */
|
|
19
|
+
payload: T
|
|
20
|
+
/** ISO timestamp when the job was created */
|
|
21
|
+
createdAt: string
|
|
22
|
+
/** Optional metadata for the job */
|
|
23
|
+
metadata?: Record<string, unknown>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Context provided to job handlers during processing.
|
|
28
|
+
*/
|
|
29
|
+
export type JobContext = {
|
|
30
|
+
/** Unique identifier of the current job */
|
|
31
|
+
jobId: string
|
|
32
|
+
/** Current attempt number (1-based) */
|
|
33
|
+
attemptNumber: number
|
|
34
|
+
/** Name of the queue being processed */
|
|
35
|
+
queueName: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Handler function that processes jobs from the queue.
|
|
40
|
+
* @template T - The payload type this handler expects
|
|
41
|
+
*/
|
|
42
|
+
export type JobHandler<T = unknown> = (
|
|
43
|
+
job: QueuedJob<T>,
|
|
44
|
+
ctx: JobContext
|
|
45
|
+
) => Promise<void> | void
|
|
46
|
+
|
|
47
|
+
// ============================================================================
|
|
48
|
+
// Strategy Types
|
|
49
|
+
// ============================================================================
|
|
50
|
+
|
|
51
|
+
/** Available queue strategy types */
|
|
52
|
+
export type QueueStrategyType = 'local' | 'async'
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Options for local (file-based) queue strategy.
|
|
56
|
+
*/
|
|
57
|
+
export type LocalQueueOptions<T = unknown> = {
|
|
58
|
+
/**
|
|
59
|
+
* Derives a coalescing key from every payload this queue enqueues, so no call site has to
|
|
60
|
+
* remember to pass one. An explicit `EnqueueOptions.coalesce` overrides it.
|
|
61
|
+
*/
|
|
62
|
+
coalesceBy?: CoalesceKeyResolver<T>
|
|
63
|
+
/** Base directory for queue files. Defaults to QUEUE_BASE_DIR or '.mercato/queue' */
|
|
64
|
+
baseDir?: string
|
|
65
|
+
/** Number of concurrent job processors. Defaults to 1 */
|
|
66
|
+
concurrency?: number
|
|
67
|
+
/** Polling interval in milliseconds while work is queued. Idle safety polling uses at least 5000 ms. Defaults to 1000. */
|
|
68
|
+
pollInterval?: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Redis connection options for async strategy.
|
|
73
|
+
*/
|
|
74
|
+
export type RedisConnectionOptions = {
|
|
75
|
+
/** Redis connection URL (e.g., redis://localhost:6379) */
|
|
76
|
+
url?: string
|
|
77
|
+
/** Redis host */
|
|
78
|
+
host?: string
|
|
79
|
+
/** Redis port */
|
|
80
|
+
port?: number
|
|
81
|
+
/** Redis username */
|
|
82
|
+
username?: string
|
|
83
|
+
/** Redis password */
|
|
84
|
+
password?: string
|
|
85
|
+
/** Redis database number */
|
|
86
|
+
db?: number
|
|
87
|
+
/** TLS configuration for rediss / encrypted Redis */
|
|
88
|
+
tls?: Record<string, unknown>
|
|
89
|
+
/** IP family used by Redis DNS resolution */
|
|
90
|
+
family?: number
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Options for async (BullMQ) queue strategy.
|
|
95
|
+
*/
|
|
96
|
+
export type AsyncQueueOptions<T = unknown> = {
|
|
97
|
+
/**
|
|
98
|
+
* Derives a coalescing key from every payload this queue enqueues, so no call site has to
|
|
99
|
+
* remember to pass one. An explicit `EnqueueOptions.coalesce` overrides it.
|
|
100
|
+
*/
|
|
101
|
+
coalesceBy?: CoalesceKeyResolver<T>
|
|
102
|
+
/** Redis connection configuration */
|
|
103
|
+
connection?: RedisConnectionOptions
|
|
104
|
+
/** Number of concurrent job processors. Defaults to 1 */
|
|
105
|
+
concurrency?: number
|
|
106
|
+
/** Number of attempts for newly enqueued jobs. Defaults to 3. */
|
|
107
|
+
attempts?: number
|
|
108
|
+
/** How long a job lock is held before the job counts as stalled, in ms. Defaults to 30000. */
|
|
109
|
+
lockDuration?: number
|
|
110
|
+
/** Number of stalled-job recoveries BullMQ permits before failing a job. Defaults to 1. */
|
|
111
|
+
maxStalledCount?: number
|
|
112
|
+
/**
|
|
113
|
+
* Called when the queue permanently gives up on a job WITHOUT its handler having run.
|
|
114
|
+
*
|
|
115
|
+
* Why this cannot be left to the handler: a queue may destroy a job before ever calling the
|
|
116
|
+
* processor — the usual cause is a job redelivered once too often, past `maxStalledCount`. The
|
|
117
|
+
* handler then never runs, never throws and never learns, and any state it created on enqueue (a
|
|
118
|
+
* run row, a progress record) is orphaned in whatever "in progress" state it was left in, with
|
|
119
|
+
* nothing to correct it.
|
|
120
|
+
*
|
|
121
|
+
* Contract:
|
|
122
|
+
* - Fires **only** for a job the queue abandoned before its handler ran. It is deliberately not a
|
|
123
|
+
* general "job failed" hook: a handler that ran and threw owns its own outcome and has already
|
|
124
|
+
* had the chance to record it. Reporting both would double-report and would hide the difference
|
|
125
|
+
* between "the work failed" and "the work never started".
|
|
126
|
+
* - **At-least-once, where the backend allows it.** The strategy reports as soon as it observes
|
|
127
|
+
* the abandonment, and also sweeps the backend's dead-job records — on worker start, then
|
|
128
|
+
* periodically — for reports that were never acknowledged. A report is acknowledged only after
|
|
129
|
+
* this callback returns, so a callback that threw or a process that died mid-report is retried
|
|
130
|
+
* by a later sweep. The callback MUST therefore be idempotent, and MUST tolerate a payload it
|
|
131
|
+
* does not recognise. Residual loss is still possible when the backend evicts its dead-job
|
|
132
|
+
* records before any sweep sees them; state that absolutely must never be stranded should also
|
|
133
|
+
* have a staleness check of its own at the domain level.
|
|
134
|
+
* - Not every strategy can implement it — the local strategy runs handlers in-process, so no queue
|
|
135
|
+
* outlives a handler to abandon its job.
|
|
136
|
+
*
|
|
137
|
+
* Backend specifics (which failures count as abandonment, and how they are detected) belong to the
|
|
138
|
+
* strategy; see `strategies/async.ts`.
|
|
139
|
+
*/
|
|
140
|
+
onJobAbandoned?: (payload: unknown, info: AbandonedJobInfo) => void | Promise<void>
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** What the queue can say about a job it gave up on. */
|
|
144
|
+
export type AbandonedJobInfo = {
|
|
145
|
+
/** The queue driver's own job id, or null when it did not supply one. */
|
|
146
|
+
jobId: string | null
|
|
147
|
+
/** The failure the queue recorded, e.g. 'job stalled more than allowable limit'. */
|
|
148
|
+
reason: string
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Conditional options type based on strategy.
|
|
153
|
+
* Local strategy gets file options, async gets Redis options.
|
|
154
|
+
*/
|
|
155
|
+
export type QueueOptions<S extends QueueStrategyType, T = unknown> = S extends 'async'
|
|
156
|
+
? AsyncQueueOptions<T>
|
|
157
|
+
: LocalQueueOptions<T>
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Collapses repeated enqueues of the same logical work into a single job.
|
|
161
|
+
*
|
|
162
|
+
* The guarantee, which holds however many enqueues arrive: **the last one always gets a run that
|
|
163
|
+
* sees it.** Enqueues that arrive while a job for the key is merely waiting add nothing — that job
|
|
164
|
+
* has not read anything yet, so it will observe their writes. Enqueues that arrive while a job for
|
|
165
|
+
* the key is *running* are parked, and exactly one follow-up run starts when it finishes, carrying
|
|
166
|
+
* the latest payload. At most one active plus one waiting job exists per key at any time.
|
|
167
|
+
*
|
|
168
|
+
* Ten triggers in a burst therefore produce at most two runs rather than ten, and none of them is
|
|
169
|
+
* lost. Keying it on the entity being recomputed is what makes that useful:
|
|
170
|
+
*
|
|
171
|
+
* ```typescript
|
|
172
|
+
* await queue.enqueue({ orderId }, { coalesce: { key: `order-totals:${orderId}` } })
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* The word is deliberate. This is not "deduplication" in the drop-the-duplicate sense that SQS FIFO
|
|
176
|
+
* and Cloud Tasks mean, and that BullMQ's bare `deduplication: { id }` does: there, an enqueue
|
|
177
|
+
* landing mid-run is discarded, the running job finishes on input that predates it, and the
|
|
178
|
+
* recomputed state stays stale until some unrelated trigger happens along. That mode is not exposed
|
|
179
|
+
* here — the loss is silent, and the run it saves is a run this package already requires workers to
|
|
180
|
+
* tolerate (see the idempotency rule in the package's AGENTS.md). Should a caller ever genuinely
|
|
181
|
+
* want it, adding an opt-out field is additive.
|
|
182
|
+
*/
|
|
183
|
+
export type CoalesceOptions = {
|
|
184
|
+
/** Coalescing key, scoped to one queue. Key it on the entity the job acts on. */
|
|
185
|
+
key: string
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Derives a coalescing key from a job's payload, set once when the queue is built.
|
|
190
|
+
*
|
|
191
|
+
* Return `null` or `undefined` to leave a payload uncoalesced.
|
|
192
|
+
*/
|
|
193
|
+
export type CoalesceKeyResolver<T = unknown> = (payload: T) => string | null | undefined
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Optional job scheduling options.
|
|
197
|
+
*/
|
|
198
|
+
export type EnqueueOptions = {
|
|
199
|
+
/**
|
|
200
|
+
* Delay job execution by this many milliseconds.
|
|
201
|
+
*/
|
|
202
|
+
delayMs?: number
|
|
203
|
+
/** Deduplicates while this ID remains queued, active, or retained by the strategy. Reuse after an uncertain outcome. */
|
|
204
|
+
jobId?: string
|
|
205
|
+
/** Positive publication deadline in milliseconds. Expiry does not cancel a late backend write. */
|
|
206
|
+
timeoutMs?: number
|
|
207
|
+
/**
|
|
208
|
+
* Payload-free job type recorded on the job envelope (`metadata.jobType`) so the
|
|
209
|
+
* queue status dashboard can filter by it without reading business data. Defaults
|
|
210
|
+
* to the producer's own `payload.jobType` string when the payload carries one.
|
|
211
|
+
*/
|
|
212
|
+
jobType?: string
|
|
213
|
+
/**
|
|
214
|
+
* Collapse this enqueue into outstanding work sharing the same key.
|
|
215
|
+
*
|
|
216
|
+
* Overrides the queue's own `coalesceBy`, if it has one. Best-effort per strategy: an
|
|
217
|
+
* implementation that does not honour coalescing MUST still enqueue the job. Degrading toward a
|
|
218
|
+
* duplicate run is acceptable; dropping one is not.
|
|
219
|
+
*
|
|
220
|
+
* **Combined with `delayMs`**, the two options interact, and the strategies differ:
|
|
221
|
+
*
|
|
222
|
+
* - **Local** takes the *earlier* of the two moments. A coalesced enqueue can pull a delayed twin
|
|
223
|
+
* forward, but collapsing never pushes a run later than the schedule an enqueue was given. The
|
|
224
|
+
* asymmetry is the one the whole feature rests on: an early run costs milliseconds, a deferred
|
|
225
|
+
* one silently leaves state wrong for the length of the delay.
|
|
226
|
+
* - **Async** inherits BullMQ, which discards the colliding add outright, so the surviving job
|
|
227
|
+
* keeps its own schedule — an immediate enqueue collapsed into a delayed twin *is* deferred
|
|
228
|
+
* until that twin's delay elapses. Nothing is lost, and the parked-follow-up path is unaffected;
|
|
229
|
+
* only the moment moves.
|
|
230
|
+
*
|
|
231
|
+
* So do not use `delayMs` to schedule work on a coalesced key — a burst's effective delay is not
|
|
232
|
+
* well-defined across strategies. Give delayed work its own key, or no key at all.
|
|
233
|
+
*/
|
|
234
|
+
coalesce?: CoalesceOptions
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ============================================================================
|
|
238
|
+
// Process Types
|
|
239
|
+
// ============================================================================
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Options for the process operation.
|
|
243
|
+
*/
|
|
244
|
+
export type ProcessOptions = {
|
|
245
|
+
/** Maximum number of jobs to process (local strategy only) */
|
|
246
|
+
limit?: number
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Result returned after processing jobs.
|
|
251
|
+
*/
|
|
252
|
+
export type ProcessResult = {
|
|
253
|
+
/** Number of jobs successfully processed */
|
|
254
|
+
processed: number
|
|
255
|
+
/** Number of jobs that failed */
|
|
256
|
+
failed: number
|
|
257
|
+
/** ID of the last processed job */
|
|
258
|
+
lastJobId?: string
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export type QueueJobScope = {
|
|
262
|
+
tenantId: string
|
|
263
|
+
organizationId?: string | null
|
|
264
|
+
jobTypes?: readonly string[]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ============================================================================
|
|
268
|
+
// Introspection Types (Queue Status Dashboard — payload-free unless noted)
|
|
269
|
+
// ============================================================================
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Sanitized record of a recently failed job. Intentionally OMITS `job.data` /
|
|
273
|
+
* payload — this is the Tier 1 (broadly-accessible) status surface's contract.
|
|
274
|
+
*/
|
|
275
|
+
export type FailedJobSummary = {
|
|
276
|
+
id: string
|
|
277
|
+
queue: string
|
|
278
|
+
/** Payload-free job type (`metadata.jobType` / `payload.jobType`), when the producer supplied one. */
|
|
279
|
+
type?: string
|
|
280
|
+
/** Best-effort worker id, when derivable from the job's own metadata. */
|
|
281
|
+
workerId?: string
|
|
282
|
+
/**
|
|
283
|
+
* Stable, safe failure code (see `classifyFailureReason`). The raw failure text is
|
|
284
|
+
* NEVER part of this broadly-accessible contract — it can echo tenant data or
|
|
285
|
+
* credentials from the handler's exception and is only readable via
|
|
286
|
+
* `getRecentJobs` (Tier 2: tenant-filtered, redacted, audited).
|
|
287
|
+
*/
|
|
288
|
+
errorCode?: string
|
|
289
|
+
attemptsMade?: number
|
|
290
|
+
/** Epoch ms. */
|
|
291
|
+
failedAt?: number
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Bounded-sample processing-time metrics for one queue. Durations/timestamps only, no `data`. */
|
|
295
|
+
export type QueueProcessingStats = {
|
|
296
|
+
/** How many completed jobs were actually sampled to compute this. */
|
|
297
|
+
sampleSize: number
|
|
298
|
+
/** Duration of the most recently completed job (finishedOn − processedOn), ms. */
|
|
299
|
+
lastProcessingMs?: number
|
|
300
|
+
/** Mean processing duration over the sample, ms. */
|
|
301
|
+
avgProcessingMs?: number
|
|
302
|
+
/** Tail latency over the sample, ms. */
|
|
303
|
+
p95ProcessingMs?: number
|
|
304
|
+
/** Mean queue latency over the sample (processedOn − timestamp), ms. */
|
|
305
|
+
avgWaitMs?: number
|
|
306
|
+
/** Epoch ms of the newest completed job in the sample. */
|
|
307
|
+
lastCompletedAt?: number
|
|
308
|
+
fidelity?: 'exact' | 'partial'
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Sanitized record of an in-flight (active) or queued (waiting/delayed) job, with
|
|
313
|
+
* server-computed timing. Intentionally OMITS `job.data` / payload.
|
|
314
|
+
*/
|
|
315
|
+
export type InFlightJobSummary = {
|
|
316
|
+
id: string
|
|
317
|
+
queue: string
|
|
318
|
+
/** Payload-free job type (`metadata.jobType` / `payload.jobType`), when the producer supplied one. */
|
|
319
|
+
type?: string
|
|
320
|
+
workerId?: string
|
|
321
|
+
state: 'active' | 'waiting' | 'delayed'
|
|
322
|
+
/** Epoch ms the job was enqueued (job.timestamp). */
|
|
323
|
+
enqueuedAt?: number
|
|
324
|
+
/** Epoch ms the job started processing (job.processedOn) — active only. */
|
|
325
|
+
startedAt?: number
|
|
326
|
+
/** now − startedAt — how long an ACTIVE job has been processing, ms. */
|
|
327
|
+
runningMs?: number
|
|
328
|
+
/** now − enqueuedAt — how long a WAITING/DELAYED job has been queued, ms. */
|
|
329
|
+
ageMs?: number
|
|
330
|
+
attemptsMade?: number
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* A job INCLUDING its raw payload — Tier 2 (privileged) only. Redaction and
|
|
335
|
+
* tenant filtering are the CALLER's responsibility (`configs/lib/queue-job-inspector.ts`),
|
|
336
|
+
* never this package's — the queue itself stays a dumb transport.
|
|
337
|
+
*/
|
|
338
|
+
export type RecentJob = {
|
|
339
|
+
id: string
|
|
340
|
+
queue: string
|
|
341
|
+
state?: string
|
|
342
|
+
type?: string
|
|
343
|
+
attemptsMade?: number
|
|
344
|
+
timestamp?: number
|
|
345
|
+
processedOn?: number
|
|
346
|
+
finishedOn?: number
|
|
347
|
+
failedReason?: string
|
|
348
|
+
/** RAW payload. Callers MUST tenant-filter + redact before this leaves the server. */
|
|
349
|
+
data: unknown
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ============================================================================
|
|
353
|
+
// Queue Interface
|
|
354
|
+
// ============================================================================
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Main queue interface that all strategies must implement.
|
|
358
|
+
* @template T - The payload type for jobs in this queue
|
|
359
|
+
*/
|
|
360
|
+
export interface Queue<T = unknown> {
|
|
361
|
+
/** Name of this queue */
|
|
362
|
+
readonly name: string
|
|
363
|
+
/** Strategy type used by this queue */
|
|
364
|
+
readonly strategy: QueueStrategyType
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Add a job to the queue.
|
|
368
|
+
* @param data - The job payload
|
|
369
|
+
* @param options - Optional scheduling options
|
|
370
|
+
* @returns Promise resolving to the job ID
|
|
371
|
+
*/
|
|
372
|
+
enqueue(data: T, options?: EnqueueOptions): Promise<string>
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Process jobs from the queue.
|
|
376
|
+
*
|
|
377
|
+
* For local strategy: processes jobs synchronously and returns result with counts.
|
|
378
|
+
* For async strategy: starts a worker and returns sentinel result (processed=-1).
|
|
379
|
+
*
|
|
380
|
+
* @param handler - Function to handle each job
|
|
381
|
+
* @param options - Processing options
|
|
382
|
+
* @returns ProcessResult with counts (or sentinel for async worker mode)
|
|
383
|
+
*/
|
|
384
|
+
process(handler: JobHandler<T>, options?: ProcessOptions): Promise<ProcessResult>
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Remove all jobs from the queue.
|
|
388
|
+
* @returns Promise with count of removed jobs
|
|
389
|
+
*/
|
|
390
|
+
clear(): Promise<{ removed: number }>
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Remove queued jobs whose payload belongs to the provided tenant/org scope.
|
|
394
|
+
* Active jobs are not forcibly terminated; callers should rely on their own
|
|
395
|
+
* cancellation/heartbeat contracts for in-flight work.
|
|
396
|
+
*/
|
|
397
|
+
removeQueuedJobsByScope?(scope: QueueJobScope): Promise<{ removed: number }>
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Close the queue and release resources.
|
|
401
|
+
*/
|
|
402
|
+
close(): Promise<void>
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Get current job counts by status.
|
|
406
|
+
* For async strategy: returns counts from BullMQ.
|
|
407
|
+
* For local strategy: waiting/completed based on last processed ID.
|
|
408
|
+
*/
|
|
409
|
+
getJobCounts(): Promise<{
|
|
410
|
+
waiting: number
|
|
411
|
+
active: number
|
|
412
|
+
completed: number
|
|
413
|
+
failed: number
|
|
414
|
+
/**
|
|
415
|
+
* Optional (#3105). Omitted by a strategy that cannot supply it — the local
|
|
416
|
+
* strategy keeps no delayed-job state, so this is async-only today.
|
|
417
|
+
*/
|
|
418
|
+
delayed?: number
|
|
419
|
+
}>
|
|
420
|
+
|
|
421
|
+
// ---------------------------------------------------------------------
|
|
422
|
+
// Optional introspection (Queue Status Dashboard, #3105) — all additive.
|
|
423
|
+
// Every method below is payload-free EXCEPT getRecentJobs, which is the
|
|
424
|
+
// privileged, separately-gated Tier 2 Job Inspector contract.
|
|
425
|
+
// ---------------------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Bounded, payload-free summary of recent failed jobs. A strategy that keeps
|
|
429
|
+
* no retained failed-job store (the local strategy) leaves this unimplemented;
|
|
430
|
+
* the snapshot builder then falls back to counts-only.
|
|
431
|
+
*/
|
|
432
|
+
getFailedJobsSummary?(limit: number, offset?: number, opts?: { type?: string }): Promise<FailedJobSummary[]>
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Processing-time metrics derived from a bounded, newest-first sample of
|
|
436
|
+
* recently completed jobs. Payload-free — only the job's own timestamp fields
|
|
437
|
+
* are read. The async strategy retains a small bounded window of completed
|
|
438
|
+
* jobs (payload reduced to ownership + type) so this sample exists.
|
|
439
|
+
*/
|
|
440
|
+
getProcessingStats?(opts?: { type?: string; sampleSize?: number }): Promise<QueueProcessingStats>
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* A small, bounded, payload-free window of in-flight (active) or queued
|
|
444
|
+
* (waiting/delayed) jobs with server-computed timing, so stuck or slow jobs
|
|
445
|
+
* are visible without enumerating the queue. Oldest / next-to-run first.
|
|
446
|
+
* A `limit` of zero (or less) yields an empty window. A strategy that cannot
|
|
447
|
+
* serve the read within its bounds throws `QueueIntrospectionUnavailableError`.
|
|
448
|
+
*/
|
|
449
|
+
getInFlightJobsSummary?(opts: {
|
|
450
|
+
state?: 'active' | 'waiting' | 'delayed'
|
|
451
|
+
type?: string
|
|
452
|
+
limit: number
|
|
453
|
+
}): Promise<InFlightJobSummary[]>
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Tier 2 (privileged) ONLY. Returns full jobs INCLUDING raw payload — never
|
|
457
|
+
* call this from a broadly-accessible surface. Supports a bounded last-X
|
|
458
|
+
* window (newest first, merged across states when `state` is omitted), or a
|
|
459
|
+
* single job by `id` (the click-through path from a Tier 1 row). The returned
|
|
460
|
+
* `state` is the job's actual state, never the caller's query. A strategy that
|
|
461
|
+
* does not retain a requested state returns an empty list for it.
|
|
462
|
+
*/
|
|
463
|
+
getRecentJobs?(opts: {
|
|
464
|
+
state?: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed'
|
|
465
|
+
type?: string
|
|
466
|
+
id?: string
|
|
467
|
+
limit: number
|
|
468
|
+
offset?: number
|
|
469
|
+
}): Promise<RecentJob[]>
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ============================================================================
|
|
473
|
+
// Factory Types
|
|
474
|
+
// ============================================================================
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Discriminated union for queue creation options.
|
|
478
|
+
*/
|
|
479
|
+
export type CreateQueueConfig<S extends QueueStrategyType = QueueStrategyType, T = unknown> =
|
|
480
|
+
S extends 'async'
|
|
481
|
+
? { strategy: 'async' } & AsyncQueueOptions<T>
|
|
482
|
+
: { strategy: 'local' } & LocalQueueOptions<T>
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Factory function signature for creating queues.
|
|
486
|
+
*/
|
|
487
|
+
export type CreateQueueFn = <T = unknown>(
|
|
488
|
+
name: string,
|
|
489
|
+
strategy: QueueStrategyType,
|
|
490
|
+
options?: QueueOptions<QueueStrategyType, T>
|
|
491
|
+
) => Queue<T>
|
|
492
|
+
|
|
493
|
+
// ============================================================================
|
|
494
|
+
// Worker Discovery Types
|
|
495
|
+
// ============================================================================
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Metadata exported by worker files for auto-discovery.
|
|
499
|
+
*
|
|
500
|
+
* @example
|
|
501
|
+
* ```typescript
|
|
502
|
+
* // src/modules/example/workers/my-queue.ts
|
|
503
|
+
* export const metadata: WorkerMeta = {
|
|
504
|
+
* queue: 'my-queue',
|
|
505
|
+
* concurrency: 5,
|
|
506
|
+
* }
|
|
507
|
+
* ```
|
|
508
|
+
*/
|
|
509
|
+
export type WorkerMeta = {
|
|
510
|
+
/** Queue name this worker processes */
|
|
511
|
+
queue: string
|
|
512
|
+
/** Optional unique identifier (defaults to <module>:workers:<filename>) */
|
|
513
|
+
id?: string
|
|
514
|
+
/** Worker concurrency (default: 1) */
|
|
515
|
+
concurrency?: number
|
|
516
|
+
/** How long a job lock is held before the job counts as stalled, in ms. */
|
|
517
|
+
lockDuration?: number
|
|
518
|
+
/** Number of stalled-job recoveries BullMQ permits before failing a job. */
|
|
519
|
+
maxStalledCount?: number
|
|
520
|
+
/**
|
|
521
|
+
* Called when the queue abandons one of this worker's jobs without running the handler.
|
|
522
|
+
*
|
|
523
|
+
* Declared here rather than on the producing queue because the worker is the side that must hear
|
|
524
|
+
* it: the event being reported is a worker restart, and the process that restarts never
|
|
525
|
+
* constructs the enqueueing queue. See `AsyncQueueOptions.onJobAbandoned` for the contract.
|
|
526
|
+
*/
|
|
527
|
+
onJobAbandoned?: AsyncQueueOptions['onJobAbandoned']
|
|
528
|
+
/**
|
|
529
|
+
* Opt-in flag allowing this queue to be selected as a user-facing scheduler
|
|
530
|
+
* target. Internal and system-only workers (webhook processors, indexers,
|
|
531
|
+
* bulk operations) must leave it unset — they stay undiscoverable by the
|
|
532
|
+
* scheduler job API.
|
|
533
|
+
*/
|
|
534
|
+
schedulerSafe?: boolean
|
|
535
|
+
/**
|
|
536
|
+
* Creator features a principal must hold (on top of scheduler.jobs.manage)
|
|
537
|
+
* to schedule onto this worker's queue. Only read when schedulerSafe is set.
|
|
538
|
+
*/
|
|
539
|
+
schedulerRequiredFeatures?: string[]
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Descriptor for a discovered and registered worker.
|
|
544
|
+
* @template T - The job payload type this worker handles
|
|
545
|
+
*/
|
|
546
|
+
export type WorkerDescriptor<T = unknown> = {
|
|
547
|
+
/** Unique identifier for this worker */
|
|
548
|
+
id: string
|
|
549
|
+
/** Queue name to process */
|
|
550
|
+
queue: string
|
|
551
|
+
/** Handler function */
|
|
552
|
+
handler: JobHandler<T>
|
|
553
|
+
/** Concurrency level */
|
|
554
|
+
concurrency: number
|
|
555
|
+
/** How long a job lock is held before the job counts as stalled, in ms. */
|
|
556
|
+
lockDuration?: number
|
|
557
|
+
/** Number of stalled-job recoveries BullMQ permits before failing a job. */
|
|
558
|
+
maxStalledCount?: number
|
|
559
|
+
/** Called when the queue abandons one of this worker's jobs without running the handler. */
|
|
560
|
+
onJobAbandoned?: AsyncQueueOptions['onJobAbandoned']
|
|
561
|
+
}
|
package/tsconfig.json
ADDED
package/watch.mjs
ADDED
package/README.md
DELETED