@zintrust/queue-monitor 2.4.6 → 2.4.8

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.
@@ -6,6 +6,64 @@ 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
+ const jobIdentity = (job) => {
10
+ const queue = job.queue ?? '';
11
+ const id = job.id == null ? '' : String(job.id);
12
+ const timestamp = Number.isFinite(job.timestamp) ? String(job.timestamp) : '';
13
+ return `${queue}::${id}::${timestamp}`;
14
+ };
15
+ const dedupeJobs = (jobs) => {
16
+ const seen = new Set();
17
+ return jobs.filter((job) => {
18
+ const identity = jobIdentity(job);
19
+ if (seen.has(identity))
20
+ return false;
21
+ seen.add(identity);
22
+ return true;
23
+ });
24
+ };
25
+ const jobSummaryFromDriverJob = (queueName, job, now) => {
26
+ // Use the actual state from BullMQ if available.
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ const jobState = job._state;
29
+ const isFailed = Boolean(job.failedReason) || jobState === 'failed';
30
+ const isCompleted = Boolean(job.finishedOn) || jobState === 'completed';
31
+ const isActive = Boolean(job.processedOn && !job.finishedOn && !job.failedReason) || jobState === 'active';
32
+ const isDelayed = jobState === 'delayed';
33
+ const isPaused = jobState === 'paused';
34
+ let status;
35
+ if (isFailed) {
36
+ status = 'failed';
37
+ }
38
+ else if (isCompleted) {
39
+ status = 'completed';
40
+ }
41
+ else if (isActive) {
42
+ status = 'active';
43
+ }
44
+ else if (isDelayed) {
45
+ status = 'delayed';
46
+ }
47
+ else if (isPaused) {
48
+ status = 'paused';
49
+ }
50
+ else {
51
+ status = 'waiting';
52
+ }
53
+ return {
54
+ id: job.id,
55
+ name: job.name,
56
+ queue: queueName,
57
+ data: job.data,
58
+ opts: job.opts,
59
+ attempts: job.attemptsMade,
60
+ status,
61
+ failedReason: job.failedReason || undefined,
62
+ timestamp: job.timestamp ?? now,
63
+ processedOn: job.processedOn ?? undefined,
64
+ finishedOn: job.finishedOn ?? undefined,
65
+ };
66
+ };
9
67
  export const emptyLockAnalytics = () => ({
10
68
  locks: [],
11
69
  metrics: { active: 0, attempts: 0, acquired: 0, collisions: 0, collisionRate: 0 },
@@ -236,63 +294,18 @@ export const QueueMonitoringStream = (res, req, getSnapshot, getLocks, metrics,
236
294
  });
237
295
  };
238
296
  export async function getRecentJobsForQueue(queueName, metrics, driver) {
239
- const [recent, failed] = await Promise.all([
297
+ const [recent, failed, driverJobs] = await Promise.all([
240
298
  metrics.getRecentJobs(queueName).catch(() => []),
241
299
  metrics.getFailedJobs(queueName).catch(() => []),
300
+ driver.getRecentJobs(queueName, 100).catch((error) => {
301
+ Logger.warn('[queue-monitor] Driver recent jobs unavailable; returning no jobs', error);
302
+ return [];
303
+ }),
242
304
  ]);
243
- const all = sortJobsByTimestamp([...recent, ...failed].map((job) => ({
305
+ const now = Date.now();
306
+ const liveJobs = driverJobs.map((job) => jobSummaryFromDriverJob(queueName, job, now));
307
+ return dedupeJobs(sortJobsByTimestamp([...recent, ...failed, ...liveJobs].map((job) => ({
244
308
  ...job,
245
309
  queue: job.queue ?? queueName,
246
- }))).slice(0, 100);
247
- if (all.length > 0) {
248
- return all;
249
- }
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
- });
254
- const now = Date.now();
255
- return jobs.map((job) => {
256
- // Use the actual state from BullMQ if available
257
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
258
- const jobState = job._state;
259
- // Fallback detection if state is not available
260
- const isFailed = Boolean(job.failedReason) || jobState === 'failed';
261
- const isCompleted = Boolean(job.finishedOn) || jobState === 'completed';
262
- const isActive = Boolean(job.processedOn && !job.finishedOn && !job.failedReason) || jobState === 'active';
263
- const isDelayed = jobState === 'delayed';
264
- const isPaused = jobState === 'paused';
265
- let status;
266
- if (isFailed) {
267
- status = 'failed';
268
- }
269
- else if (isCompleted) {
270
- status = 'completed';
271
- }
272
- else if (isActive) {
273
- status = 'active';
274
- }
275
- else if (isDelayed) {
276
- status = 'delayed';
277
- }
278
- else if (isPaused) {
279
- status = 'paused';
280
- }
281
- else {
282
- status = 'waiting';
283
- }
284
- return {
285
- id: job.id,
286
- name: job.name,
287
- queue: queueName,
288
- data: job.data,
289
- opts: job.opts,
290
- attempts: job.attemptsMade,
291
- status,
292
- failedReason: job.failedReason || undefined,
293
- timestamp: job.timestamp ?? now,
294
- processedOn: job.processedOn ?? undefined,
295
- finishedOn: job.finishedOn ?? undefined,
296
- };
297
- });
310
+ })))).slice(0, 100);
298
311
  }
