@zintrust/workers 2.0.1 → 2.0.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.
@@ -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);
@@ -1,4 +1,4 @@
1
- import { Env, ErrorFactory, Logger } from '@zintrust/core';
1
+ import { Env, ErrorFactory, Logger, queueConfig } from '@zintrust/core/runtime';
2
2
  import { WorkerFactory } from '../WorkerFactory.js';
3
3
  import { WorkerMetrics as WorkerMetricsManager } from '../WorkerMetrics.js';
4
4
  import { WorkerRegistry } from '../WorkerRegistry.js';
@@ -44,15 +44,10 @@ 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
- return await withTimeout(getQueueData(), 3000, 'Queue data timeout');
49
+ const timeoutMs = queueConfig.monitor?.queueDataTimeoutMs ?? Env.getInt('QUEUE_DATA_TIMEOUT_MS', 10000);
50
+ return await withTimeout(getQueueData(), timeoutMs, 'Queue data timeout');
56
51
  }
57
52
  catch (err) {
58
53
  Logger.warn('[getWorkers] Queue data fetch failed or timed out', err);
@@ -276,6 +271,21 @@ const normalizeDriver = (driver) => {
276
271
  return 'redis';
277
272
  return 'memory';
278
273
  };
274
+ const normalizeQueueDriver = (driver) => {
275
+ return normalizeDriver(driver);
276
+ };
277
+ const resolveConfiguredQueueDriver = () => {
278
+ return normalizeQueueDriver(Env.get('QUEUE_DRIVER', 'redis'));
279
+ };
280
+ const buildEmptyQueueData = (driver) => {
281
+ return {
282
+ driver,
283
+ totalQueues: 0,
284
+ totalJobs: 0,
285
+ processingJobs: 0,
286
+ failedJobs: 0,
287
+ };
288
+ };
279
289
  const getAvailableDriversFromDrivers = (drivers) => {
280
290
  const uniqueDrivers = new Set(drivers);
281
291
  return Array.from(uniqueDrivers);
@@ -433,7 +443,7 @@ function applySorting(workers, sortBy, sortOrder = 'asc') {
433
443
  });
434
444
  }
