@zintrust/workers 2.0.1 → 2.0.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.
@@ -35,10 +35,14 @@ const verifyWorkerHealth = async (worker) => {
35
35
  const isRunning = await worker.isRunning();
36
36
  if (!isRunning)
37
37
  return false;
38
- const client = await worker.client;
39
- const redisInfo = await client.info();
40
- if (redisInfo.trim() === '') {
41
- throw ErrorFactory.createWorkerError('Redis info command returned empty response');
38
+ const client = (await worker.client);
39
+ const ping = client.ping;
40
+ if (typeof ping !== 'function') {
41
+ throw ErrorFactory.createWorkerError('Redis ping command is not available');
42
+ }
43
+ const pingResult = await ping.call(client);
44
+ if (typeof pingResult === 'string' && pingResult.trim() === '') {
45
+ throw ErrorFactory.createWorkerError('Redis ping command returned empty response');
42
46
  }
43
47
  return true;
44
48
  };
@@ -252,7 +256,7 @@ const getCurrentHealth = (name) => {
252
256
  const state = registry.get(name);
253
257
  if (!state || state.history.length === 0)
254
258
  return null;
255
- return state.history[state.history.length - 1];
259
+ return state.history.at(-1) ?? null;
256
260
  };
257
261
  const getHealthHistory = (name, limit) => {
258
262
  const state = registry.get(name);
@@ -4,10 +4,9 @@
4
4
  * Sealed namespace for immutability
5
5
  */
6
6
  import * as ZintrustCoreModule from '@zintrust/core';
7
- import { Env, ErrorFactory, generateUuid, getBullMQSafeQueueName, isFunction, isNonEmptyString, isObject, Logger, NodeSingletons, useEnsureDbConnected, ZintrustLang, } from '@zintrust/core';
7
+ import { Env, ErrorFactory, generateUuid, getBullMQSafeQueueName, isFunction, isNonEmptyString, isObject, JobStateTracker, Logger, NodeSingletons, useEnsureDbConnected, ZintrustLang, } from '@zintrust/core';
8
8
  import { Cloudflare, createRedisConnection, databaseConfig, queueConfig, workersConfig, } from '@zintrust/core/config';
9
9
  import { DatabaseConnectionRegistry, registerDatabasesFromRuntimeConfig } from '@zintrust/core/orm';
10
- import { JobStateTracker } from '@zintrust/core/tools/queue';
11
10
  import { Worker } from 'bullmq';
12
11
  import { AutoScaler } from './AutoScaler.js';
13
12
  import { CanaryController } from './CanaryController.js';
@@ -838,16 +837,20 @@ const waitForWorkerConnection = async (worker, name, _queueName, timeoutMs) => {
838
837
  throw ErrorFactory.createWorkerError('Worker not running');
839
838
  }
840
839
  // Check Redis connection
841
- const client = await worker.client;
842
- const redisInfo = await client.info();
843
- if (redisInfo.trim() === '') {
844
- throw ErrorFactory.createWorkerError('Redis info command returned empty response');
840
+ const client = (await worker.client);
841
+ const ping = client.ping;
842
+ if (typeof ping !== 'function') {
843
+ throw ErrorFactory.createWorkerError('Redis ping command is not available');
844
+ }
845
+ const pingResult = await ping.call(client);
846
+ if (typeof pingResult === 'string' && pingResult.trim() === '') {
847
+ throw ErrorFactory.createWorkerError('Redis ping command returned empty response');
845
848
  }
846
849
  // Removed heavy Queue instantiation loop - relying on Redis ping for connectivity check
847
850
  // The queue instance creation was causing memory pressure and potential connection leaks in this retry loop
848
851
  Logger.debug(`Worker health verification passed for ${name}`, {
849
852
  isRunning,
850
- redisInfoLength: redisInfo.length,
853
+ redisInfoLength: typeof pingResult === 'string' ? pingResult.length : 0,
851
854
  });
852
855
  if (timeoutId)
853
856
  clearTimeout(timeoutId);
@@ -44,13 +44,7 @@ async function fetchPersistenceWithTimeout(page, limit, query) {
44
44
  }
45
45
  }
46
46
  async function fetchQueueDataSafe() {
47
- const defaultData = {
48
- driver: 'memory',
49
- totalQueues: 0,
50
- totalJobs: 0,
51
- processingJobs: 0,
52
- failedJobs: 0,
53
- };
47
+ const defaultData = buildEmptyQueueData(resolveConfiguredQueueDriver());
54
48
  try {
55
49
  return await withTimeout(getQueueData(), 3000, 'Queue data timeout');
56
50
  }
@@ -276,6 +270,21 @@ const normalizeDriver = (driver) => {
276
270
  return 'redis';
277
271
  return 'memory';
278
272
  };
273
+ const normalizeQueueDriver = (driver) => {
274
+ return normalizeDriver(driver);
275
+ };
276
+ const resolveConfiguredQueueDriver = () => {
277
+ return normalizeQueueDriver(Env.get('QUEUE_DRIVER', 'redis'));
278
+ };
279
+ const buildEmptyQueueData = (driver) => {
280
+ return {
281
+ driver,
282
+ totalQueues: 0,
283
+ totalJobs: 0,
284
+ processingJobs: 0,
285
+ failedJobs: 0,
286
+ };
287
+ };
279
288
  const getAvailableDriversFromDrivers = (drivers) => {
280
289
  const uniqueDrivers = new Set(drivers);
281
290
  return Array.from(uniqueDrivers);
@@ -433,7 +442,7 @@ function applySorting(workers, sortBy, sortOrder = 'asc') {
433
442
  });
434
443
  }
435
444
  async function getQueueData() {
436
- const queueDriver = Env.get('QUEUE_DRIVER', 'redis');
445
+ const queueDriver = resolveConfiguredQueueDriver();
437
446
  try {
438
447
  // Get queue statistics based on QUEUE_DRIVER
439
448
  switch (queueDriver) {
@@ -441,15 +450,13 @@ async function getQueueData() {
441
450
  return await getRedisQueueData();
442
451
  case 'database':
443
452
  return await getDatabaseQueueData();
444
- case 'db':
445
- return await getDatabaseQueueData();
446
453
  default:
447
454
  return await getMemoryQueueData();
448
455
  }
449
456
  }
450
457
  catch (error) {
451
458
  Logger.error('Error fetching queue data:', error);
452
- return await getMemoryQueueData();
459
+ return buildEmptyQueueData(queueDriver);
453
460
  }
454
461
  }
455
462
  async function getRedisQueueData() {
@@ -552,13 +559,7 @@ async function getMemoryQueueData() {
552
559
  // access the actual queue registry from the queue system
553
560
  // Since memory queues don't persist, we return basic info
554
561
  // In a real implementation, you'd track active memory queues
555
- return {
556
- driver: 'memory',
557
- totalQueues: 0, // Memory queues are not persisted
558
- totalJobs: 0,
559
- processingJobs: 0,
560
- failedJobs: 0,
561
- };
562
+ return buildEmptyQueueData('memory');
562
563
  }
563
564
  const createWorkerMetricRequests = (workers, startDate, endDate) => {
564
565
  return workers.flatMap((worker) => [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zintrust/workers",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Worker orchestration and background job management for ZinTrust.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -85,11 +85,21 @@ const verifyWorkerHealth = async (worker: Worker): Promise<boolean> => {
85
85
  const isRunning = await worker.isRunning();
86
86
  if (!isRunning) return false;
87
87
 
88
- const client = await worker.client;
89
- const redisInfo = await client.info();
90
- if (redisInfo.trim() === '') {
91
- throw ErrorFactory.createWorkerError('Redis info command returned empty response');
88
+ const client = (await worker.client) as unknown as {
89
+ ping?: () => Promise<string> | Promise<unknown>;
90
+ };
91
+ const ping = client.ping;
92
+
93
+ if (typeof ping !== 'function') {
94
+ throw ErrorFactory.createWorkerError('Redis ping command is not available');
95
+ }
96
+
97
+ const pingResult = await ping.call(client);
98
+
99
+ if (typeof pingResult === 'string' && pingResult.trim() === '') {
100
+ throw ErrorFactory.createWorkerError('Redis ping command returned empty response');
92
101
  }
102
+
93
103
  return true;
94
104
  };
95
105
 
@@ -337,7 +347,7 @@ const updateConfig = (name: string, monitorConfig: WorkerMonitorConfig): void =>
337
347
  const getCurrentHealth = (name: string): HealthCheckResult | null => {
338
348
  const state = registry.get(name);
339
349
  if (!state || state.history.length === 0) return null;
340
- return state.history[state.history.length - 1];
350
+ return state.history.at(-1) ?? null;
341
351
  };
342
352
 
343
353
  const getHealthHistory = (name: string, limit?: number): HealthCheckResult[] => {
@@ -13,6 +13,7 @@ import {
13
13
  isFunction,
14
14
  isNonEmptyString,
15
15
  isObject,
16
+ JobStateTracker,
16
17
  Logger,
17
18
  NodeSingletons,
18
19
  useEnsureDbConnected,
@@ -29,7 +30,6 @@ import {
29
30
  type RedisConfig,
30
31
  } from '@zintrust/core/config';
31
32
  import { DatabaseConnectionRegistry, registerDatabasesFromRuntimeConfig } from '@zintrust/core/orm';
32
- import { JobStateTracker } from '@zintrust/core/tools/queue';
33
33
  import { Worker, type Job, type WorkerOptions } from 'bullmq';
34
34
  import { AutoScaler, type AutoScalerConfig } from './AutoScaler';
35
35
  import { CanaryController } from './CanaryController';
@@ -100,7 +100,7 @@ const canUseProjectFileImports = (): boolean =>
100
100
  typeof NodeSingletons?.path?.join === 'function';
101
101
 
102
102
  const getProcessorPackageBridgeGlobal = (): ProcessorPackageBridgeGlobal => {
103
- return globalThis as ProcessorPackageBridgeGlobal;
103
+ return globalThis;
104
104
  };
105
105
 
106
106
  const isValidBridgeExportName = (value: string): boolean => {
@@ -109,7 +109,7 @@ const isValidBridgeExportName = (value: string): boolean => {
109
109
 
110
110
  const resolveRuntimeBridgeModule = (specifier: string): Record<string, unknown> | null => {
111
111
  if (specifier === '@zintrust/core') {
112
- return ZintrustCoreModule as Record<string, unknown>;
112
+ return ZintrustCoreModule;
113
113
  }
114
114
 
115
115
  return null;
@@ -1234,10 +1234,18 @@ const waitForWorkerConnection = async (
1234
1234
  }
1235
1235
 
1236
1236
  // Check Redis connection
1237
- const client = await worker.client;
1238
- const redisInfo = await client.info();
1239
- if (redisInfo.trim() === '') {
1240
- throw ErrorFactory.createWorkerError('Redis info command returned empty response');
1237
+ const client = (await worker.client) as unknown as {
1238
+ ping?: () => Promise<string> | Promise<unknown>;
1239
+ };
1240
+ const ping = client.ping;
1241
+
1242
+ if (typeof ping !== 'function') {
1243
+ throw ErrorFactory.createWorkerError('Redis ping command is not available');
1244
+ }
1245
+
1246
+ const pingResult = await ping.call(client);
1247
+ if (typeof pingResult === 'string' && pingResult.trim() === '') {
1248
+ throw ErrorFactory.createWorkerError('Redis ping command returned empty response');
1241
1249
  }
1242
1250
 
1243
1251
  // Removed heavy Queue instantiation loop - relying on Redis ping for connectivity check
@@ -1245,7 +1253,7 @@ const waitForWorkerConnection = async (
1245
1253
 
1246
1254
  Logger.debug(`Worker health verification passed for ${name}`, {
1247
1255
  isRunning,
1248
- redisInfoLength: redisInfo.length,
1256
+ redisInfoLength: typeof pingResult === 'string' ? pingResult.length : 0,
1249
1257
  });
1250
1258
 
1251
1259
  if (timeoutId) clearTimeout(timeoutId);
@@ -3144,7 +3152,7 @@ export const WorkerFactory = Object.freeze({
3144
3152
  );
3145
3153
  const errorMessage = typeof error === 'string' ? error : error?.message;
3146
3154
  await store.update(name, {
3147
- status: status as WorkerCreationStatus,
3155
+ status: status,
3148
3156
  updatedAt: new Date(),
3149
3157
  lastError: errorMessage,
3150
3158
  });
@@ -96,13 +96,7 @@ async function fetchPersistenceWithTimeout(
96
96
  }
97
97
 
98
98
  async function fetchQueueDataSafe(): Promise<QueueData> {
99
- const defaultData: QueueData = {
100
- driver: 'memory',
101
- totalQueues: 0,
102
- totalJobs: 0,
103
- processingJobs: 0,
104
- failedJobs: 0,
105
- };
99
+ const defaultData = buildEmptyQueueData(resolveConfiguredQueueDriver());
106
100
 
107
101
  try {
108
102
  return await withTimeout(getQueueData(), 3000, 'Queue data timeout');
@@ -392,6 +386,24 @@ const normalizeDriver = (driver: string): WorkerDriver => {
392
386
  return 'memory';
393
387
  };
394
388
 
389
+ const normalizeQueueDriver = (driver: string): WorkerDriver => {
390
+ return normalizeDriver(driver);
391
+ };
392
+
393
+ const resolveConfiguredQueueDriver = (): WorkerDriver => {
394
+ return normalizeQueueDriver(Env.get('QUEUE_DRIVER', 'redis'));
395
+ };
396
+
397
+ const buildEmptyQueueData = (driver: WorkerDriver): QueueData => {
398
+ return {
399
+ driver,
400
+ totalQueues: 0,
401
+ totalJobs: 0,
402
+ processingJobs: 0,
403
+ failedJobs: 0,
404
+ };
405
+ };
406
+
395
407
  const getAvailableDriversFromDrivers = (drivers: WorkerDriver[]): WorkerDriver[] => {
396
408
  const uniqueDrivers = new Set(drivers);
397
409
  return Array.from(uniqueDrivers);
@@ -577,7 +589,7 @@ function applySorting(
577
589
  }
578
590
 
579
591
  async function getQueueData(): Promise<QueueData> {
580
- const queueDriver = Env.get('QUEUE_DRIVER', 'redis');
592
+ const queueDriver = resolveConfiguredQueueDriver();
581
593
 
582
594
  try {
583
595
  // Get queue statistics based on QUEUE_DRIVER
@@ -586,14 +598,12 @@ async function getQueueData(): Promise<QueueData> {
586
598
  return await getRedisQueueData();
587
599
  case 'database':
588
600
  return await getDatabaseQueueData();
589
- case 'db':
590
- return await getDatabaseQueueData();
591
601
  default:
592
602
  return await getMemoryQueueData();
593
603
  }
594
604
  } catch (error) {
595
605
  Logger.error('Error fetching queue data:', error);
596
- return await getMemoryQueueData();
606
+ return buildEmptyQueueData(queueDriver);
597
607
  }
598
608
  }
599
609
 
@@ -717,13 +727,7 @@ async function getMemoryQueueData(): Promise<QueueData> {
717
727
  // access the actual queue registry from the queue system
718
728
  // Since memory queues don't persist, we return basic info
719
729
  // In a real implementation, you'd track active memory queues
720
- return {
721
- driver: 'memory',
722
- totalQueues: 0, // Memory queues are not persisted
723
- totalJobs: 0,
724
- processingJobs: 0,
725
- failedJobs: 0,
726
- };
730
+ return buildEmptyQueueData('memory');
727
731
  }
728
732
 
729
733
  const createWorkerMetricRequests = (
@@ -1,12 +0,0 @@
1
- type DurableObjectState = {
2
- storage: {
3
- get: (key: string) => Promise<unknown>;
4
- put: (key: string, value: unknown) => Promise<void>;
5
- };
6
- };
7
- export declare class ZinTrustWorkerShutdownDurableObject {
8
- private readonly state;
9
- constructor(state: DurableObjectState);
10
- fetch(request: Request): Promise<Response>;
11
- }
12
- export {};
@@ -1,41 +0,0 @@
1
- import { Logger } from '@zintrust/core';
2
- const loadState = async (state) => {
3
- const stored = (await state.storage.get('shutdown'));
4
- return stored ?? { shuttingDown: false };
5
- };
6
- const saveState = async (state, value) => {
7
- await state.storage.put('shutdown', value);
8
- };
9
- // eslint-disable-next-line no-restricted-syntax
10
- export class ZinTrustWorkerShutdownDurableObject {
11
- state;
12
- constructor(state) {
13
- this.state = state;
14
- }
15
- async fetch(request) {
16
- const url = new URL(request.url);
17
- const path = url.pathname;
18
- if (request.method === 'GET' && path === '/status') {
19
- const current = await loadState(this.state);
20
- return new Response(JSON.stringify(current), {
21
- status: 200,
22
- headers: { 'content-type': 'application/json' },
23
- });
24
- }
25
- if (request.method === 'POST' && path === '/shutdown') {
26
- const payload = (await request.json().catch(() => ({})));
27
- const next = {
28
- shuttingDown: true,
29
- startedAt: new Date().toISOString(),
30
- reason: payload.reason ?? 'manual',
31
- };
32
- await saveState(this.state, next);
33
- Logger.info('Worker shutdown requested via Durable Object', next);
34
- return new Response(JSON.stringify({ ok: true }), {
35
- status: 202,
36
- headers: { 'content-type': 'application/json' },
37
- });
38
- }
39
- return new Response('Not Found', { status: 404 });
40
- }
41
- }