@zintrust/workers 2.4.3 → 2.4.5

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.
@@ -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 { type Job } from 'bullmq';
6
+ import type { Job } from 'bullmq';
7
7
  export type QueueConfig = {
8
8
  name: string;
9
9
  concurrency: number;
@@ -6,8 +6,13 @@
6
6
  import { ErrorFactory } from '@zintrust/core/errors';
7
7
  import { Logger } from '@zintrust/core/logger';
8
8
  import { ShutdownTrace } from '@zintrust/core/workers';
9
- import { Worker } from 'bullmq';
10
9
  import { PriorityQueue } from './PriorityQueue.js';
10
+ // Lazy BullMQ Worker loader keyed on a variable specifier so bundlers do not inline
11
+ // bullmq into the Workers bundle. Worker creation is consumer-side (Node).
12
+ const loadBullmqWorker = async () => {
13
+ const bullmqPkg = 'bullmq';
14
+ return (await import(bullmqPkg)).Worker;
15
+ };
11
16
  // Internal state
12
17
  const multiQueueWorkers = new Map();
13
18
  /**
@@ -23,7 +28,8 @@ const createQueueWorker = async (workerName, queueConfig, processor) => {
23
28
  autorun: queueConfig.enabled,
24
29
  prefix: queue.opts.prefix,
25
30
  };
26
- const worker = new Worker(queueConfig.name, async (job) => {
31
+ const WorkerCtor = await loadBullmqWorker();
32
+ const worker = new WorkerCtor(queueConfig.name, async (job) => {
27
33
  Logger.debug(`Processing job from queue: ${queueConfig.name}`, {
28
34
  jobId: job.id,
29
35
  workerName,
@@ -57,8 +57,13 @@ let datadogClient = null;
57
57
  * Helper: Lazy load Prometheus client
58
58
  */
59
59
  const getPrometheusClient = async () => {
60
- promClient ??= await import('prom-client');
61
- return promClient;
60
+ if (promClient !== null)
61
+ return promClient;
62
+ // Variable specifier so bundlers do not inline prom-client into the Workers bundle.
63
+ const promClientPkg = 'prom-client';
64
+ const loaded = await import(promClientPkg);
65
+ promClient = loaded;
66
+ return loaded;
62
67
  };
63
68
  /**
64
69
  * Helper: Lazy load OpenTelemetry API
@@ -117,7 +122,9 @@ const initDatadog = async (ddConfig) => {
117
122
  if (!ddConfig.enabled)
118
123
  return;
119
124
  try {
120
- const module = (await import('hot-shots'));
125
+ // Variable specifier so bundlers do not inline hot-shots (StatsD/UDP) into the Workers bundle.
126
+ const hotShotsPkg = 'hot-shots';
127
+ const module = (await import(hotShotsPkg));
121
128
  const StatsDClass = module.StatsD;
122
129
  if (!StatsDClass) {
123
130
  Logger.warn('Datadog StatsD client unavailable');
@@ -82,6 +82,11 @@ export type ISLAReport = {
82
82
  complianceRate: number;
83
83
  }>;
84
84
  };
85
+ export type ISLAGate = {
86
+ allowed: boolean;
87
+ reason?: string;
88
+ status?: ISLAStatus;
89
+ };
85
90
  /**
86
91
  * SLA Monitor - Sealed namespace
87
92
  */
@@ -90,10 +95,13 @@ export declare const SLAMonitor: Readonly<{
90
95
  * Define SLA for a worker
91
96
  */
92
97
  defineSLA(config: ISLAConfig): void;
98
+ hasSLA(workerName: string): boolean;
99
+ isAnyConfigured(): boolean;
93
100
  /**
94
101
  * Check SLA compliance for a worker
95
102
  */
96
103
  checkCompliance(workerName: string): Promise<ISLAStatus>;
104
+ canSendWorkerRequest(workerName: string): Promise<ISLAGate>;
97
105
  /**
98
106
  * Get SLA violations for a worker
99
107
  */
@@ -175,6 +175,12 @@ export const SLAMonitor = Object.freeze({
175
175
  slaConfigs.set(config.workerName, { ...config });
176
176
  Logger.info(`SLA defined for worker "${config.workerName}"`);
177
177
  },
178
+ hasSLA(workerName) {
179
+ return slaConfigs.has(workerName);
180
+ },
181
+ isAnyConfigured() {
182
+ return slaConfigs.size > 0;
183
+ },
178
184
  /**
179
185
  * Check SLA compliance for a worker
180
186
  */
@@ -211,6 +217,20 @@ export const SLAMonitor = Object.freeze({
211
217
  checks,
212
218
  };
213
219
  },
220
+ async canSendWorkerRequest(workerName) {
221
+ if (!slaConfigs.has(workerName)) {
222
+ return { allowed: true, reason: 'sla_not_configured' };
223
+ }
224
+ const status = await SLAMonitor.checkCompliance(workerName);
225
+ if (status.status === 'compliant') {
226
+ return { allowed: true, status };
227
+ }
228
+ return {
229
+ allowed: false,
230
+ reason: `sla_${status.status}`,
231
+ status,
232
+ };
233
+ },
214
234
  /**
215
235
  * Get SLA violations for a worker
216
236
  */
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { type IDatabase } from '@zintrust/core/database';
7
7
  import { type RedisConfig } from '@zintrust/core/redis';
8
- import { Worker, type Job, type WorkerOptions } from 'bullmq';
8
+ import type { Job, Worker, WorkerOptions } from 'bullmq';
9
9
  import { type AutoScalerConfig } from './AutoScaler';
10
10
  import { type ComplianceConfig } from './ComplianceManager';
11
11
  import { type RetentionPolicy } from './DeadLetterQueue';
@@ -13,7 +13,6 @@ import { JobStateTracker } from '@zintrust/core/queue';
13
13
  import { createRedisConnection, getBullMQSafeQueueName, } from '@zintrust/core/redis';
14
14
  import { generateUuid, isFunction, isNonEmptyString, isObject, ZintrustLang, } from '@zintrust/core/utils';
15
15
  import { NodeSingletons } from '@zintrust/core/workers';
16
- import { Worker } from 'bullmq';
17
16
  import { AutoScaler } from './AutoScaler.js';
18
17
  import { CanaryController } from './CanaryController.js';
19
18
  import { CircuitBreaker } from './CircuitBreaker.js';
@@ -27,6 +26,7 @@ import { Observability } from './Observability.js';
27
26
  import { PluginManager } from './PluginManager.js';
28
27
  import { PriorityQueue } from './PriorityQueue.js';
29
28
  import { ResourceMonitor } from './ResourceMonitor.js';
29
+ import { SLAMonitor } from './SLAMonitor.js';
30
30
  import { WorkerMetrics } from './WorkerMetrics.js';
31
31
  import { WorkerRegistry } from './WorkerRegistry.js';
32
32
  import { WorkerVersioning } from './WorkerVersioning.js';
@@ -34,6 +34,12 @@ import { resolveWorkerKeyPrefix } from './config/workerConfig.js';
34
34
  import { recordQueueMonitorJob } from './queueMonitorHistory.js';
35
35
  import { DbWorkerStore, InMemoryWorkerStore, RedisWorkerStore, } from './storage/WorkerStore.js';
36
36
  const path = NodeSingletons.path;
37
+ // Lazy BullMQ Worker loader keyed on a variable specifier so bundlers do not inline
38
+ // bullmq into the Workers bundle. Worker creation is consumer-side (Node).
39
+ const loadBullmqWorker = async () => {
40
+ const bullmqPkg = 'bullmq';
41
+ return (await import(bullmqPkg)).Worker;
42
+ };
37
43
  const createNoopShutdownTrace = () => ({
38
44
  log: () => undefined,
39
45
  logHandles: () => undefined,
@@ -1803,6 +1809,17 @@ const buildWorkerRecord = (config, status) => {
1803
1809
  connectionState: undefined,
1804
1810
  };
1805
1811
  };
1812
+ const assertSlaAllowsWorkerRequest = async (workerName) => {
1813
+ const gate = await SLAMonitor.canSendWorkerRequest(workerName);
1814
+ if (gate.allowed)
1815
+ return;
1816
+ throw ErrorFactory.createConfigError(`Worker "${workerName}" blocked because SLA status is not compliant`, {
1817
+ kind: 'worker_sla_blocked',
1818
+ workerName,
1819
+ reason: gate.reason,
1820
+ status: gate.status?.status,
1821
+ });
1822
+ };
1806
1823
  const buildDefaultAutoScalerConfig = () => ({
1807
1824
  enabled: workersConfig.autoScaling.enabled,
1808
1825
  checkInterval: workersConfig.autoScaling.interval,
@@ -2179,6 +2196,9 @@ export const WorkerFactory = Object.freeze({
2179
2196
  if (workers.has(name)) {
2180
2197
  throw ErrorFactory.createWorkerError(`Worker "${name}" already exists`);
2181
2198
  }
2199
+ if (autoStart) {
2200
+ await assertSlaAllowsWorkerRequest(name);
2201
+ }
2182
2202
  // Resolve the correct store for this worker configuration
2183
2203
  const store = await getStoreForWorker(config);
2184
2204
  // Save initial status as "creating"
@@ -2194,7 +2214,8 @@ export const WorkerFactory = Object.freeze({
2194
2214
  const enhancedProcessor = createEnhancedProcessor(config);
2195
2215
  // Create BullMQ worker
2196
2216
  const resolvedOptions = resolveWorkerOptions(config, autoStart);
2197
- const worker = new Worker(queueName, enhancedProcessor, resolvedOptions);
2217
+ const WorkerCtor = await loadBullmqWorker();
2218
+ const worker = new WorkerCtor(queueName, enhancedProcessor, resolvedOptions);
2198
2219
  setupWorkerEventListeners(worker, name, queueName, workerVersion, features);
2199
2220
  // Update status to "starting"
2200
2221
  await store.update(name, {
@@ -2514,6 +2535,7 @@ export const WorkerFactory = Object.freeze({
2514
2535
  if (persisted?.activeStatus === false) {
2515
2536
  throw ErrorFactory.createConfigError(`Worker "${name}" is inactive`);
2516
2537
  }
2538
+ await assertSlaAllowsWorkerRequest(name);
2517
2539
  const version = instance.config.version ?? '1.0.0';
2518
2540
  await WorkerRegistry.start(name, version);
2519
2541
  instance.status = WorkerCreationStatus.RUNNING;
@@ -2569,6 +2591,7 @@ export const WorkerFactory = Object.freeze({
2569
2591
  if (record.activeStatus === false) {
2570
2592
  throw ErrorFactory.createConfigError(`Worker "${name}" is inactive`);
2571
2593
  }
2594
+ await assertSlaAllowsWorkerRequest(name);
2572
2595
  let processor;
2573
2596
  try {
2574
2597
  processor = await resolveStartFromPersistedProcessor(name, record, discovered);
@@ -66,6 +66,9 @@ export interface WorkersListResponse {
66
66
  hasPrev: boolean;
67
67
  };
68
68
  drivers: WorkerDriver[];
69
+ features: {
70
+ sla: boolean;
71
+ };
69
72
  }
70
73
  export interface QueueData {
71
74
  driver: WorkerDriver;
@@ -0,0 +1,15 @@
1
+ export type WorkerManifestEntry = Readonly<{
2
+ name?: string;
3
+ workerName?: string;
4
+ queueName?: string;
5
+ processorSpec?: string | null;
6
+ concurrency?: number;
7
+ autoStart?: boolean;
8
+ activeStatus?: boolean;
9
+ status?: string;
10
+ }>;
11
+ export declare const readWorkerManifestGlobalKeys: () => string[];
12
+ export declare const getWorkerManifestEntries: () => WorkerManifestEntry[];
13
+ export declare const getWorkerManifestQueueNames: () => string[];
14
+ export declare const getWorkerManifestRecord: (workerName: string) => WorkerManifestEntry | undefined;
15
+ export declare const getWorkerManifestStatus: (workerName: string) => boolean;
@@ -0,0 +1,67 @@
1
+ import { Env } from '@zintrust/core/config';
2
+ const DEFAULT_WORKER_MANIFEST_GLOBAL_KEYS = Object.freeze([
3
+ '__zintrustWorkersManifest',
4
+ '__zintrustWorkerManifest',
5
+ '__zintrustAppWorkerManifest',
6
+ ]);
7
+ const normalizeKeyList = (values) => {
8
+ return Array.from(new Set(values.map((value) => value.trim()).filter((value) => value.length > 0)));
9
+ };
10
+ const readKeyListValue = (value) => {
11
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {
12
+ return undefined;
13
+ }
14
+ return normalizeKeyList(value);
15
+ };
16
+ export const readWorkerManifestGlobalKeys = () => {
17
+ const manifestGlobal = globalThis;
18
+ const runtimeKeys = readKeyListValue(manifestGlobal.workerManifestGlobalKeys) ??
19
+ readKeyListValue(manifestGlobal.__zintrustWorkerManifestGlobalKeys);
20
+ if (runtimeKeys && runtimeKeys.length > 0) {
21
+ return runtimeKeys;
22
+ }
23
+ const raw = Env.get('WORKER_MANIFEST_GLOBAL_KEYS', '').trim();
24
+ if (raw.length > 0) {
25
+ try {
26
+ const parsed = JSON.parse(raw);
27
+ const jsonKeys = readKeyListValue(parsed);
28
+ if (jsonKeys && jsonKeys.length > 0) {
29
+ return jsonKeys;
30
+ }
31
+ }
32
+ catch {
33
+ // fall through to CSV parsing
34
+ }
35
+ const csvKeys = normalizeKeyList(raw
36
+ .split(',')
37
+ .map((value) => value.trim())
38
+ .filter((value) => value.length > 0));
39
+ if (csvKeys.length > 0) {
40
+ return csvKeys;
41
+ }
42
+ }
43
+ return [...DEFAULT_WORKER_MANIFEST_GLOBAL_KEYS];
44
+ };
45
+ export const getWorkerManifestEntries = () => {
46
+ const manifestGlobal = globalThis;
47
+ for (const key of readWorkerManifestGlobalKeys()) {
48
+ const value = manifestGlobal[key];
49
+ if (Array.isArray(value)) {
50
+ return value;
51
+ }
52
+ }
53
+ return [];
54
+ };
55
+ export const getWorkerManifestQueueNames = () => {
56
+ return Array.from(new Set(getWorkerManifestEntries()
57
+ .map((entry) => entry.queueName)
58
+ .filter((queueName) => typeof queueName === 'string')
59
+ .map((queueName) => queueName.trim())
60
+ .filter((queueName) => queueName.length > 0))).sort((left, right) => left.localeCompare(right));
61
+ };
62
+ export const getWorkerManifestRecord = (workerName) => {
63
+ return getWorkerManifestEntries().find((entry) => (entry.name ?? entry.workerName) === workerName);
64
+ };
65
+ export const getWorkerManifestStatus = (workerName) => {
66
+ return getWorkerManifestRecord(workerName)?.activeStatus === false;
67
+ };
@@ -4,7 +4,9 @@ import { Logger } from '@zintrust/core/logger';
4
4
  import { WorkerFactory } from '../WorkerFactory.js';
5
5
  import { WorkerMetrics as WorkerMetricsManager } from '../WorkerMetrics.js';
6
6
  import { WorkerRegistry } from '../WorkerRegistry.js';
7
+ import { SLAMonitor } from '../SLAMonitor.js';
7
8
  import { maskInfrastructurePasswords } from '../helper/index.js';
9
+ import { getWorkerManifestEntries, getWorkerManifestQueueNames, getWorkerManifestRecord, } from './workerManifest.js';
8
10
  const DEFAULT_PAGE_SIZE = 100;
9
11
  const MAX_PAGE_SIZE = 200;
10
12
  const shouldUseRedisRpcWorkerApi = () => Cloudflare.getWorkersEnv() !== null &&
@@ -34,29 +36,28 @@ const callRedisRpc = async (service, method, payload = {}) => {
34
36
  }
35
37
  return body.result;
36
38
  };
37
- const getManifestEntries = () => {
38
- const manifestGlobal = globalThis;
39
- const manifest = manifestGlobal.__zintrustWorkersManifest ??
40
- manifestGlobal.__zintrustWorkerManifest ??
41
- manifestGlobal.__zintrustAppWorkerManifest ??
42
- [];
43
- return Array.isArray(manifest) ? [...manifest] : [];
44
- };
45
- const getManifestQueueNames = () => Array.from(new Set(getManifestEntries()
46
- .map((entry) => entry.queueName)
47
- .filter((queueName) => typeof queueName === 'string')
48
- .map((queueName) => queueName.trim())
49
- .filter(Boolean))).sort((left, right) => left.localeCompare(right));
50
- const manifestWorkers = () => transformToWorkerData(getManifestEntries()
39
+ const manifestWorkers = () => transformToWorkerData(getWorkerManifestEntries()
51
40
  .map((entry) => {
52
41
  const name = entry.name ?? entry.workerName;
53
42
  if (typeof name !== 'string' || name.trim() === '')
54
43
  return null;
44
+ const autoStart = entry.autoStart ?? false;
45
+ let status;
46
+ if (entry.status) {
47
+ status = normalizeStatus(entry.status);
48
+ }
49
+ else if (autoStart) {
50
+ status = 'running';
51
+ }
52
+ else {
53
+ status = 'stopped';
54
+ }
55
+ const trimmedName = name.trim();
55
56
  return {
56
- name: name.trim(),
57
- queueName: typeof entry.queueName === 'string' ? entry.queueName : `${name}-queue`,
58
- status: normalizeStatus(entry.status ?? 'stopped'),
59
- autoStart: entry.autoStart ?? false,
57
+ name: trimmedName,
58
+ queueName: typeof entry.queueName === 'string' ? entry.queueName : `${trimmedName}-queue`,
59
+ status,
60
+ autoStart,
60
61
  activeStatus: entry.activeStatus ?? true,
61
62
  };
62
63
  })
@@ -234,6 +235,9 @@ export async function getWorkers(query) {
234
235
  hasPrev: page > 1,
235
236
  },
236
237
  drivers: persistence.drivers,
238
+ features: {
239
+ sla: SLAMonitor.isAnyConfigured(),
240
+ },
237
241
  };
238
242
  // Include details if requested
239
243
  if (query.includeDetails) {
@@ -437,6 +441,24 @@ const buildWorkerFromRecord = (record, driver) => {
437
441
  };
438
442
  return buildWorkerFromRaw(rawData, driver);
439
443
  };
444
+ const resolveWorkerDetailsFromPersistence = async (name, driver) => {
445
+ if (driver === 'database') {
446
+ const dbRecord = await WorkerFactory.getPersisted(name, { driver: 'database' });
447
+ if (dbRecord)
448
+ return buildWorkerFromRecord(dbRecord, 'database');
449
+ const redisRecord = await WorkerFactory.getPersisted(name, { driver: 'redis' });
450
+ if (redisRecord)
451
+ return buildWorkerFromRecord(redisRecord, 'redis');
452
+ return undefined;
453
+ }
454
+ const record = await WorkerFactory.getPersisted(name, { driver });
455
+ if (record)
456
+ return buildWorkerFromRecord(record, driver);
457
+ const fileBacked = await WorkerFactory.getFileBackedRecord(name);
458
+ if (fileBacked)
459
+ return buildWorkerFromRecord(fileBacked, 'memory');
460
+ return undefined;
461
+ };
440
462
  const buildWorkerFromRaw = (workerData, driver) => {
441
463
  const status = normalizeStatus(workerData.status ?? 'stopped');
442
464
  return {
@@ -591,7 +613,7 @@ async function getRedisQueueData() {
591
613
  }
592
614
  const monitor = QueueMonitor.create({
593
615
  knownQueues: async () => {
594
- const manifestQueues = getManifestQueueNames();
616
+ const manifestQueues = getWorkerManifestQueueNames();
595
617
  if (shouldUseRedisRpcWorkerApi() && manifestQueues.length > 0) {
596
618
  return manifestQueues;
597
619
  }
@@ -980,38 +1002,37 @@ const getLiveWorkerMetricsByName = () => {
980
1002
  }
981
1003
  return liveMetrics;
982
1004
  };
1005
+ const buildRedisRpcManifestWorker = (name, manifestRecord) => {
1006
+ if (!manifestRecord)
1007
+ return undefined;
1008
+ const trimmedName = (manifestRecord.name ?? manifestRecord.workerName ?? name).trim();
1009
+ return buildWorkerFromRaw({
1010
+ name: trimmedName,
1011
+ queueName: typeof manifestRecord.queueName === 'string' && manifestRecord.queueName.trim().length > 0
1012
+ ? manifestRecord.queueName.trim()
1013
+ : `${trimmedName}-queue`,
1014
+ status: normalizeStatus(manifestRecord.status ?? 'stopped'),
1015
+ autoStart: manifestRecord.autoStart ?? false,
1016
+ activeStatus: manifestRecord.activeStatus ?? true,
1017
+ }, 'redis');
1018
+ };
1019
+ const resolveRedisRpcWorkerDetails = async (name) => {
1020
+ const persistence = await redisRpcPersistence(5000);
1021
+ const persistedWorker = persistence.workers.find((candidate) => candidate.name === name);
1022
+ if (persistedWorker)
1023
+ return persistedWorker;
1024
+ return buildRedisRpcManifestWorker(name, getWorkerManifestRecord(name));
1025
+ };
983
1026
  export async function toggleAutoStart(name, enabled) {
984
1027
  await WorkerFactory.setAutoStart(name, enabled);
985
1028
  }
986
1029
  export async function getWorkerDetails(name, driver) {
987
- const persistenceDriver = (driver || process.env['WORKER_PERSISTENCE_DRIVER']) ?? 'memory';
988
- const isMixedPersistence = persistenceDriver === 'database';
989
- let worker;
990
- if (isMixedPersistence) {
991
- const dbRecord = await WorkerFactory.getPersisted(name, { driver: 'database' });
992
- if (dbRecord) {
993
- worker = buildWorkerFromRecord(dbRecord, 'database');
994
- }
995
- else {
996
- const redisRecord = await WorkerFactory.getPersisted(name, { driver: 'redis' });
997
- if (redisRecord) {
998
- worker = buildWorkerFromRecord(redisRecord, 'redis');
999
- }
1000
- }
1001
- }
1002
- else {
1003
- const normalizedDriver = normalizeDriver(persistenceDriver);
1004
- const record = await WorkerFactory.getPersisted(name, { driver: normalizedDriver });
1005
- if (record) {
1006
- worker = buildWorkerFromRecord(record, normalizedDriver);
1007
- }
1008
- }
1009
- if (!worker) {
1010
- const fileBacked = await WorkerFactory.getFileBackedRecord(name);
1011
- if (fileBacked) {
1012
- worker = buildWorkerFromRecord(fileBacked, 'memory');
1013
- }
1014
- }
1030
+ const persistenceDriver = (driver || Env.get('WORKER_PERSISTENCE_DRIVER', 'memory')) ?? 'memory';
1031
+ const normalizedDriver = normalizeDriver(String(persistenceDriver).toLowerCase());
1032
+ const fromRedisRpc = shouldUseRedisRpcWorkerApi() && (driver === undefined || normalizedDriver === 'redis');
1033
+ const worker = fromRedisRpc
1034
+ ? await resolveRedisRpcWorkerDetails(name)
1035
+ : await resolveWorkerDetailsFromPersistence(name, normalizedDriver);
1015
1036
  if (!worker) {
1016
1037
  throw ErrorFactory.createWorkerError(`Worker ${name} not found`);
1017
1038
  }