@@ -112,6 +112,17 @@ html[data-theme="light"] .refresh-btn:hover { background: rgba(2, 132, 199, 0.16
112
112
  .retry-btn { background: rgba(59, 130, 246, 0.1); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.3); padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: 600; transition: all 0.2s; }
113
113
  .retry-btn:hover { background: rgba(59, 130, 246, 0.2); transform: scale(1.05); }
114
114
  .retry-btn:disabled { opacity: 0.5; cursor: not-allowed; }
115
+ .recover-btn { background: rgba(245, 158, 11, 0.12); color: #fbbf24; border-color: rgba(245, 158, 11, 0.35); }
116
+ .recover-btn:hover { background: rgba(245, 158, 11, 0.2); }
117
+
118
+ .job-tab-bar { display: flex; gap: 0; padding: 0 8px; border-bottom: 1px solid var(--border); overflow-x: auto; }
119
+ .job-tab { background: transparent; border: none; border-bottom: 2px solid transparent; padding: 9px 12px; cursor: pointer; font-size: 12px; font-weight: 700; color: var(--muted); transition: color 0.15s, border-color 0.15s; margin-bottom: -1px; display: flex; align-items: center; gap: 5px; white-space: nowrap; }
120
+ .job-tab:hover { color: var(--text); }
121
+ .job-tab.active-tab { color: var(--accent); border-bottom-color: var(--accent); }
122
+ .job-tab-count { background: rgba(255,255,255,0.06); padding: 1px 6px; border-radius: 999px; font-size: 10px; font-weight: 800; min-width: 16px; text-align: center; }
123
+ .job-tab.active-tab .job-tab-count { background: rgba(186,230,253,0.12); }
124
+ html[data-theme="light"] .job-tab-count { background: rgba(0,0,0,0.06); }
125
+ html[data-theme="light"] .job-tab.active-tab .job-tab-count { background: rgba(2,132,199,0.12); }
115
126
 
116
127
  #error-container { display: none; margin-bottom: 2rem; padding: 1rem; background: rgba(239, 68, 68, 0.1); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); border-radius: 0.5rem; font-size: 13px; font-weight: 600; }
117
128
  code { background: rgba(0,0,0,0.3); padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 12px; color: var(--accent); border: 1px solid var(--border); }
@@ -193,11 +204,21 @@ const getLocksSection = () => `
193
204
  `;
194
205
  const getJobsSection = () => `
195
206
  <div class="tile" style="margin-top: 24px; padding: 0;">
196
- <div style="padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border);">
207
+ <div style="padding: 16px 20px; display: flex; justify-content: space-between; align-items: center;">
197
208
  <h3 style="margin: 0; font-size: 14px; font-weight: 800; color: var(--text);">Recent Jobs</h3>
198
- <select id="queue-select">
199
- <!-- Queues inserted here -->
200
- </select>
209
+ <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
210
+ <button id="jobs-refresh" class="refresh-btn" type="button">Refresh jobs</button>
211
+ <select id="queue-select">
212
+ <!-- Queues inserted here -->
213
+ </select>
214
+ </div>
215
+ </div>
216
+ <div class="job-tab-bar">
217
+ <button class="job-tab active-tab" data-status="all" type="button" onclick="setJobStatusFilter('all')">All <span class="job-tab-count" id="tab-count-all">—</span></button>
218
+ <button class="job-tab" data-status="active" type="button" onclick="setJobStatusFilter('active')">Active <span class="job-tab-count" id="tab-count-active">—</span></button>
219
+ <button class="job-tab" data-status="waiting" type="button" onclick="setJobStatusFilter('waiting')">Waiting <span class="job-tab-count" id="tab-count-waiting">—</span></button>
220
+ <button class="job-tab" data-status="failed" type="button" onclick="setJobStatusFilter('failed')">Failed <span class="job-tab-count" id="tab-count-failed">—</span></button>
221
+ <button class="job-tab" data-status="completed" type="button" onclick="setJobStatusFilter('completed')">Completed <span class="job-tab-count" id="tab-count-completed">—</span></button>
201
222
  </div>
202
223
  <div style="overflow-x: auto;">
203
224
  <table id="jobs-table">
@@ -251,6 +272,9 @@ const getDashboardScriptState = (options) => String.raw `
251
272
  let dashboardResetTimer = null;
252
273
  let reconnectAttempts = 0;
253
274
  let currentTheme = null;
275
+ const JOB_STATUS_FILTER_KEY = 'zintrust-queue-monitor-job-status-filter';
276
+ let currentJobStatusFilter = localStorage.getItem(JOB_STATUS_FILTER_KEY) || 'all';
277
+ let allJobsCache = [];
254
278
  `;
255
279
  const getDashboardScriptTheme = () => `
256
280
  function getPreferredTheme() {
@@ -550,6 +574,9 @@ const getRenderJobsIdentityHelpersFunction = () => `
550
574
 
551
575
  function getJobRetryMarkup(job) {
552
576
  const status = (job.status || (job.failedReason ? 'failed' : 'completed')).toLowerCase();
577
+ if (status === 'active') {
578
+ return '<button class="retry-btn recover-btn" onclick="recoverActiveJob(' + "'" + job.id + "'" + ', ' + "'" + (job.queue || currentQueue) + "'" + ')" title="Recover this active job">Recover</button>';
579
+ }
553
580
  if (status === 'failed') {
554
581
  return '<button class="retry-btn" onclick="retryJob(' + "'" + job.id + "'" + ', ' + "'" + (job.queue || currentQueue) + "'" + ')" title="Retry this job">↻ Retry</button>';
555
582
  }
@@ -631,6 +658,7 @@ const getRenderJobsRowHelpersFunction = () => `
631
658
  tr.className = 'expandable-row';
632
659
  tr.addEventListener('click', (e) => {
633
660
  if (e.target.classList.contains('retry-btn')) return;
661
+ if (e.target.classList.contains('recover-btn')) return;
634
662
  toggleJobDetails(tr, tr.__jobData);
635
663
  });
636
664
  updateExistingJobRow(tr, job, idx);
@@ -698,9 +726,8 @@ const getRenderJobsRowHelpersFunction = () => `
698
726
  }
699
727
  `;
700
728
  const getRenderJobsFunction = () => `
701
- function renderJobs(jobs) {
729
+ function _renderJobsToDOM(jobList) {
702
730
  const tbody = document.querySelector('#jobs-table tbody');
703
- const jobList = Array.isArray(jobs) ? jobs : [];
704
731
 
705
732
  if (jobList.length === 0) {
706
733
  ensureEmptyJobsState(tbody);
@@ -730,7 +757,47 @@ const getRenderJobsFunction = () => `
730
757
 
731
758
  expandedJobIds = new Set([...expandedJobIds].filter(id => currentJobIds.has(id)));
732
759
  tbody.replaceChildren(fragment);
760
+ }
761
+
762
+ function renderJobs(jobs) {
763
+ allJobsCache = Array.isArray(jobs) ? jobs : [];
764
+ updateJobTabCounts(allJobsCache);
765
+ applyJobStatusFilter();
733
766
  }`;
767
+ const getJobStatusTabsFunction = () => `
768
+ function updateJobTabCounts(jobs) {
769
+ const counts = { all: jobs.length, active: 0, waiting: 0, failed: 0, completed: 0 };
770
+ jobs.forEach(function(job) {
771
+ const status = (job.status || (job.failedReason ? 'failed' : 'completed')).toLowerCase();
772
+ if (Object.prototype.hasOwnProperty.call(counts, status)) {
773
+ counts[status]++;
774
+ }
775
+ });
776
+ Object.keys(counts).forEach(function(status) {
777
+ const el = document.getElementById('tab-count-' + status);
778
+ if (el) el.textContent = String(counts[status]);
779
+ });
780
+ }
781
+
782
+ function applyJobStatusFilter() {
783
+ const filtered = currentJobStatusFilter === 'all'
784
+ ? allJobsCache
785
+ : allJobsCache.filter(function(job) {
786
+ const status = (job.status || (job.failedReason ? 'failed' : 'completed')).toLowerCase();
787
+ return status === currentJobStatusFilter;
788
+ });
789
+ _renderJobsToDOM(filtered);
790
+ }
791
+
792
+ function setJobStatusFilter(status) {
793
+ currentJobStatusFilter = status;
794
+ localStorage.setItem(JOB_STATUS_FILTER_KEY, status);
795
+ document.querySelectorAll('.job-tab').forEach(function(btn) {
796
+ btn.classList.toggle('active-tab', btn.dataset.status === status);
797
+ });
798
+ applyJobStatusFilter();
799
+ }
800
+ `;
734
801
  const getRenderLocksFunction = () => `
735
802
  // Track expanded lock keys to preserve state during SSE updates
736
803
  let expandedLockKeys = new Set();
@@ -971,6 +1038,36 @@ const getToggleDetailsFunctions = () => `
971
1038
 
972
1039
  row.parentNode.insertBefore(detailRow, row.nextSibling);
973
1040
  }`;
1041
+ const getRecoverActiveJobFunction = () => `
1042
+ async function recoverActiveJob(jobId, queueName) {
1043
+ try {
1044
+ const btn = event.target;
1045
+ btn.disabled = true;
1046
+ btn.textContent = 'Recovering...';
1047
+
1048
+ const res = await fetch(API_BASE + '/api/recover-active/' + queueName + '/' + jobId, {
1049
+ method: 'POST'
1050
+ });
1051
+ const payload = await res.json().catch(() => null);
1052
+
1053
+ if (res.ok) {
1054
+ btn.textContent = payload && payload.status === 'removed_after_delayed_retry'
1055
+ ? 'Removed'
1056
+ : 'Recovered';
1057
+ setTimeout(() => {
1058
+ fetchData();
1059
+ }, 1000);
1060
+ } else {
1061
+ btn.textContent = 'Failed';
1062
+ btn.disabled = false;
1063
+ }
1064
+ } catch (e) {
1065
+ console.error('Failed to recover active job', e);
1066
+ const btn = event.target;
1067
+ btn.textContent = 'Failed';
1068
+ btn.disabled = false;
1069
+ }
1070
+ }`;
974
1071
  const getRetryJobFunction = () => `
975
1072
  async function retryJob(jobId, queueName) {
976
1073
  try {
@@ -988,8 +1085,7 @@ const getRetryJobFunction = () => `
988
1085
  ? '✓ Requeued'
989
1086
  : '✓ Retried';
990
1087
  setTimeout(() => {
991
- console.log('HTTP jobs polling disabled - using SSE only');
992
- // fetchJobs(currentQueue);
1088
+ fetchData();
993
1089
  }, 1000);
994
1090
  } else {
995
1091
  btn.textContent = '✗ Failed';
@@ -1161,11 +1257,7 @@ const getDashboardScriptEventStream = () => `
1161
1257
  }
1162
1258
  `;
1163
1259
  const getFetchDataFunction = () => `
1164
- // HTTP polling disabled - 100% SSE reliance
1165
1260
  async function fetchData() {
1166
- console.log('HTTP polling disabled - using SSE only');
1167
- // Disabled to ensure 100% SSE streaming
1168
- /*
1169
1261
  try {
1170
1262
  document.getElementById('error-container').style.display = 'none';
1171
1263
  const res = await fetch(API_BASE + '/api/snapshot');
@@ -1173,18 +1265,26 @@ const getFetchDataFunction = () => `
1173
1265
  const data = await res.json();
1174
1266
 
1175
1267
  renderStats(data);
1176
- updateQueueSelect(data.queues);
1268
+ const nextQueue = updateQueueSelect(data.queues || []);
1269
+ currentQueue = nextQueue;
1270
+ if (currentQueue) {
1271
+ localStorage.setItem(QUEUE_KEY, currentQueue);
1272
+ } else {
1273
+ localStorage.removeItem(QUEUE_KEY);
1274
+ }
1177
1275
  handleQueueSelection(data);
1276
+ if (currentQueue) {
1277
+ await fetchJobs(currentQueue);
1278
+ }
1178
1279
  await fetchLocks();
1179
1280
  document.getElementById('last-updated').textContent = formatDateTime(new Date());
1180
1281
  } catch (e) {
1181
1282
  showError(e.message);
1182
1283
  }
1183
- */
1184
1284
  }
