@zintrust/queue-monitor 2.4.2 → 2.4.3
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/dist/QueueMonitoringService.d.ts +1 -0
- package/dist/QueueMonitoringService.js +34 -7
- package/dist/driver.js +69 -17
- package/dist/index.js +32 -12
- package/dist/runtime-index.js +18 -4
- package/package.json +1 -1
|
@@ -22,6 +22,7 @@ type QueueMonitoringConfig = {
|
|
|
22
22
|
intervalMs: number;
|
|
23
23
|
};
|
|
24
24
|
type QueueMonitoringCallback = (data: QueueSnapshotData) => void;
|
|
25
|
+
export declare const emptyLockAnalytics: () => LockAnalytics;
|
|
25
26
|
export declare function getRecentJobsForSelection(queueName: string, metrics: Metrics, driver: QueueDriver, queueNames?: ReadonlyArray<string>): Promise<JobSummary[]>;
|
|
26
27
|
export declare const QueueMonitoringService: Readonly<{
|
|
27
28
|
subscribe(callback: QueueMonitoringCallback, config: QueueMonitoringConfig): void;
|
|
@@ -6,6 +6,11 @@ const objectIds = new WeakMap();
|
|
|
6
6
|
let nextObjectId = 0;
|
|
7
7
|
const isAllQueuesSelection = (queue) => queue === ALL_QUEUES;
|
|
8
8
|
const sortJobsByTimestamp = (jobs) => jobs.toSorted((left, right) => right.timestamp - left.timestamp);
|
|
9
|
+
export const emptyLockAnalytics = () => ({
|
|
10
|
+
locks: [],
|
|
11
|
+
metrics: { active: 0, attempts: 0, acquired: 0, collisions: 0, collisionRate: 0 },
|
|
12
|
+
histogram: [],
|
|
13
|
+
});
|
|
9
14
|
const getObjectId = (value) => {
|
|
10
15
|
const existing = objectIds.get(value);
|
|
11
16
|
if (existing !== undefined)
|
|
@@ -36,12 +41,23 @@ export async function getRecentJobsForSelection(queueName, metrics, driver, queu
|
|
|
36
41
|
return getRecentJobsForQueue(queueName, metrics, driver);
|
|
37
42
|
}
|
|
38
43
|
const names = Array.from(new Set((queueNames ?? (await driver.getQueues())).filter(Boolean)));
|
|
39
|
-
const jobsByQueue = await Promise.all(names.map(async (name) =>
|
|
44
|
+
const jobsByQueue = await Promise.all(names.map(async (name) => {
|
|
45
|
+
try {
|
|
46
|
+
return await getRecentJobsForQueue(name, metrics, driver);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
Logger.warn('[queue-monitor] Recent jobs lookup failed; returning no jobs', error);
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}));
|
|
40
53
|
return sortJobsByTimestamp(jobsByQueue.flat()).slice(0, 100);
|
|
41
54
|
}
|
|
42
55
|
const buildSnapshotPayload = async (config) => {
|
|
43
56
|
const { getSnapshot, getLocks, metrics, driver, queue: configuredQueue, pattern } = config;
|
|
44
|
-
const snapshot = await getSnapshot()
|
|
57
|
+
const snapshot = await getSnapshot().catch((error) => {
|
|
58
|
+
Logger.warn('[queue-monitor] Snapshot unavailable; returning empty snapshot', error);
|
|
59
|
+
return { status: 'ok', startedAt: new Date().toISOString(), queues: [] };
|
|
60
|
+
});
|
|
45
61
|
let queue;
|
|
46
62
|
if (isAllQueuesSelection(configuredQueue)) {
|
|
47
63
|
queue = ALL_QUEUES;
|
|
@@ -59,9 +75,15 @@ const buildSnapshotPayload = async (config) => {
|
|
|
59
75
|
queue,
|
|
60
76
|
snapshot,
|
|
61
77
|
jobs: queue
|
|
62
|
-
? await getRecentJobsForSelection(queue, metrics, driver, snapshot.queues.map((candidate) => candidate.name))
|
|
78
|
+
? await getRecentJobsForSelection(queue, metrics, driver, snapshot.queues.map((candidate) => candidate.name)).catch((error) => {
|
|
79
|
+
Logger.warn('[queue-monitor] Recent jobs unavailable; returning no jobs', error);
|
|
80
|
+
return [];
|
|
81
|
+
})
|
|
63
82
|
: [],
|
|
64
|
-
locks: await getLocks(pattern)
|
|
83
|
+
locks: await getLocks(pattern).catch((error) => {
|
|
84
|
+
Logger.warn('[queue-monitor] Lock analytics unavailable; returning empty analytics', error);
|
|
85
|
+
return emptyLockAnalytics();
|
|
86
|
+
}),
|
|
65
87
|
};
|
|
66
88
|
};
|
|
67
89
|
const pushSnapshot = async (channel) => {
|
|
@@ -214,8 +236,10 @@ export const QueueMonitoringStream = (res, req, getSnapshot, getLocks, metrics,
|
|
|
214
236
|
});
|
|
215
237
|
};
|
|
216
238
|
export async function getRecentJobsForQueue(queueName, metrics, driver) {
|
|
217
|
-
const recent = await
|
|
218
|
-
|
|
239
|
+
const [recent, failed] = await Promise.all([
|
|
240
|
+
metrics.getRecentJobs(queueName).catch(() => []),
|
|
241
|
+
metrics.getFailedJobs(queueName).catch(() => []),
|
|
242
|
+
]);
|
|
219
243
|
const all = sortJobsByTimestamp([...recent, ...failed].map((job) => ({
|
|
220
244
|
...job,
|
|
221
245
|
queue: job.queue ?? queueName,
|
|
@@ -223,7 +247,10 @@ export async function getRecentJobsForQueue(queueName, metrics, driver) {
|
|
|
223
247
|
if (all.length > 0) {
|
|
224
248
|
return all;
|
|
225
249
|
}
|
|
226
|
-
const jobs = await driver.getRecentJobs(queueName, 100)
|
|
250
|
+
const jobs = await driver.getRecentJobs(queueName, 100).catch((error) => {
|
|
251
|
+
Logger.warn('[queue-monitor] Driver recent jobs unavailable; returning no jobs', error);
|
|
252
|
+
return [];
|
|
253
|
+
});
|
|
227
254
|
const now = Date.now();
|
|
228
255
|
return jobs.map((job) => {
|
|
229
256
|
// Use the actual state from BullMQ if available
|
package/dist/driver.js
CHANGED
|
@@ -4,7 +4,6 @@ import { Logger } from '@zintrust/core/logger';
|
|
|
4
4
|
import { getBullMQSafeQueueName } from '@zintrust/core/redis';
|
|
5
5
|
import { Queue } from 'bullmq';
|
|
6
6
|
import { createRedisConnection } from './connection.js';
|
|
7
|
-
const REDIS_RPC_PACKAGE = '@zintrust/redis-rpc';
|
|
8
7
|
const shouldUseRedisRpcMonitorDriver = () => Env.USE_REDIS_PROXY === true && Env.get('REDIS_RPC_URL', '').trim() !== '';
|
|
9
8
|
const resolveRpcBaseUrl = () => {
|
|
10
9
|
const configured = Env.get('REDIS_RPC_URL', '').trim();
|
|
@@ -14,18 +13,41 @@ const resolveRpcBaseUrl = () => {
|
|
|
14
13
|
const port = Env.getInt('REDIS_RPC_PORT', 8794);
|
|
15
14
|
return `http://${host}:${port}`;
|
|
16
15
|
};
|
|
17
|
-
const
|
|
16
|
+
const createRequestId = () => {
|
|
17
|
+
const cryptoApi = globalThis.crypto;
|
|
18
|
+
if (typeof cryptoApi?.randomUUID === 'function')
|
|
19
|
+
return cryptoApi.randomUUID();
|
|
20
|
+
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
21
|
+
};
|
|
22
|
+
const normalizeRpcBaseUrl = () => {
|
|
18
23
|
try {
|
|
19
|
-
|
|
20
|
-
return mod.createRedisRpcClient({
|
|
21
|
-
baseUrl: resolveRpcBaseUrl(),
|
|
22
|
-
secret: Env.get('REDIS_RPC_SECRET', Env.get('REDIS_PROXY_SECRET', Env.APP_KEY)),
|
|
23
|
-
});
|
|
24
|
+
return new URL(resolveRpcBaseUrl());
|
|
24
25
|
}
|
|
25
26
|
catch (error) {
|
|
26
|
-
throw ErrorFactory.createConfigError('
|
|
27
|
+
throw ErrorFactory.createConfigError('REDIS_RPC_URL must be a valid URL', error);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const callRedisRpc = async (service, method, payload = {}) => {
|
|
31
|
+
const endpoint = new URL('/rpc', normalizeRpcBaseUrl());
|
|
32
|
+
const secret = Env.get('REDIS_RPC_SECRET', Env.get('REDIS_PROXY_SECRET', Env.APP_KEY));
|
|
33
|
+
const response = await fetch(endpoint, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: {
|
|
36
|
+
'content-type': 'application/json',
|
|
37
|
+
...(secret.trim() === '' ? {} : { 'x-redis-rpc-secret': secret }),
|
|
38
|
+
},
|
|
39
|
+
body: JSON.stringify({ requestId: createRequestId(), service, method, payload }),
|
|
40
|
+
});
|
|
41
|
+
const body = (await response.json().catch(() => ({})));
|
|
42
|
+
if (!response.ok || body.ok !== true) {
|
|
43
|
+
throw ErrorFactory.createTryCatchError(body.error?.message ?? `Redis RPC request failed with status ${response.status}`);
|
|
27
44
|
}
|
|
45
|
+
return body.result;
|
|
28
46
|
};
|
|
47
|
+
const createRpcClient = async () => Object.freeze({
|
|
48
|
+
queue: (method, payload = {}) => callRedisRpc('queue', method, payload),
|
|
49
|
+
monitor: (method, payload = {}) => callRedisRpc('queue-monitor', method, payload),
|
|
50
|
+
});
|
|
29
51
|
const createRedisRpcDriver = () => {
|
|
30
52
|
const enqueue = async (name, payload, options) => {
|
|
31
53
|
const client = await createRpcClient();
|
|
@@ -42,22 +64,46 @@ const createRedisRpcDriver = () => {
|
|
|
42
64
|
enqueue,
|
|
43
65
|
async getJob(queueName, jobId) {
|
|
44
66
|
const client = await createRpcClient();
|
|
45
|
-
|
|
67
|
+
try {
|
|
68
|
+
return (await client.queue('getJob', { target: queueName, args: [jobId] }));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
Logger.warn('[queue-monitor] Redis RPC job lookup failed; returning no job', error);
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
46
74
|
},
|
|
47
75
|
async getJobCounts(queueName) {
|
|
48
76
|
const client = await createRpcClient();
|
|
49
|
-
|
|
77
|
+
try {
|
|
78
|
+
return client.queue('getJobCounts', { target: queueName });
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
Logger.warn('[queue-monitor] Redis RPC job counts failed; returning empty counts', error);
|
|
82
|
+
return {};
|
|
83
|
+
}
|
|
50
84
|
},
|
|
51
85
|
async getJobCountsMany(queueNames) {
|
|
52
86
|
const client = await createRpcClient();
|
|
53
|
-
|
|
54
|
-
|
|
87
|
+
try {
|
|
88
|
+
const snapshot = await client.monitor('getSnapshot', { args: [queueNames] });
|
|
89
|
+
return snapshot.queues ?? [];
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
Logger.warn('[queue-monitor] Redis RPC batch counts failed; returning no queues', error);
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
55
95
|
},
|
|
56
96
|
async getRecentJobs(queueName, limit = 100) {
|
|
57
97
|
const client = await createRpcClient();
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
98
|
+
try {
|
|
99
|
+
return (await client.monitor('getRecentJobsForQueue', {
|
|
100
|
+
args: [queueName, limit],
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
Logger.warn('[queue-monitor] Redis RPC recent jobs failed; returning no jobs', error);
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
61
107
|
},
|
|
62
108
|
async retryJob(queueName, jobId) {
|
|
63
109
|
const client = await createRpcClient();
|
|
@@ -65,8 +111,14 @@ const createRedisRpcDriver = () => {
|
|
|
65
111
|
},
|
|
66
112
|
async getQueues() {
|
|
67
113
|
const client = await createRpcClient();
|
|
68
|
-
|
|
69
|
-
|
|
114
|
+
try {
|
|
115
|
+
const snapshot = await client.monitor('getSnapshot');
|
|
116
|
+
return (snapshot.queues ?? []).map((queue) => queue.name);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
Logger.warn('[queue-monitor] Redis RPC queue discovery failed; returning no queues', error);
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
70
122
|
},
|
|
71
123
|
async close() {
|
|
72
124
|
await Promise.resolve();
|
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import { createRedisConnection } from './connection.js';
|
|
|
8
8
|
import { getDashboardHtml } from './dashboard-ui.js';
|
|
9
9
|
import { createBullMQDriver as createQueueDriver, } from './driver.js';
|
|
10
10
|
import { createMetrics } from './metrics.js';
|
|
11
|
-
import { getRecentJobsForSelection, QueueMonitoringStream } from './QueueMonitoringService.js';
|
|
11
|
+
import { emptyLockAnalytics, getRecentJobsForSelection, QueueMonitoringStream, } from './QueueMonitoringService.js';
|
|
12
12
|
export { getRecentJobsForQueue, getRecentJobsForSelection, QueueMonitoringService, QueueMonitoringStream, } from './QueueMonitoringService.js';
|
|
13
13
|
export { createBullMQDriver } from './driver.js';
|
|
14
14
|
export { createMetrics } from './metrics.js';
|
|
@@ -156,6 +156,10 @@ function createGetLocks(redisConfig) {
|
|
|
156
156
|
histogram,
|
|
157
157
|
};
|
|
158
158
|
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
Logger.warn('[queue-monitor] Lock analytics failed; returning empty analytics', error);
|
|
161
|
+
return emptyLockAnalytics();
|
|
162
|
+
}
|
|
159
163
|
finally {
|
|
160
164
|
if (typeof client.quit === 'function') {
|
|
161
165
|
await client.quit();
|
|
@@ -227,9 +231,17 @@ function buildSettings(config) {
|
|
|
227
231
|
}
|
|
228
232
|
function createGetSnapshot(driver, startedAt, knownQueues) {
|
|
229
233
|
return async () => {
|
|
230
|
-
const persistedQueues = await resolveKnownQueues(knownQueues)
|
|
234
|
+
const persistedQueues = await resolveKnownQueues(knownQueues).catch((error) => {
|
|
235
|
+
Logger.warn('[queue-monitor] Known queue resolution failed; using no configured queues', error);
|
|
236
|
+
return [];
|
|
237
|
+
});
|
|
231
238
|
const shouldDiscoverQueues = persistedQueues.length === 0;
|
|
232
|
-
const discoveredQueues = shouldDiscoverQueues
|
|
239
|
+
const discoveredQueues = shouldDiscoverQueues
|
|
240
|
+
? await driver.getQueues().catch((error) => {
|
|
241
|
+
Logger.warn('[queue-monitor] Queue discovery failed; using no discovered queues', error);
|
|
242
|
+
return [];
|
|
243
|
+
})
|
|
244
|
+
: [];
|
|
233
245
|
const queues = Array.from(new Set([...persistedQueues, ...discoveredQueues])).sort((left, right) => left.localeCompare(right));
|
|
234
246
|
const QUEUE_MONITOR_LOGGING_ENABLED = Env.getBool('QUEUE_MONITOR_LOGGING_ENABLED', false);
|
|
235
247
|
if (QUEUE_MONITOR_LOGGING_ENABLED) {
|
|
@@ -243,15 +255,23 @@ function createGetSnapshot(driver, startedAt, knownQueues) {
|
|
|
243
255
|
});
|
|
244
256
|
}
|
|
245
257
|
const batchStartedAt = Date.now();
|
|
246
|
-
const stats =
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
258
|
+
const stats = await (async () => {
|
|
259
|
+
try {
|
|
260
|
+
return typeof driver.getJobCountsMany === 'function'
|
|
261
|
+
? (await driver.getJobCountsMany(queues)).map((item) => ({
|
|
262
|
+
name: item.name,
|
|
263
|
+
counts: item.counts,
|
|
264
|
+
}))
|
|
265
|
+
: await Promise.all(queues.map(async (name) => {
|
|
266
|
+
const counts = await driver.getJobCounts(name);
|
|
267
|
+
return { name, counts: counts };
|
|
268
|
+
}));
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
Logger.warn('[queue-monitor] Queue count lookup failed; returning empty snapshot', error);
|
|
272
|
+
return [];
|
|
273
|
+
}
|
|
274
|
+
})();
|
|
255
275
|
if (QUEUE_MONITOR_LOGGING_ENABLED) {
|
|
256
276
|
Logger.info('[queue-monitor] snapshot queue counts resolved', {
|
|
257
277
|
durationMs: Date.now() - batchStartedAt,
|
package/dist/runtime-index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { ShutdownTrace } from '@zintrust/core/workers';
|
|
|
10
10
|
import { createRedisConnection } from './connection.js';
|
|
11
11
|
import { createBullMQDriver } from './driver.js';
|
|
12
12
|
import { createMetrics } from './metrics.js';
|
|
13
|
+
import { emptyLockAnalytics } from './QueueMonitoringService.js';
|
|
13
14
|
export { createMetrics } from './metrics.js';
|
|
14
15
|
export { createWorker as createQueueWorker } from './worker.js';
|
|
15
16
|
const DEFAULTS = {
|
|
@@ -146,6 +147,10 @@ function createGetLocks(redisConfig) {
|
|
|
146
147
|
histogram,
|
|
147
148
|
};
|
|
148
149
|
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
Logger.warn('[queue-monitor] Lock analytics failed; returning empty analytics', error);
|
|
152
|
+
return emptyLockAnalytics();
|
|
153
|
+
}
|
|
149
154
|
finally {
|
|
150
155
|
if (typeof client.quit === 'function') {
|
|
151
156
|
await client.quit();
|
|
@@ -170,14 +175,23 @@ function buildSettings(config) {
|
|
|
170
175
|
function createGetSnapshot(driver, startedAt, knownQueues) {
|
|
171
176
|
return async () => {
|
|
172
177
|
const [discoveredQueues, persistedQueues] = await Promise.all([
|
|
173
|
-
driver.getQueues()
|
|
174
|
-
|
|
178
|
+
driver.getQueues().catch((error) => {
|
|
179
|
+
Logger.warn('[queue-monitor] Queue discovery failed; using no discovered queues', error);
|
|
180
|
+
return [];
|
|
181
|
+
}),
|
|
182
|
+
resolveKnownQueues(knownQueues).catch((error) => {
|
|
183
|
+
Logger.warn('[queue-monitor] Known queue resolution failed; using no configured queues', error);
|
|
184
|
+
return [];
|
|
185
|
+
}),
|
|
175
186
|
]);
|
|
176
187
|
const queues = Array.from(new Set([...persistedQueues, ...discoveredQueues])).sort((left, right) => left.localeCompare(right));
|
|
177
188
|
const stats = await Promise.all(queues.map(async (name) => {
|
|
178
|
-
const counts = await driver.getJobCounts(name);
|
|
189
|
+
const counts = await driver.getJobCounts(name).catch(() => ({}));
|
|
179
190
|
return { name, counts: counts };
|
|
180
|
-
}))
|
|
191
|
+
})).catch((error) => {
|
|
192
|
+
Logger.warn('[queue-monitor] Queue count lookup failed; returning empty snapshot', error);
|
|
193
|
+
return [];
|
|
194
|
+
});
|
|
181
195
|
return {
|
|
182
196
|
status: 'ok',
|
|
183
197
|
startedAt,
|