@zintrust/workers 1.5.2 → 1.7.2

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.
@@ -16,6 +16,24 @@ const getAuditPrefix = () => {
16
16
  let redisClient = null;
17
17
  let retentionPolicy = null;
18
18
  let cleanupInterval = null;
19
+ const REDIS_SHUTDOWN_TIMEOUT_MS = 100;
20
+ const closeRedisClient = async (client) => {
21
+ try {
22
+ await Promise.race([
23
+ client.quit(),
24
+ new Promise((_, reject) => {
25
+ const timeoutId = globalThis.setTimeout(() => {
26
+ reject(new Error('DeadLetterQueue Redis shutdown timed out'));
27
+ }, REDIS_SHUTDOWN_TIMEOUT_MS);
28
+ timeoutId.unref?.();
29
+ }),
30
+ ]);
31
+ }
32
+ catch (error) {
33
+ Logger.warn('DeadLetterQueue graceful Redis shutdown failed, forcing disconnect', error);
34
+ client.disconnect();
35
+ }
36
+ };
19
37
  /**
20
38
  * Helper: Get DLQ key
21
39
  */
@@ -536,7 +554,7 @@ export const DeadLetterQueue = Object.freeze({
536
554
  cleanupInterval = null;
537
555
  }
538
556
  if (redisClient) {
539
- await redisClient.quit();
557
+ await closeRedisClient(redisClient);
540
558
  redisClient = null;
541
559
  }
542
560
  retentionPolicy = null;
@@ -3,7 +3,7 @@
3
3
  * Enable workers to process multiple queues with different priorities
4
4
  * Sealed namespace for immutability
5
5
  */
6
- import { ErrorFactory, Logger } from '@zintrust/core';
6
+ import { ErrorFactory, Logger, ShutdownTrace } from '@zintrust/core';
7
7
  import { Worker } from 'bullmq';
8
8
  import { PriorityQueue } from './PriorityQueue.js';
9
9
  // Internal state
@@ -28,6 +28,13 @@ const createQueueWorker = async (workerName, queueConfig, processor) => {
28
28
  });
29
29
  return processor(job);
30
30
  }, workerOptions);
31
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.create', worker, {
32
+ workerName,
33
+ queueName: queueConfig.name,
34
+ configuredConcurrency: queueConfig.concurrency,
35
+ configuredPriority: queueConfig.priority,
36
+ enabled: queueConfig.enabled,
37
+ });
31
38
  // Set up event listeners
32
39
  worker.on('completed', (job) => {
33
40
  const stats = multiQueueWorkers.get(workerName)?.stats.get(queueConfig.name);
@@ -260,7 +267,17 @@ export const MultiQueueWorker = Object.freeze({
260
267
  throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
261
268
  }
262
269
  // Close all workers
263
- const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
270
+ const closePromises = Array.from(mqw.workers.entries()).map(async ([queueName, worker]) => {
271
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.remove.close.start', worker, {
272
+ workerName,
273
+ queueName,
274
+ });
275
+ await worker.close(true);
276
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.remove.close.complete', worker, {
277
+ workerName,
278
+ queueName,
279
+ });
280
+ });
264
281
  await Promise.all(closePromises);
265
282
  multiQueueWorkers.delete(workerName);
266
283
  Logger.info(`Multi-queue worker removed: ${workerName}`);
@@ -270,13 +287,27 @@ export const MultiQueueWorker = Object.freeze({
270
287
  */
271
288
  async shutdown() {
272
289
  Logger.info('MultiQueueWorker shutting down...');
290
+ ShutdownTrace.logHandles('multi-queue-worker.shutdown.start', {
291
+ workerGroupCount: multiQueueWorkers.size,
292
+ });
273
293
  const shutdownPromises = Array.from(multiQueueWorkers.values()).map(async (mqw) => {
274
- const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
294
+ const closePromises = Array.from(mqw.workers.entries()).map(async ([queueName, worker]) => {
295
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.shutdown.close.start', worker, {
296
+ workerName: mqw.config.workerName,
297
+ queueName,
298
+ });
299
+ await worker.close(true);
300
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.shutdown.close.complete', worker, {
301
+ workerName: mqw.config.workerName,
302
+ queueName,
303
+ });
304
+ });
275
305
  await Promise.all(closePromises);
276
306
  });
277
307
  await Promise.all(shutdownPromises);
278
308
  multiQueueWorkers.clear();