1185
1285
 
1186
1286
  function handleQueueSelection(data) {
1187
- if (data.queues.length > 0) {
1287
+ if (Array.isArray(data.queues) && data.queues.length > 0 && currentQueue) {
1188
1288
  document.getElementById('queue-select').value = currentQueue;
1189
1289
  } else {
1190
1290
  document.getElementById('queue-select').innerHTML = '<option>No Queues</option>';
@@ -1193,35 +1293,33 @@ const getFetchDataFunction = () => `
1193
1293
  }
1194
1294
  `;
1195
1295
  const getDashboardScriptFetch = () => `
1196
- // HTTP polling disabled - 100% SSE reliance
1197
1296
  async function fetchJobs(queue) {
1198
- console.log('HTTP jobs polling disabled - using SSE only');
1199
- // Disabled to ensure 100% SSE streaming
1200
- /*
1297
+ if (!queue) {
1298
+ renderJobs([]);
1299
+ return;
1300
+ }
1201
1301
  try {
1202
- const res = await fetch(API_BASE + '/api/jobs/' + queue);
1302
+ const res = await fetch(API_BASE + '/api/jobs/' + encodeURIComponent(queue));
1303
+ if (!res.ok) throw new Error('Failed to fetch jobs');
1203
1304
  const jobs = await res.json();
1204
1305
  renderJobs(jobs);
1205
1306
  } catch (e) {
1206
1307
  console.error('Failed to fetch jobs', e);
1308
+ showError(e.message);
1207
1309
  }
1208
- */
1209
1310
  }
1210
1311
 
1211
- // HTTP polling disabled - 100% SSE reliance
1212
1312
  async function fetchLocks() {
1213
- console.log('HTTP locks polling disabled - using SSE only');
1214
- // Disabled to ensure 100% SSE streaming
1215
- /*
1216
1313
  try {
1217
1314
  const pattern = getLockPattern();
1218
1315
  const res = await fetch(API_BASE + '/api/locks?pattern=' + encodeURIComponent(pattern));
1316
+ if (!res.ok) throw new Error('Failed to fetch locks');
1219
1317
  const data = await res.json();
1220
1318
  renderLocks(data);
1221
1319
  } catch (e) {
1222
1320
  console.error('Failed to fetch locks', e);
1321
+ showError(e.message);
1223
1322
  }
1224
- */
1225
1323
  }
1226
1324
  `;
1227
1325
  const getDashboardScriptRender = () => [
@@ -1234,10 +1332,12 @@ const getDashboardScriptRender = () => [
1234
1332
  getRenderJobsEmptyStateFunction(),
1235
1333
  getRenderJobsRowHelpersFunction(),
1236
1334
  getRenderJobsFunction(),
1335
+ getJobStatusTabsFunction(),
1237
1336
  getRenderLocksFunction(),
1238
1337
  getLockHelperFunctions(),
1239
1338
  getErrorAndTooltipFunctions(),
1240
1339
  getToggleDetailsFunctions(),
1340
+ getRecoverActiveJobFunction(),
1241
1341
  getRetryJobFunction(),
1242
1342
  ].join('\n');
1243
1343
  const getDashboardScriptBootstrap = () => `
@@ -1260,9 +1360,9 @@ const getDashboardScriptBootstrap = () => `
1260
1360
  } else {
1261
1361
  localStorage.removeItem(QUEUE_KEY);
1262
1362
  }
1263
- console.log('Queue changed - SSE will update automatically');
1264
1363
  clearError();
1265
1364
 
1365
+ fetchData();
1266
1366
  setupEventStream(currentQueue);
1267
1367
  });
1268
1368
  }