435
445
  async function getQueueData() {
436
- const queueDriver = Env.get('QUEUE_DRIVER', 'redis');
446
+ const queueDriver = resolveConfiguredQueueDriver();
437
447
  try {
438
448
  // Get queue statistics based on QUEUE_DRIVER
439
449
  switch (queueDriver) {
@@ -441,22 +451,19 @@ async function getQueueData() {
441
451
  return await getRedisQueueData();
442
452
  case 'database':
443
453
  return await getDatabaseQueueData();
444
- case 'db':
445
- return await getDatabaseQueueData();
446
454
  default:
447
455
  return await getMemoryQueueData();
448
456
  }
449
457
  }
450
458
  catch (error) {
451
459
  Logger.error('Error fetching queue data:', error);
452
- return await getMemoryQueueData();
460
+ return buildEmptyQueueData(queueDriver);
453
461
  }
454
462
  }
455
463
  async function getRedisQueueData() {
456
464
  try {
457
465
  // Use existing queue monitor infrastructure
458
466
  const { QueueMonitor } = await import('@zintrust/queue-monitor');
459
- const { queueConfig } = await import('@zintrust/core');
460
467
  const redisConfig = queueConfig.drivers.redis;
461
468
  if (redisConfig?.driver !== 'redis') {
462
469
  throw ErrorFactory.createConfigError('Redis driver not configured');
@@ -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.3",
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
  });
@@ -1,4 +1,4 @@
1
- import { Env, ErrorFactory, Logger } from '@zintrust/core';
1
+ import { Env, ErrorFactory, Logger, queueConfig } from '@zintrust/core/runtime';
2
2
  import { WorkerFactory } from '../WorkerFactory';
3
3
  import { WorkerMetrics as WorkerMetricsManager } from '../WorkerMetrics';
4
4
  import { WorkerRegistry } from '../WorkerRegistry';
@@ -96,16 +96,12 @@ 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
- return await withTimeout(getQueueData(), 3000, 'Queue data timeout');
102
+ const timeoutMs =
103
+ queueConfig.monitor?.queueDataTimeoutMs ?? Env.getInt('QUEUE_DATA_TIMEOUT_MS', 10000);
104
+ return await withTimeout(getQueueData(), timeoutMs, 'Queue data timeout');
109
105
  } catch (err) {
110
106
  Logger.warn('[getWorkers] Queue data fetch failed or timed out', err);
111
107
  return defaultData;
@@ -392,6 +388,24 @@ const normalizeDriver = (driver: string): WorkerDriver => {
392
388
  return 'memory';
393
389
  };
394
390
 
391
+ const normalizeQueueDriver = (driver: string): WorkerDriver => {
392
+ return normalizeDriver(driver);
393
+ };
394
+
395
+ const resolveConfiguredQueueDriver = (): WorkerDriver => {
396
+ return normalizeQueueDriver(Env.get('QUEUE_DRIVER', 'redis'));
397
+ };
398
+
399
+ const buildEmptyQueueData = (driver: WorkerDriver): QueueData => {
400
+ return {
401
+ driver,
402
+ totalQueues: 0,
403
+ totalJobs: 0,
404
+ processingJobs: 0,
405
+ failedJobs: 0,
406
+ };
407
+ };
408
+
395
409
  const getAvailableDriversFromDrivers = (drivers: WorkerDriver[]): WorkerDriver[] => {
396
410
  const uniqueDrivers = new Set(drivers);
397
411
  return Array.from(uniqueDrivers);
@@ -451,7 +465,7 @@ const buildWorkerFromRaw = (workerData: RawWorkerData, driver: WorkerDriver): Wo
451
465
  autoStart: workerData.autoStart || false,
452
466
  activeStatus: workerData.activeStatus ?? true,
453
467
  details: workerData.details || {
454
- configuration: {} as WorkerConfiguration,
468
+ configuration: {},
455
469
  health: {} as WorkerHealth,
456
470
  metrics: {} as WorkerMetrics,
457
471
  recentLogs: [],
@@ -577,7 +591,7 @@ function applySorting(
577
591
  }
578
592
 
579
593
  async function getQueueData(): Promise<QueueData> {
580
- const queueDriver = Env.get('QUEUE_DRIVER', 'redis');
594
+ const queueDriver = resolveConfiguredQueueDriver();
581
595
 
582
596
  try {
583
597
  // Get queue statistics based on QUEUE_DRIVER
@@ -586,14 +600,12 @@ async function getQueueData(): Promise<QueueData> {
586
600
  return await getRedisQueueData();
587
601
  case 'database':
588
602
  return await getDatabaseQueueData();
589
- case 'db':
590
- return await getDatabaseQueueData();
591
603
  default:
592
604
  return await getMemoryQueueData();
593
605
  }
594
606
  } catch (error) {
595
607
  Logger.error('Error fetching queue data:', error);
596
- return await getMemoryQueueData();
608
+ return buildEmptyQueueData(queueDriver);
597
609
  }
598
610
  }
599
611
 
@@ -601,7 +613,6 @@ async function getRedisQueueData(): Promise<QueueData> {
601
613
  try {
602
614
  // Use existing queue monitor infrastructure
603
615
  const { QueueMonitor } = await import('@zintrust/queue-monitor');
604
- const { queueConfig } = await import('@zintrust/core');
605
616
 
606
617
  const redisConfig = queueConfig.drivers.redis;
607
618
  if (redisConfig?.driver !== 'redis') {
@@ -717,13 +728,7 @@ async function getMemoryQueueData(): Promise<QueueData> {
717
728
  // access the actual queue registry from the queue system
718
729
  // Since memory queues don't persist, we return basic info
719
730
  // 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
- };
731
+ return buildEmptyQueueData('memory');
727
732
  }
728
733
 
729
734
  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
- }