279
309
  Logger.info('MultiQueueWorker shutdown complete');
310
+ ShutdownTrace.logHandles('multi-queue-worker.shutdown.complete');
280
311
  },
281
312
  });
282
313
  // Graceful shutdown handled by WorkerShutdown
@@ -17,7 +17,7 @@ const loadQueueRedisModule = async () => {
17
17
  if (queueRedisModule)
18
18
  return queueRedisModule;
19
19
  try {
20
- queueRedisModule = (await import('@zintrust/queue-redis'));
20
+ queueRedisModule = await import('@zintrust/queue-redis');
21
21
  return queueRedisModule;
22
22
  }
23
23
  catch (error) {
@@ -266,9 +266,15 @@ export const PriorityQueue = Object.freeze({
266
266
  */
267
267
  async shutdown() {
268
268
  Logger.info('PriorityQueue shutting down via BullMQRedisQueue...');
269
+ if (!queueRedisModule) {
270
+ Logger.info('PriorityQueue shutdown complete');
271
+ return;
272
+ }
269
273
  const queueRedis = await loadQueueRedisModule();
270
- if (!queueRedis)
274
+ if (!queueRedis) {
275
+ Logger.info('PriorityQueue shutdown complete');
271
276
  return;
277
+ }
272
278
  await queueRedis.BullMQRedisQueue.shutdown();
273
279
  Logger.info('PriorityQueue shutdown complete');
274
280
  },
@@ -26,6 +26,20 @@ import { resolveWorkerKeyPrefix } from './config/workerConfig.js';
26
26
  import { recordQueueMonitorJob } from './queueMonitorHistory.js';
27
27
  import { DbWorkerStore, InMemoryWorkerStore, RedisWorkerStore, } from './storage/WorkerStore.js';
28
28
  const path = NodeSingletons.path;
29
+ const createNoopShutdownTrace = () => ({
30
+ log: () => undefined,
31
+ logHandles: () => undefined,
32
+ });
33
+ const resolveShutdownTrace = () => {
34
+ try {
35
+ const candidate = ZintrustCoreModule.ShutdownTrace;
36
+ return candidate ?? createNoopShutdownTrace();
37
+ }
38
+ catch {
39
+ return createNoopShutdownTrace();
40
+ }
41
+ };
42
+ const ShutdownTrace = resolveShutdownTrace();
29
43
  const isNodeRuntime = () => typeof process !== 'undefined' && Boolean(process.versions?.node);
30
44
  const resolveProjectRoot = () => {
31
45
  const envRoot = Env.get('ZINTRUST_PROJECT_ROOT', '').trim();
@@ -287,6 +301,64 @@ const workers = new Map();
287
301
  let workerStore = InMemoryWorkerStore.create();
288
302
  let workerStoreConfigured = false;
289
303
  let workerStoreConfig = null;
304
+ const collectWorkerStoresForCleanup = (stores = []) => {
305
+ const storesToClose = new Set(stores);
306
+ if (workerStoreConfigured) {
307
+ storesToClose.add(workerStore);
308
+ }
309
+ for (const store of storeInstanceCache.values()) {
310
+ storesToClose.add(store);
311
+ }
312
+ return storesToClose;
313
+ };
314
+ const closeWorkerStores = async (stores = []) => {
315
+ const storesToClose = collectWorkerStoresForCleanup(stores);
316
+ ShutdownTrace.logHandles('worker-factory.store-cleanup.start', {
317
+ storeCount: storesToClose.size,
318
+ storeTypes: Array.from(storesToClose).map((store) => store.constructor.name),
319
+ });
320
+ await Promise.all(Array.from(storesToClose).map(async (store) => {
321
+ if (typeof store.close !== 'function')
322
+ return;
323
+ await shutdownWithTimeout('WorkerStore', async () => {
324
+ await store.close?.();
325
+ }, 100);
326
+ }));
327
+ workerStoreConfigured = false;
328
+ workerStoreConfig = null;
329
+ workerStore = InMemoryWorkerStore.create();
330
+ storeInstanceCache.clear();
331
+ ShutdownTrace.logHandles('worker-factory.store-cleanup.complete');
332
+ };
333
+ const shutdownWithTimeout = async (label, action, timeoutMs = 150) => {
334
+ let timeoutId;
335
+ try {
336
+ ShutdownTrace.log('worker-factory.step.start', { label, timeoutMs });
337
+ await Promise.race([
338
+ action(),
339
+ new Promise((_, reject) => {
340
+ timeoutId = globalThis.setTimeout(() => {
341
+ reject(ErrorFactory.createGeneralError(`${label} shutdown timed out`, { timeoutMs }));
342
+ }, timeoutMs);
343
+ timeoutId.unref?.();
344
+ }),
345
+ ]);
346
+ ShutdownTrace.logHandles('worker-factory.step.complete', { label, timeoutMs });
347
+ }
348
+ catch (error) {
349
+ Logger.warn(`${label} shutdown failed or timed out`, error);
350
+ ShutdownTrace.logHandles('worker-factory.step.failed', {
351
+ label,
352
+ timeoutMs,
353
+ error: error instanceof Error ? error.message : String(error),
354
+ });
355
+ }
356
+ finally {
357
+ if (timeoutId !== undefined) {
358
+ globalThis.clearTimeout(timeoutId);
359
+ }
360
+ }
361
+ };
290
362
  const processorRegistry = new Map();
291
363
  const processorPathRegistry = new Map();
292
364
  const processorResolvers = [];
@@ -2626,6 +2698,9 @@ export const WorkerFactory = Object.freeze({
2626
2698
  */
2627
2699
  async shutdown() {
2628
2700
  Logger.info('WorkerFactory shutting down...');
2701
+ ShutdownTrace.logHandles('worker-factory.shutdown.start', {
2702
+ workerCount: workers.size,
2703
+ });
2629
2704
  const workerEntries = Array.from(workers.entries());
2630
2705
  const workerNames = workerEntries.map(([name]) => name);
2631
2706
  // Bulk-update persisted statuses before stopping workers to avoid per-worker DB updates
@@ -2659,31 +2734,50 @@ export const WorkerFactory = Object.freeze({
2659
2734
  await Promise.all(workerNames.map(async (name) => WorkerFactory.stop(name, undefined, { skipPersistedUpdate: true })));
2660
2735
  // Shutdown all modules
2661
2736
  ResourceMonitor.stop();
2662
- await WorkerMetrics.shutdown();
2663
- await MultiQueueWorker.shutdown();
2664
- await ComplianceManager.shutdown();
2665
- await PriorityQueue.shutdown();
2666
2737
  HealthMonitor.shutdown();
2667
2738
  AutoScaler.stop();
2668
- ClusterLock.shutdown();
2669
2739
  WorkerVersioning.shutdown();
2670
2740
  CanaryController.shutdown();
2671
2741
  DatacenterOrchestrator.shutdown();
2672
- PluginManager.shutdown();
2673
2742
  Observability.shutdown();
2674
- await DeadLetterQueue.shutdown();
2675
2743
  CircuitBreaker.shutdown();
2744
+ await Promise.all([
2745
+ shutdownWithTimeout('WorkerMetrics', async () => {
2746
+ await WorkerMetrics.shutdown();
2747
+ }),
2748
+ shutdownWithTimeout('MultiQueueWorker', async () => {
2749
+ await MultiQueueWorker.shutdown();
2750
+ }),
2751
+ shutdownWithTimeout('ComplianceManager', async () => {
2752
+ await ComplianceManager.shutdown();
2753
+ }),
2754
+ shutdownWithTimeout('PriorityQueue', async () => {
2755
+ await PriorityQueue.shutdown();
2756
+ }),
2757
+ shutdownWithTimeout('ClusterLock', async () => {
2758
+ await ClusterLock.shutdown();
2759
+ }),
2760
+ shutdownWithTimeout('PluginManager', async () => {
2761
+ await PluginManager.shutdown();
2762
+ }),
2763
+ shutdownWithTimeout('DeadLetterQueue', async () => {
2764
+ await DeadLetterQueue.shutdown();
2765
+ }),
2766
+ closeWorkerStores(storeGroups.keys()),
2767
+ ]);
2768
+ ShutdownTrace.logHandles('worker-factory.shutdown.after-parallel-teardown', {
2769
+ workerCount: workers.size,
2770
+ });
2676
2771
  workers.clear();
2677
2772
  Logger.info('WorkerFactory shutdown complete');
2773
+ ShutdownTrace.logHandles('worker-factory.shutdown.complete');
2678
2774
  },
2679
2775
  /**
2680
2776
  * Reset persistence connection state.
2681
2777
  * Useful when connections become stale in long-running processes or serverless environments.
2682
2778
  */
2683
2779
  async resetPersistence() {
2684
- workerStoreConfigured = false;
2685
- workerStore = InMemoryWorkerStore.create();
2686
- storeInstanceCache.clear();
2780
+ await closeWorkerStores();
2687
2781
  Logger.info('Worker persistence configuration reset');
2688
2782
  },
2689
2783
  });
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@zintrust/workers",
3
- "version": "1.5.2",
4
- "buildDate": "2026-04-25T12:35:50.007Z",
3
+ "version": "1.7.2",
4
+ "buildDate": "2026-05-01T06:34:10.880Z",
5
5
  "buildEnvironment": {
6
6
  "node": "v20.20.2",
7
7
  "platform": "linux",
8
8
  "arch": "x64"
9
9
  },
10
10
  "git": {
11
- "commit": "616b0d5d",
11
+ "commit": "549bf22e",
12
12
  "branch": "master"
13
13
  },
14
14
  "package": {
@@ -106,8 +106,8 @@
106
106
  "sha256": "dd82e7e2c23a2fcaefc0cb87a1a7931594d6a5f76b758f608c77063f5e8533cd"
107
107
  },
108
108
  "DeadLetterQueue.js": {
109
- "size": 19512,
110
- "sha256": "47ad34c16e8e44a7febb849c56d7558f0f5a951a771c7b2e5c73c8db1b718e63"
109
+ "size": 20135,
110
+ "sha256": "7e60e3cef67195cc9dff4f6580d78db1012da4a688719ba193d5f9b984757583"
111
111
  },
112
112
  "HealthMonitor.d.ts": {
113
113
  "size": 1485,
@@ -122,8 +122,8 @@
122
122
  "sha256": "45d2b0a22c187de40aaf8d26ec69b051ae1fc08eff0c200dd93ed03e2406c066"
123
123
  },
124
124
  "MultiQueueWorker.js": {
125
- "size": 10708,
126
- "sha256": "23837171b31c5242e4b43226cb0acae815dea0ce7b1628aa1428a86b24689230"
125
+ "size": 12067,
126
+ "sha256": "e7bf8e95b6ff589548c3aef2c12a644e43d5ca52a6c6430ce0cee0931ad47979"
127
127
  },
128
128
  "NotificationWorker.d.ts": {
129
129
  "size": 952,
@@ -154,8 +154,8 @@
154
154
  "sha256": "c9bca520824e523f0e7d7f0f04be0e36de8375d5b9cc0319238f6d9460186df2"
155
155
  },
156
156
  "PriorityQueue.js": {
157
- "size": 8718,
158
- "sha256": "f8ed5f5dc27ffe0d610eb758a0094bcdc3af39512d1ee824852872eeaf185245"
157
+ "size": 8911,
158
+ "sha256": "94c80b52b28e6e67c7b159796ade26d88248449bb777c1663f50c6c6040c0701"
159
159
  },
160
160
  "ResourceMonitor.d.ts": {
161
161
  "size": 4019,
@@ -178,8 +178,8 @@
178
178
  "sha256": "3869f960c87260588e40941ff91bffcfa0757be7a04815fd28b57dd4840c51df"
179
179
  },
180
180
  "WorkerFactory.js": {
181
- "size": 107617,
182
- "sha256": "c15002aa229ddf992d2b302a8503f00ecddb78ec97d1afa38de6d9685b9c8b2b"
181
+ "size": 111089,
182
+ "sha256": "bf326ae52a4cd75ea806d8d43b6b882ecb2f89dafaf23d8fb25b07f7b04b2a00"
183
183
  },
184
184
  "WorkerInit.d.ts": {
185
185
  "size": 3284,
@@ -403,7 +403,7 @@
403
403
  },
404
404
  "index.js": {
405
405
  "size": 2336,
406
- "sha256": "14acafe485c1803f59b82252dc9c064c0f89d9ffd06a68bb7e76bff025fb7f0e"
406
+ "sha256": "01152020d6cee0945124019f07ed8bb41a0540aaf599633e26c5a629d6c40cf7"
407
407
  },
408
408
  "queueMonitorHistory.d.ts": {
409
409
  "size": 433,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zintrust/workers",
3
- "version": "1.5.2",
3
+ "version": "1.7.2",
4
4
  "description": "Worker orchestration and background job management for ZinTrust.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -85,6 +85,24 @@ const getAuditPrefix = (): string => {
85
85
  let redisClient: RedisConnection | null = null;
86
86
  let retentionPolicy: RetentionPolicy | null = null;
87
87
  let cleanupInterval: NodeJS.Timeout | null = null;
88
+ const REDIS_SHUTDOWN_TIMEOUT_MS = 100;
89
+
90
+ const closeRedisClient = async (client: RedisConnection): Promise<void> => {
91
+ try {
92
+ await Promise.race([
93
+ client.quit(),
94
+ new Promise<never>((_, reject) => {
95
+ const timeoutId = globalThis.setTimeout(() => {
96
+ reject(new Error('DeadLetterQueue Redis shutdown timed out'));
97
+ }, REDIS_SHUTDOWN_TIMEOUT_MS);
98
+ (timeoutId as { unref?: () => void }).unref?.();
99
+ }),
100
+ ]);
101
+ } catch (error) {
102
+ Logger.warn('DeadLetterQueue graceful Redis shutdown failed, forcing disconnect', error);
103
+ client.disconnect();
104
+ }
105
+ };
88
106
 
89
107
  /**
90
108
  * Helper: Get DLQ key
@@ -195,11 +213,11 @@ const cleanupOldEntries = async (): Promise<number> => {
195
213
  const keys = await client.keys(pattern);
196
214
 
197
215
  const cleanedCounts = await Promise.all(
198
- (keys as string[]).map(async (key: string) => {
216
+ keys.map(async (key: string) => {
199
217
  const oldEntries = await client.zrangebyscore(key, '-inf', cutoffTimestamp);
200
218
 
201
219
  await Promise.all(
202
- (oldEntries as string[]).map(async (entryJson: string) => {
220
+ oldEntries.map(async (entryJson: string) => {
203
221
  const entry = JSON.parse(entryJson) as FailedJobEntry;
204
222
 
205
223
  if (policy.anonymizeInsteadOfDelete) {
@@ -345,7 +363,7 @@ export const DeadLetterQueue = Object.freeze({
345
363
  const key = getDLQKey(queueName);
346
364
  const entries = await redisClient.zrange(key, 0, -1);
347
365
 
348
- const entry = (entries as string[])
366
+ const entry = entries
349
367
  .map((e: string) => JSON.parse(e) as FailedJobEntry)
350
368
  .find((e: FailedJobEntry) => e.id === jobId);
351
369
 
@@ -392,7 +410,7 @@ export const DeadLetterQueue = Object.freeze({
392
410
  // Get most recent failures first (highest scores)
393
411
  const entries = await redisClient.zrevrange(key, 0, limit - 1);
394
412
 
395
- return (entries as string[]).map((e: string) => JSON.parse(e) as FailedJobEntry);
413
+ return entries.map((e: string) => JSON.parse(e) as FailedJobEntry);
396
414
  } catch (error) {
397
415
  Logger.error(`Failed to get DLQ entries for queue: ${queueName}`, error);
398
416
  return [];
@@ -579,7 +597,7 @@ export const DeadLetterQueue = Object.freeze({
579
597
  const auditKey = getAuditKey(failedJobId);
580
598
  const entries = await redisClient.zrevrange(auditKey, 0, limit - 1);
581
599
 
582
- return (entries as string[]).map((e: string) => JSON.parse(e) as ComplianceAuditEntry);
600
+ return entries.map((e: string) => JSON.parse(e) as ComplianceAuditEntry);
583
601
  } catch (error) {
584
602
  Logger.error(`Failed to get audit log for: ${failedJobId}`, error);
585
603
  return [];
@@ -600,13 +618,13 @@ export const DeadLetterQueue = Object.freeze({
600
618
  const keys = await client.keys(pattern);
601
619
 
602
620
  const entriesByQueue = await Promise.all(
603
- (keys as string[]).map(async (key: string) => {
621
+ keys.map(async (key: string) => {
604
622
  const queueName = key.replace(getDLQPrefix(), '');
605
623
  const entries = await client.zrange(key, 0, -1);
606
624
  return {
607
625
  queueName,
608
626
  count: entries.length,
609
- entries: (entries as string[]).map((e: string) => JSON.parse(e) as FailedJobEntry),
627
+ entries: entries.map((e: string) => JSON.parse(e) as FailedJobEntry),
610
628
  };
611
629
  })
612
630
  );
@@ -729,7 +747,7 @@ export const DeadLetterQueue = Object.freeze({
729
747
  }
730
748
 
731
749
  if (redisClient) {
732
- await redisClient.quit();
750
+ await closeRedisClient(redisClient);
733
751
  redisClient = null;
734
752
  }
735
753
 
@@ -4,7 +4,7 @@
4
4
  * Sealed namespace for immutability
5
5
  */
6
6
 
7
- import { ErrorFactory, Logger } from '@zintrust/core';
7
+ import { ErrorFactory, Logger, ShutdownTrace } from '@zintrust/core';
8
8
  import { Worker, type Job, type WorkerOptions } from 'bullmq';
9
9
  import { PriorityQueue } from './PriorityQueue';
10
10
 
@@ -79,6 +79,14 @@ const createQueueWorker = async (
79
79
  workerOptions
80
80
  );
81
81
 
82
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.create', worker, {
83
+ workerName,
84
+ queueName: queueConfig.name,
85
+ configuredConcurrency: queueConfig.concurrency,
86
+ configuredPriority: queueConfig.priority,
87
+ enabled: queueConfig.enabled,
88
+ });
89
+
82
90
  // Set up event listeners
83
91
  worker.on('completed', (job: Job) => {
84
92
  const stats = multiQueueWorkers.get(workerName)?.stats.get(queueConfig.name);
@@ -407,7 +415,17 @@ export const MultiQueueWorker = Object.freeze({
407
415
  }
408
416
 
409
417
  // Close all workers
410
- const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
418
+ const closePromises = Array.from(mqw.workers.entries()).map(async ([queueName, worker]) => {
419
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.remove.close.start', worker, {
420
+ workerName,
421
+ queueName,
422
+ });
423
+ await worker.close(true);
424
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.remove.close.complete', worker, {
425
+ workerName,
426
+ queueName,
427
+ });
428
+ });
411
429
 
412
430
  await Promise.all(closePromises);
413
431
 
@@ -421,9 +439,22 @@ export const MultiQueueWorker = Object.freeze({
421
439
  */
422
440
  async shutdown(): Promise<void> {
423
441
  Logger.info('MultiQueueWorker shutting down...');
442
+ ShutdownTrace.logHandles('multi-queue-worker.shutdown.start', {
443
+ workerGroupCount: multiQueueWorkers.size,
444
+ });
424
445
 
425
446
  const shutdownPromises = Array.from(multiQueueWorkers.values()).map(async (mqw) => {
426
- const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
447
+ const closePromises = Array.from(mqw.workers.entries()).map(async ([queueName, worker]) => {
448
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.shutdown.close.start', worker, {
449
+ workerName: mqw.config.workerName,
450
+ queueName,
451
+ });
452
+ await worker.close(true);
453
+ ShutdownTrace.logBullMQWorker('multi-queue-worker.shutdown.close.complete', worker, {
454
+ workerName: mqw.config.workerName,
455
+ queueName,
456
+ });
457
+ });
427
458
  await Promise.all(closePromises);
428
459
  });
429
460
 
@@ -432,6 +463,7 @@ export const MultiQueueWorker = Object.freeze({
432
463
  multiQueueWorkers.clear();
433
464
 
434
465
  Logger.info('MultiQueueWorker shutdown complete');
466
+ ShutdownTrace.logHandles('multi-queue-worker.shutdown.complete');
435
467
  },
436
468
  });
437
469
 
@@ -62,7 +62,7 @@ const loadQueueRedisModule = async (): Promise<QueueRedisModule | undefined> =>
62
62
  if (queueRedisModule) return queueRedisModule;
63
63
 
64
64
  try {
65
- queueRedisModule = (await import('@zintrust/queue-redis')) as QueueRedisModule;
65
+ queueRedisModule = await import('@zintrust/queue-redis');
66
66
  return queueRedisModule;
67
67
  } catch (error) {
68
68
  if (!hasWarnedMissingQueueRedis) {
@@ -86,7 +86,7 @@ const getQueue = async (queueName: string): Promise<Queue> => {
86
86
  'Optional package "@zintrust/queue-redis" is required for PriorityQueue. Install it to use queue features.'
87
87
  );
88
88
  }
89
- return queueRedis.BullMQRedisQueue.getQueue(queueName) as Queue;
89
+ return queueRedis.BullMQRedisQueue.getQueue(queueName) as unknown as Queue;
90
90
  };
91
91
 
92
92
  /**
@@ -378,8 +378,17 @@ export const PriorityQueue = Object.freeze({
378
378
  */
379
379
  async shutdown(): Promise<void> {
380
380
  Logger.info('PriorityQueue shutting down via BullMQRedisQueue...');
381
+ if (!queueRedisModule) {
382
+ Logger.info('PriorityQueue shutdown complete');
383
+ return;
384
+ }
385
+
381
386
  const queueRedis = await loadQueueRedisModule();
382
- if (!queueRedis) return;
387
+ if (!queueRedis) {
388
+ Logger.info('PriorityQueue shutdown complete');
389
+ return;
390
+ }
391
+
383
392
  await queueRedis.BullMQRedisQueue.shutdown();
384
393
  Logger.info('PriorityQueue shutdown complete');
385
394
  },
@@ -58,6 +58,27 @@ import {
58
58
 
59
59
  const path = NodeSingletons.path;
60
60
 
61
+ type ShutdownTraceApi = {
62
+ log: (label: string, details?: Record<string, unknown>) => void;
63
+ logHandles: (label: string, details?: Record<string, unknown>) => void;
64
+ };
65
+
66
+ const createNoopShutdownTrace = (): ShutdownTraceApi => ({
67
+ log: (): void => undefined,
68
+ logHandles: (): void => undefined,
69
+ });
70
+
71
+ const resolveShutdownTrace = (): ShutdownTraceApi => {
72
+ try {
73
+ const candidate = (ZintrustCoreModule as { ShutdownTrace?: ShutdownTraceApi }).ShutdownTrace;
74
+ return candidate ?? createNoopShutdownTrace();
75
+ } catch {
76
+ return createNoopShutdownTrace();
77
+ }
78
+ };
79
+
80
+ const ShutdownTrace = resolveShutdownTrace();
81
+
61
82
  type ProcessorPackageBridgeGlobal = typeof globalThis & {
62
83
  __zintrustProcessorPackageBridges__?: Map<string, Record<string, unknown>>;
63
84
  };
@@ -451,6 +472,82 @@ let workerStore: WorkerStore = InMemoryWorkerStore.create();
451
472
  let workerStoreConfigured = false;
452
473
  let workerStoreConfig: WorkerPersistenceConfig | null = null;
453
474
 
475
+ const collectWorkerStoresForCleanup = (stores: Iterable<WorkerStore> = []): Set<WorkerStore> => {
476
+ const storesToClose = new Set<WorkerStore>(stores);
477
+
478
+ if (workerStoreConfigured) {
479
+ storesToClose.add(workerStore);
480
+ }
481
+
482
+ for (const store of storeInstanceCache.values()) {
483
+ storesToClose.add(store);
484
+ }
485
+
486
+ return storesToClose;
487
+ };
488
+
489
+ const closeWorkerStores = async (stores: Iterable<WorkerStore> = []): Promise<void> => {
490
+ const storesToClose = collectWorkerStoresForCleanup(stores);
491
+
492
+ ShutdownTrace.logHandles('worker-factory.store-cleanup.start', {
493
+ storeCount: storesToClose.size,
494
+ storeTypes: Array.from(storesToClose).map((store) => store.constructor.name),
495
+ });
496
+
497
+ await Promise.all(
498
+ Array.from(storesToClose).map(async (store) => {
499
+ if (typeof store.close !== 'function') return;
500
+
501
+ await shutdownWithTimeout(
502
+ 'WorkerStore',
503
+ async () => {
504
+ await store.close?.();
505
+ },
506
+ 100
507
+ );
508
+ })
509
+ );
510
+
511
+ workerStoreConfigured = false;
512
+ workerStoreConfig = null;
513
+ workerStore = InMemoryWorkerStore.create();
514
+ storeInstanceCache.clear();
515
+ ShutdownTrace.logHandles('worker-factory.store-cleanup.complete');
516
+ };
517
+
518
+ const shutdownWithTimeout = async (
519
+ label: string,
520
+ action: () => Promise<void>,
521
+ timeoutMs = 150
522
+ ): Promise<void> => {
523
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
524
+
525
+ try {
526
+ ShutdownTrace.log('worker-factory.step.start', { label, timeoutMs });
527
+ await Promise.race([
528
+ action(),
529
+ new Promise<never>((_, reject) => {
530
+ timeoutId = globalThis.setTimeout(() => {
531
+ reject(ErrorFactory.createGeneralError(`${label} shutdown timed out`, { timeoutMs }));
532
+ }, timeoutMs);
533
+ (timeoutId as { unref?: () => void }).unref?.();
534
+ }),
535
+ ]);
536
+ ShutdownTrace.logHandles('worker-factory.step.complete', { label, timeoutMs });
537
+ } catch (error) {
538
+ Logger.warn(`${label} shutdown failed or timed out`, error as Error);
539
+ ShutdownTrace.logHandles('worker-factory.step.failed', {
540
+ label,
541
+ timeoutMs,
542
+ error: error instanceof Error ? error.message : String(error),
543
+ });
544
+ } finally {
545
+ if (timeoutId !== undefined) {
546
+ globalThis.clearTimeout(timeoutId);
547
+ }
548
+ }
549
+ };
550
+
454
551
  export type ProcessorResolver = (
455
552
  name: string
456
553
  ) =>
@@ -3583,6 +3680,9 @@ export const WorkerFactory = Object.freeze({
3583
3680
  */
3584
3681
  async shutdown(): Promise<void> {
3585
3682
  Logger.info('WorkerFactory shutting down...');
3683
+ ShutdownTrace.logHandles('worker-factory.shutdown.start', {
3684
+ workerCount: workers.size,
3685
+ });
3586
3686
 
3587
3687
  const workerEntries = Array.from(workers.entries());
3588
3688
  const workerNames = workerEntries.map(([name]) => name);
@@ -3628,24 +3728,47 @@ export const WorkerFactory = Object.freeze({
3628
3728
 
3629
3729
  // Shutdown all modules
3630
3730
  ResourceMonitor.stop();
3631
- await WorkerMetrics.shutdown();
3632
- await MultiQueueWorker.shutdown();
3633
- await ComplianceManager.shutdown();
3634
- await PriorityQueue.shutdown();
3635
3731
  HealthMonitor.shutdown();
3636
3732
  AutoScaler.stop();
3637
- ClusterLock.shutdown();
3638
3733
  WorkerVersioning.shutdown();
3639
3734
  CanaryController.shutdown();
3640
3735
  DatacenterOrchestrator.shutdown();
3641
- PluginManager.shutdown();
3642
3736
  Observability.shutdown();
3643
- await DeadLetterQueue.shutdown();
3644
3737
  CircuitBreaker.shutdown();
3645
3738
 
3739
+ await Promise.all([
3740
+ shutdownWithTimeout('WorkerMetrics', async () => {
3741
+ await WorkerMetrics.shutdown();
3742
+ }),
3743
+ shutdownWithTimeout('MultiQueueWorker', async () => {
3744
+ await MultiQueueWorker.shutdown();
3745
+ }),
3746
+ shutdownWithTimeout('ComplianceManager', async () => {
3747
+ await ComplianceManager.shutdown();
3748
+ }),
3749
+ shutdownWithTimeout('PriorityQueue', async () => {
3750
+ await PriorityQueue.shutdown();
3751
+ }),
3752
+ shutdownWithTimeout('ClusterLock', async () => {
3753
+ await ClusterLock.shutdown();
3754
+ }),
3755
+ shutdownWithTimeout('PluginManager', async () => {
3756
+ await PluginManager.shutdown();
3757
+ }),
3758
+ shutdownWithTimeout('DeadLetterQueue', async () => {
3759
+ await DeadLetterQueue.shutdown();
3760
+ }),
3761
+ closeWorkerStores(storeGroups.keys()),
3762
+ ]);
3763
+
3764
+ ShutdownTrace.logHandles('worker-factory.shutdown.after-parallel-teardown', {
3765
+ workerCount: workers.size,
3766
+ });
3767
+
3646
3768
  workers.clear();
3647
3769
 
3648
3770
  Logger.info('WorkerFactory shutdown complete');
3771
+ ShutdownTrace.logHandles('worker-factory.shutdown.complete');
3649
3772
  },
3650
3773
 
3651
3774
  /**
@@ -3653,9 +3776,7 @@ export const WorkerFactory = Object.freeze({
3653
3776
  * Useful when connections become stale in long-running processes or serverless environments.
3654
3777
  */
3655
3778
  async resetPersistence(): Promise<void> {
3656
- workerStoreConfigured = false;
3657
- workerStore = InMemoryWorkerStore.create();
3658
- storeInstanceCache.clear();
3779
+ await closeWorkerStores();
3659
3780
  Logger.info('Worker persistence configuration reset');
3660
3781
  },
3661
3782
  });