@@ -1270,8 +1370,15 @@ const getDashboardScriptBootstrap = () => `
1270
1370
  const lockRefresh = document.getElementById('lock-refresh');
1271
1371
  if (lockRefresh) {
1272
1372
  lockRefresh.addEventListener('click', () => {
1273
- console.log('Lock refresh disabled - SSE handles updates');
1274
- // fetchLocks(); // Disabled - SSE handles updates
1373
+ fetchLocks();
1374
+ setupEventStream(currentQueue);
1375
+ });
1376
+ }
1377
+
1378
+ const jobsRefresh = document.getElementById('jobs-refresh');
1379
+ if (jobsRefresh) {
1380
+ jobsRefresh.addEventListener('click', () => {
1381
+ fetchData();
1275
1382
  setupEventStream(currentQueue);
1276
1383
  });
1277
1384
  }
@@ -1282,8 +1389,13 @@ const getDashboardScriptBootstrap = () => `
1282
1389
  : storedAutoRefresh === 'true';
1283
1390
 
1284
1391
  applyTheme(getPreferredTheme());
1285
- console.log('HTTP polling disabled - 100% SSE streaming active');
1286
- // fetchData(); // Disabled - SSE handles initial data
1392
+
1393
+ // Restore persisted status filter tab
1394
+ document.querySelectorAll('.job-tab').forEach(function(btn) {
1395
+ btn.classList.toggle('active-tab', btn.dataset.status === currentJobStatusFilter);
1396
+ });
1397
+
1398
+ fetchData();
1287
1399
  setAutoRefresh(initialAutoRefresh);
1288
1400
 
1289
1401
  setupEventStream(currentQueue);
@@ -3,4 +3,4 @@
3
3
  * Contains only the core queue driver functionality for production Workers
4
4
  */
5
5
  export { createBullMQDriver } from './driver.js';
6
- export type { JobCounts, JobPayload, QueueDriver, RetryJobResult, RetrySnapshot, } from './driver.js';
6
+ export type { JobCounts, JobPayload, QueueDriver, RecoverActiveJobResult, RetryJobResult, RetrySnapshot, } from './driver.js';
package/dist/driver.d.ts CHANGED
@@ -27,6 +27,15 @@ export type RetryJobResult = {
27
27
  status: 'not_retryable';
28
28
  reason?: string;
29
29
  };
30
+ export type RecoverActiveJobResult = {
31
+ ok: true;
32
+ status: 'failed' | 'removed' | 'removed_after_delayed_retry' | 'moved';
33
+ state?: string;
34
+ } | {
35
+ ok: false;
36
+ status: 'missing' | 'not_active' | 'not_recoverable';
37
+ reason?: string;
38
+ };
30
39
  export type QueueDriver = {
31
40
  enqueue<T>(name: string, payload: T, options?: JobsOptions): Promise<string>;
32
41
  getJob(queueName: string, jobId: string): Promise<Job | undefined>;
@@ -37,6 +46,7 @@ export type QueueDriver = {
37
46
  }>>;
38
47
  getRecentJobs(queueName: string, limit?: number): Promise<Job[]>;
39
48
  retryJob(queueName: string, jobId: string, snapshot?: RetrySnapshot): Promise<RetryJobResult>;
49
+ recoverActiveJob(queueName: string, jobId: string): Promise<RecoverActiveJobResult>;
40
50
  getQueues(): Promise<string[]>;
41
51
  close(): Promise<void>;
42
52
  };
package/dist/driver.js CHANGED
@@ -123,6 +123,73 @@ const createRedisRpcRetryJob = async (queueName, jobId) => {
123
123
  const client = await createRpcClient();
124
124
  return client.queue('retryJob', { target: queueName, args: [jobId] });
125
125
  };
126
+ const redisRpcRecoverActiveLockMs = () => Math.max(1, Env.getInt('QUEUE_MONITOR_RECOVER_ACTIVE_LOCK_MS', 30_000));
127
+ const redisRpcBullMqPrefix = () => Env.get('REDIS_RPC_BULLMQ_PREFIX', Env.get('BULLMQ_PREFIX', 'bull')).replace(/:+$/u, '');
128
+ const inspectRecoveredRedisRpcJob = async (client, queueName, jobId) => {
129
+ const job = await client.queue('getJob', {
130
+ target: queueName,
131
+ args: [jobId],
132
+ });
133
+ if (!job)
134
+ return { ok: true, status: 'removed' };
135
+ if (job.state === 'failed')
136
+ return { ok: true, status: 'failed', state: job.state };
137
+ if (job.state === 'delayed') {
138
+ await client.queue('removeJob', { target: queueName, args: [jobId] });
139
+ return { ok: true, status: 'removed_after_delayed_retry', state: job.state };
140
+ }
141
+ if (job.state && job.state !== 'active') {
142
+ return { ok: true, status: 'moved', state: job.state };
143
+ }
144
+ return {
145
+ ok: false,
146
+ status: 'not_recoverable',
147
+ reason: `Job is ${job.state ?? 'unknown'} after recovery attempt`,
148
+ };
149
+ };
150
+ const createRedisRpcRecoverActiveJob = async (queueName, jobId) => {
151
+ const client = await createRpcClient();
152
+ const existingJob = await client.queue('getJob', {
153
+ target: queueName,
154
+ args: [jobId],
155
+ });
156
+ if (!existingJob)
157
+ return { ok: false, status: 'missing' };
158
+ if (existingJob.state !== 'active') {
159
+ return {
160
+ ok: false,
161
+ status: 'not_active',
162
+ reason: `Job is ${existingJob.state ?? 'unknown'}, not active`,
163
+ };
164
+ }
165
+ const visibilityTimeoutMs = redisRpcRecoverActiveLockMs();
166
+ try {
167
+ await client.queue('fail', {
168
+ target: queueName,
169
+ args: [jobId, 'manual queue-monitor stale active recovery'],
170
+ force: true,
171
+ discard: true,
172
+ visibilityTimeoutMs,
173
+ });
174
+ }
175
+ catch {
176
+ const prefix = redisRpcBullMqPrefix();
177
+ await callRedisRpc('redis', 'call', {
178
+ args: [
179
+ 'set',
180
+ `${prefix}:${queueName}:${jobId}:lock`,
181
+ 'pull-worker',
182
+ 'PX',
183
+ String(visibilityTimeoutMs),
184
+ ],
185
+ });
186
+ await client.queue('fail', {
187
+ target: queueName,
188
+ args: [jobId, 'manual queue-monitor stale active recovery'],
189
+ });
190
+ }
191
+ return inspectRecoveredRedisRpcJob(client, queueName, jobId);
192
+ };
126
193
  const createRedisRpcGetQueues = async () => {
127
194
  const client = await createRpcClient();
128
195
  try {
@@ -144,6 +211,7 @@ const createRedisRpcDriver = () => Object.freeze({
144
211
  getJobCountsMany: createRedisRpcGetJobCountsMany,
145
212
  getRecentJobs: createRedisRpcRecentJobs,
146
213
  retryJob: createRedisRpcRetryJob,
214
+ recoverActiveJob: createRedisRpcRecoverActiveJob,
147
215
  getQueues: createRedisRpcGetQueues,
148
216
  close: createRedisRpcClose,
149
217
  });
@@ -190,9 +258,9 @@ async function discoverQueuesFromRedis(redis, inMemoryQueues) {
190
258
  const createBullMQQueueGetter = (queues, redis) => {
191
259
  return async (name) => {
192
260
  if (!queues.has(name)) {
193
- const QueueCtor = await ensureBullmqLoaded();
261
+ const QueueConstructor = await ensureBullmqLoaded();
194
262
  const prefix = getBullMQSafeQueueName();
195
- const queue = new QueueCtor(name, { prefix, connection: redis });
263
+ const queue = new QueueConstructor(name, { prefix, connection: redis });
196
264
  queues.set(name, queue);
197
265
  }
198
266
  const queue = queues.get(name);
@@ -294,6 +362,35 @@ const createBullMQRetryJob = (getQueue, getJob) => async (queueName, jobId, snap
294
362
  };
295
363
  }
296
364
  };
365
+ const createBullMQRecoverActiveJob = (getQueue, getJob) => async (queueName, jobId) => {
366
+ const queue = await getQueue(queueName);
367
+ const job = await getJob(queueName, jobId);
368
+ if (!job)
369
+ return { ok: false, status: 'missing' };
370
+ const state = await job.getState().catch(() => undefined);
371
+ if (state !== 'active') {
372
+ return {
373
+ ok: false,
374
+ status: 'not_active',
375
+ reason: `Job is ${state ?? 'unknown'}, not active`,
376
+ };
377
+ }
378
+ try {
379
+ job.discard();
380
+ const queueWithClient = queue;
381
+ const client = await queueWithClient.client;
382
+ await client.set(queue.toKey(jobId) + ':lock', 'pull-worker', 'PX', String(Math.max(1, Env.getInt('QUEUE_MONITOR_RECOVER_ACTIVE_LOCK_MS', 30_000))));
383
+ await job.moveToFailed(new Error('manual queue-monitor stale active recovery'), 'pull-worker', false);
384
+ return { ok: true, status: 'failed' };
385
+ }
386
+ catch (error) {
387
+ return {
388
+ ok: false,
389
+ status: 'not_recoverable',
390
+ reason: error instanceof Error ? error.message : String(error),
391
+ };
392
+ }
393
+ };
297
394
  const createBullMQGetRecentJobs = (getQueue) => async (queueName, limit = 100) => {
298
395
  const queue = await getQueue(queueName);
299
396
  const jobs = await queue.getJobs(['completed', 'failed', 'active', 'waiting', 'delayed', 'paused'], 0, Math.max(0, limit - 1), true);
@@ -320,6 +417,7 @@ export const createBullMQDriver = (config) => {
320
417
  getJobCountsMany: createBullMQGetJobCountsMany(createBullMQGetJobCounts(getQueue)),
321
418
  getRecentJobs: createBullMQGetRecentJobs(getQueue),
322
419
  retryJob: createBullMQRetryJob(getQueue, createBullMQGetJob(getQueue)),
420
+ recoverActiveJob: createBullMQRecoverActiveJob(getQueue, createBullMQGetJob(getQueue)),
323
421
  getQueues: createBullMQGetQueues(redis, queues),
324
422
  close: createBullMQClose(queues),
325
423
  });
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { type QueueDriver } from './driver.js';
4
4
  import { type Metrics } from './metrics.js';
5
5
  export { getRecentJobsForQueue, getRecentJobsForSelection, QueueMonitoringService, QueueMonitoringStream, } from './QueueMonitoringService.js';
6
6
  export { createBullMQDriver } from './driver.js';
7
- export type { JobPayload, QueueDriver } from './driver.js';
7
+ export type { JobPayload, QueueDriver, RecoverActiveJobResult } from './driver.js';
8
8
  export { createMetrics, type JobStatus, type JobSummary, type Metrics } from './metrics.js';
9
9
  export { createWorker as createQueueWorker, type QueueWorker } from './worker.js';
10
10
  export type QueueMonitorConfig = {
package/dist/index.js CHANGED
@@ -227,6 +227,27 @@ async function handleRetryEndpoint(req, res, driver, metrics) {
227
227
  status: result.status,
228
228
  });
229
229
  }
230
+ async function handleRecoverActiveEndpoint(req, res, driver) {
231
+ const queueName = extractQueueParam(req);
232
+ const jobId = typeof req.getParam === 'function' ? req.getParam?.('jobId') : req.params?.['jobId'];
233
+ if (!queueName || !jobId) {
234
+ res.status(400).json(fieldError('queue_name,job_id', 'Queue name and job ID must be provided'));
235
+ return;
236
+ }
237
+ const result = await driver.recoverActiveJob(queueName, jobId);
238
+ if (result.ok) {
239
+ res.json({ ok: true, status: result.status, state: result.state });
240
+ return;
241
+ }
242
+ if (result.status === 'missing') {
243
+ res.status(404).json({ error: `Job ${jobId} no longer exists`, status: result.status });
244
+ return;
245
+ }
246
+ res.status(409).json({
247
+ error: result.reason ?? `Job ${jobId} cannot be recovered in its current state`,
248
+ status: result.status,
249
+ });
250
+ }
230
251
  function buildSettings(config) {
231
252
  return {
232
253
  enabled: config.enabled ?? DEFAULTS.enabled,
@@ -325,6 +346,7 @@ function registerApiRoutes(router, settings, routeOptions, metrics, driver, getS
325
346
  registerJobsApi(router, settings, routeOptions, metrics, driver);
326
347
  registerLocksApi(router, settings, routeOptions, getLocks);
327
348
  registerRetryApi(router, settings, routeOptions, driver, metrics);
349
+ registerRecoverActiveApi(router, settings, routeOptions, driver);
328
350
  registerEventsApi(router, settings, routeOptions, getSnapshot, getLocks, metrics, driver);
329
351
  }
330
352
  function registerSnapshotApi(router, settings, routeOptions, getSnapshot) {
@@ -353,6 +375,11 @@ function registerRetryApi(router, settings, routeOptions, driver, metrics) {
353
375
  await handleRetryEndpoint(req, res, driver, metrics);
354
376
  }, routeOptions);
355
377
  }
378
+ function registerRecoverActiveApi(router, settings, routeOptions, driver) {
379
+ Router.post(router, `${settings.basePath}/api/recover-active/:queue/:jobId`, async (req, res) => {
380
+ await handleRecoverActiveEndpoint(req, res, driver);
381
+ }, routeOptions);
382
+ }
356
383
  function registerEventsApi(router, settings, routeOptions, getSnapshot, getLocks, metrics, driver) {
357
384
  Router.get(router, `${settings.basePath}/api/events`, async (req, res) => {
358
385
  QueueMonitoringStream(res, req, getSnapshot, getLocks, metrics, driver, settings);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zintrust/queue-monitor",
3
- "version": "2.4.6",
3
+ "version": "2.4.8",
4
4
  "description": "Queue monitoring package for ZinTrust with BullMQ and Redis.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -1,129 +0,0 @@
1
- {
2
- "name": "@zintrust/queue-monitor",
3
- "version": "2.4.5",
4
- "buildDate": "2026-06-03T09:57:58.476Z",
5
- "buildEnvironment": {
6
- "node": "v22.22.1",
7
- "platform": "darwin",
8
- "arch": "arm64"
9
- },
10
- "git": {
11
- "commit": "feec4c80",
12
- "branch": "release"
13
- },
14
- "package": {
15
- "engines": {
16
- "node": ">=20.0.0"
17
- },
18
- "dependencies": [
19
- "bullmq",
20
- "ioredis"
21
- ],
22
- "peerDependencies": [
23
- "@zintrust/core",
24
- "@zintrust/redis-rpc"
25
- ]
26
- },
27
- "files": {
28
- "BrandFavicon.d.ts": {
29
- "size": 81,
30
- "sha256": "0f477b645fb3df6d3f52ced87c3c0f7dc942e5f4c4710f24866eca3b2e411fb9"
31
- },
32
- "BrandFavicon.js": {
33
- "size": 721,
34
- "sha256": "33e57f6cec15b8dcb5886ca92644139d2e3ca1789aae1c3a4a066d75a273a6bb"
35
- },
36
- "QueueMonitoringService.d.ts": {
37
- "size": 1760,
38
- "sha256": "949569e78120329804b63736b25c8cff9b5516ca44c9e7f1b2989d9cb09360b9"
39
- },
40
- "QueueMonitoringService.js": {
41
- "size": 10048,
42
- "sha256": "3b7e85e6a0ba5dd958010bdf023052b1fb66cfbb52047554b326b4465b817719"
43
- },
44
- "build-manifest.json": {
45
- "size": 3871,
46
- "sha256": "2b7d6b37d81ec677fb07cbd8e69566cc5fcc953b5d40d3187b1ad75c85ab57e8"
47
- },
48
- "connection.d.ts": {
49
- "size": 287,
50
- "sha256": "dcc6ea45e59b0a2e8844b27f466dff4849618c06b74aae62a99c8edd772d0db0"
51
- },
52
- "connection.js": {
53
- "size": 178,
54
- "sha256": "ff387351f5b8c7c14a7f2ef817fbbb065ad677faffcb47e5e8ddc4b064747e5b"
55
- },
56
- "dashboard-index.d.ts": {
57
- "size": 183,
58
- "sha256": "9d7c7fc63fe2919de0584d3f3d0ef74166d834af0a68caca2fe6fe64340652b9"
59
- },
60
- "dashboard-index.js": {
61
- "size": 183,
62
- "sha256": "9d7c7fc63fe2919de0584d3f3d0ef74166d834af0a68caca2fe6fe64340652b9"
63
- },
64
- "dashboard-ui.d.ts": {
65
- "size": 219,
66
- "sha256": "5140191207b5620500ac5e1edacefed65956a1ad88739695d545ea7d2b405243"
67
- },
68
- "dashboard-ui.js": {
69
- "size": 53927,
70
- "sha256": "71bab126f20aea1165ee3aa3c82e896ebd89b1f1a815ef2716cd884b846ab34f"
71
- },
72
- "driver-index.d.ts": {
73
- "size": 287,
74
- "sha256": "915a41bc57b3a5d826832bd4a899861ddbfd15a66ab04f7a599454a248222480"
75
- },
76
- "driver-index.js": {
77
- "size": 184,
78
- "sha256": "fb91df973acd13a88cca443e50ecdd34944c66e1a1d48333f63099079a00f3c9"
79
- },
80
- "driver.d.ts": {
81
- "size": 1417,
82
- "sha256": "9aa9e6ac31d8a0a3d4145a8228bd61180be89e7170b02d1290fcb732a4c217a1"
83
- },
84
- "driver.js": {
85
- "size": 12494,
86
- "sha256": "038d017128abb2c1319039bfa6d1fccc72c1eaea472d2296e1efc153dd17cfd6"
87
- },
88
- "index.d.ts": {
89
- "size": 2344,
90
- "sha256": "370b578ca6412fbdbb2f6966c0899a4c9d6d1ab08defe48a9004564124b1f45e"
91
- },
92
- "index.js": {
93
- "size": 17226,
94
- "sha256": "66b89ca171cc49187182d84d3fb9a9ae112785bd1a3cc8ea2ee103a508fcafd3"
95
- },
96
- "metrics-index.d.ts": {
97
- "size": 239,
98
- "sha256": "b68d7ca4d15e2380bc7a57e8ff6b00eb19a9f49417f7df88ff20b93cd2aeb00d"
99
- },
100
- "metrics-index.js": {
101
- "size": 171,
102
- "sha256": "53e858995605858b819f2c48c701e3b8f7d028ec51c1b4814c46284c7fb3989e"
103
- },
104
- "metrics.d.ts": {
105
- "size": 913,
106
- "sha256": "c68b254af229871ae8d4ad5c2aca00108c07465e0abb336a68a9c2023d2d5776"
107
- },
108
- "metrics.js": {
109
- "size": 3526,
110
- "sha256": "bec6d546c15a4040eaf637feb974799db85cbdf34a7cb077f7b407da31181f11"
111
- },
112
- "runtime-index.d.ts": {
113
- "size": 2230,
114
- "sha256": "b4608f964f6c5cdb5469eb320683fee827734adcf1d03ea931766405451f35df"
115
- },
116
- "runtime-index.js": {
117
- "size": 9948,
118
- "sha256": "7aa5c97aef19ec36e1309b9abc922481924672e4017bc3fe198b5eff7dabda86"
119
- },
120
- "worker.d.ts": {
121
- "size": 347,
122
- "sha256": "fb7751246ae88f5f470107e35f25f561da5919fd2619fe70b8b182d0c878ac0e"
123
- },
124
- "worker.js": {
125
- "size": 1376,
126
- "sha256": "4f114198579d049482e284738cbdf35576d48bb269cc0936053911548efacb5d"
127
- }
128
- }
129
- }