@zintrust/workers 0.1.27

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.
Files changed (178) hide show
  1. package/README.md +861 -0
  2. package/dist/AnomalyDetection.d.ts +102 -0
  3. package/dist/AnomalyDetection.js +321 -0
  4. package/dist/AutoScaler.d.ts +127 -0
  5. package/dist/AutoScaler.js +425 -0
  6. package/dist/BroadcastWorker.d.ts +21 -0
  7. package/dist/BroadcastWorker.js +24 -0
  8. package/dist/CanaryController.d.ts +103 -0
  9. package/dist/CanaryController.js +380 -0
  10. package/dist/ChaosEngineering.d.ts +79 -0
  11. package/dist/ChaosEngineering.js +216 -0
  12. package/dist/CircuitBreaker.d.ts +106 -0
  13. package/dist/CircuitBreaker.js +374 -0
  14. package/dist/ClusterLock.d.ts +90 -0
  15. package/dist/ClusterLock.js +385 -0
  16. package/dist/ComplianceManager.d.ts +177 -0
  17. package/dist/ComplianceManager.js +556 -0
  18. package/dist/DatacenterOrchestrator.d.ts +133 -0
  19. package/dist/DatacenterOrchestrator.js +404 -0
  20. package/dist/DeadLetterQueue.d.ts +122 -0
  21. package/dist/DeadLetterQueue.js +539 -0
  22. package/dist/HealthMonitor.d.ts +42 -0
  23. package/dist/HealthMonitor.js +301 -0
  24. package/dist/MultiQueueWorker.d.ts +89 -0
  25. package/dist/MultiQueueWorker.js +277 -0
  26. package/dist/NotificationWorker.d.ts +21 -0
  27. package/dist/NotificationWorker.js +23 -0
  28. package/dist/Observability.d.ts +153 -0
  29. package/dist/Observability.js +530 -0
  30. package/dist/PluginManager.d.ts +123 -0
  31. package/dist/PluginManager.js +392 -0
  32. package/dist/PriorityQueue.d.ts +117 -0
  33. package/dist/PriorityQueue.js +244 -0
  34. package/dist/ResourceMonitor.d.ts +164 -0
  35. package/dist/ResourceMonitor.js +605 -0
  36. package/dist/SLAMonitor.d.ts +110 -0
  37. package/dist/SLAMonitor.js +274 -0
  38. package/dist/WorkerFactory.d.ts +193 -0
  39. package/dist/WorkerFactory.js +1507 -0
  40. package/dist/WorkerInit.d.ts +85 -0
  41. package/dist/WorkerInit.js +223 -0
  42. package/dist/WorkerMetrics.d.ts +114 -0
  43. package/dist/WorkerMetrics.js +509 -0
  44. package/dist/WorkerRegistry.d.ts +145 -0
  45. package/dist/WorkerRegistry.js +319 -0
  46. package/dist/WorkerShutdown.d.ts +61 -0
  47. package/dist/WorkerShutdown.js +159 -0
  48. package/dist/WorkerVersioning.d.ts +107 -0
  49. package/dist/WorkerVersioning.js +300 -0
  50. package/dist/build-manifest.json +462 -0
  51. package/dist/config/workerConfig.d.ts +3 -0
  52. package/dist/config/workerConfig.js +19 -0
  53. package/dist/createQueueWorker.d.ts +23 -0
  54. package/dist/createQueueWorker.js +113 -0
  55. package/dist/dashboard/index.d.ts +1 -0
  56. package/dist/dashboard/index.js +1 -0
  57. package/dist/dashboard/types.d.ts +117 -0
  58. package/dist/dashboard/types.js +1 -0
  59. package/dist/dashboard/workers-api.d.ts +4 -0
  60. package/dist/dashboard/workers-api.js +638 -0
  61. package/dist/dashboard/workers-dashboard-ui.d.ts +3 -0
  62. package/dist/dashboard/workers-dashboard-ui.js +1026 -0
  63. package/dist/dashboard/workers-dashboard.d.ts +4 -0
  64. package/dist/dashboard/workers-dashboard.js +904 -0
  65. package/dist/helper/index.d.ts +5 -0
  66. package/dist/helper/index.js +10 -0
  67. package/dist/http/WorkerApiController.d.ts +38 -0
  68. package/dist/http/WorkerApiController.js +312 -0
  69. package/dist/http/WorkerController.d.ts +374 -0
  70. package/dist/http/WorkerController.js +1351 -0
  71. package/dist/http/middleware/CustomValidation.d.ts +92 -0
  72. package/dist/http/middleware/CustomValidation.js +270 -0
  73. package/dist/http/middleware/DatacenterValidator.d.ts +3 -0
  74. package/dist/http/middleware/DatacenterValidator.js +94 -0
  75. package/dist/http/middleware/EditWorkerValidation.d.ts +7 -0
  76. package/dist/http/middleware/EditWorkerValidation.js +55 -0
  77. package/dist/http/middleware/FeaturesValidator.d.ts +3 -0
  78. package/dist/http/middleware/FeaturesValidator.js +60 -0
  79. package/dist/http/middleware/InfrastructureValidator.d.ts +31 -0
  80. package/dist/http/middleware/InfrastructureValidator.js +226 -0
  81. package/dist/http/middleware/OptionsValidator.d.ts +3 -0
  82. package/dist/http/middleware/OptionsValidator.js +112 -0
  83. package/dist/http/middleware/PayloadSanitizer.d.ts +7 -0
  84. package/dist/http/middleware/PayloadSanitizer.js +42 -0
  85. package/dist/http/middleware/ProcessorPathSanitizer.d.ts +3 -0
  86. package/dist/http/middleware/ProcessorPathSanitizer.js +74 -0
  87. package/dist/http/middleware/QueueNameSanitizer.d.ts +3 -0
  88. package/dist/http/middleware/QueueNameSanitizer.js +45 -0
  89. package/dist/http/middleware/ValidateDriver.d.ts +7 -0
  90. package/dist/http/middleware/ValidateDriver.js +20 -0
  91. package/dist/http/middleware/VersionSanitizer.d.ts +3 -0
  92. package/dist/http/middleware/VersionSanitizer.js +25 -0
  93. package/dist/http/middleware/WorkerNameSanitizer.d.ts +3 -0
  94. package/dist/http/middleware/WorkerNameSanitizer.js +46 -0
  95. package/dist/http/middleware/WorkerValidationChain.d.ts +27 -0
  96. package/dist/http/middleware/WorkerValidationChain.js +185 -0
  97. package/dist/index.d.ts +46 -0
  98. package/dist/index.js +48 -0
  99. package/dist/routes/workers.d.ts +12 -0
  100. package/dist/routes/workers.js +81 -0
  101. package/dist/storage/WorkerStore.d.ts +45 -0
  102. package/dist/storage/WorkerStore.js +195 -0
  103. package/dist/type.d.ts +76 -0
  104. package/dist/type.js +1 -0
  105. package/dist/ui/router/ui.d.ts +3 -0
  106. package/dist/ui/router/ui.js +83 -0
  107. package/dist/ui/types/worker-ui.d.ts +229 -0
  108. package/dist/ui/types/worker-ui.js +5 -0
  109. package/package.json +53 -0
  110. package/src/AnomalyDetection.ts +434 -0
  111. package/src/AutoScaler.ts +654 -0
  112. package/src/BroadcastWorker.ts +34 -0
  113. package/src/CanaryController.ts +531 -0
  114. package/src/ChaosEngineering.ts +301 -0
  115. package/src/CircuitBreaker.ts +495 -0
  116. package/src/ClusterLock.ts +499 -0
  117. package/src/ComplianceManager.ts +815 -0
  118. package/src/DatacenterOrchestrator.ts +561 -0
  119. package/src/DeadLetterQueue.ts +733 -0
  120. package/src/HealthMonitor.ts +390 -0
  121. package/src/MultiQueueWorker.ts +431 -0
  122. package/src/NotificationWorker.ts +33 -0
  123. package/src/Observability.ts +696 -0
  124. package/src/PluginManager.ts +551 -0
  125. package/src/PriorityQueue.ts +351 -0
  126. package/src/ResourceMonitor.ts +769 -0
  127. package/src/SLAMonitor.ts +408 -0
  128. package/src/WorkerFactory.ts +2108 -0
  129. package/src/WorkerInit.ts +313 -0
  130. package/src/WorkerMetrics.ts +709 -0
  131. package/src/WorkerRegistry.ts +443 -0
  132. package/src/WorkerShutdown.ts +210 -0
  133. package/src/WorkerVersioning.ts +422 -0
  134. package/src/config/workerConfig.ts +25 -0
  135. package/src/createQueueWorker.ts +174 -0
  136. package/src/dashboard/index.ts +6 -0
  137. package/src/dashboard/types.ts +141 -0
  138. package/src/dashboard/workers-api.ts +785 -0
  139. package/src/dashboard/zintrust.svg +30 -0
  140. package/src/helper/index.ts +11 -0
  141. package/src/http/WorkerApiController.ts +369 -0
  142. package/src/http/WorkerController.ts +1512 -0
  143. package/src/http/middleware/CustomValidation.ts +360 -0
  144. package/src/http/middleware/DatacenterValidator.ts +124 -0
  145. package/src/http/middleware/EditWorkerValidation.ts +74 -0
  146. package/src/http/middleware/FeaturesValidator.ts +82 -0
  147. package/src/http/middleware/InfrastructureValidator.ts +295 -0
  148. package/src/http/middleware/OptionsValidator.ts +144 -0
  149. package/src/http/middleware/PayloadSanitizer.ts +52 -0
  150. package/src/http/middleware/ProcessorPathSanitizer.ts +86 -0
  151. package/src/http/middleware/QueueNameSanitizer.ts +55 -0
  152. package/src/http/middleware/ValidateDriver.ts +29 -0
  153. package/src/http/middleware/VersionSanitizer.ts +30 -0
  154. package/src/http/middleware/WorkerNameSanitizer.ts +56 -0
  155. package/src/http/middleware/WorkerValidationChain.ts +230 -0
  156. package/src/index.ts +98 -0
  157. package/src/routes/workers.ts +154 -0
  158. package/src/storage/WorkerStore.ts +240 -0
  159. package/src/type.ts +89 -0
  160. package/src/types/queue-monitor.d.ts +38 -0
  161. package/src/types/queue-redis.d.ts +38 -0
  162. package/src/ui/README.md +13 -0
  163. package/src/ui/components/JsonEditor.js +670 -0
  164. package/src/ui/components/JsonViewer.js +387 -0
  165. package/src/ui/components/WorkerCard.js +178 -0
  166. package/src/ui/components/WorkerExpandPanel.js +257 -0
  167. package/src/ui/components/fetcher.js +42 -0
  168. package/src/ui/components/sla-scorecard.js +32 -0
  169. package/src/ui/components/styles.css +30 -0
  170. package/src/ui/components/table-expander.js +34 -0
  171. package/src/ui/integration/worker-ui-integration.js +565 -0
  172. package/src/ui/router/ui.ts +99 -0
  173. package/src/ui/services/workerApi.js +240 -0
  174. package/src/ui/types/worker-ui.ts +283 -0
  175. package/src/ui/utils/jsonValidator.js +444 -0
  176. package/src/ui/workers/index.html +202 -0
  177. package/src/ui/workers/main.js +1781 -0
  178. package/src/ui/workers/styles.css +1350 -0
@@ -0,0 +1,301 @@
1
+ import { ErrorFactory, Logger } from '@zintrust/core';
2
+ import { WorkerCreationStatus, WorkerFactory } from './WorkerFactory';
3
+ const DEFAULT_CONFIG = {
4
+ enabled: true,
5
+ tickIntervalMs: 1000,
6
+ concurrencyLimit: 50,
7
+ checkTimeoutMs: 5000,
8
+ intervalHealthyMs: 30000,
9
+ intervalSuspectMs: 5000,
10
+ failureThreshold: 2,
11
+ historyLimit: 50,
12
+ };
13
+ // Module-level state (Singleton by nature of ESM)
14
+ const registry = new Map();
15
+ let config = { ...DEFAULT_CONFIG };
16
+ let timer = null;
17
+ let runningChecks = 0;
18
+ // Internal Helpers
19
+ const persistStatusChange = async (name, status, lastError) => {
20
+ try {
21
+ await WorkerFactory.updateStatus(name, status, lastError);
22
+ }
23
+ catch (err) {
24
+ Logger.error(`Failed to persist status change for ${name}`, err);
25
+ }
26
+ };
27
+ const verifyWorkerHealth = async (worker, _name, _queueName) => {
28
+ // Check if isClosing exists (isClosing check safe for mocks)
29
+ const workerAny = worker;
30
+ const isClosingFn = workerAny['isClosing'];
31
+ if (worker.isPaused() ||
32
+ (typeof isClosingFn === 'function' && isClosingFn())) {
33
+ return false;
34
+ }
35
+ const isRunning = await worker.isRunning();
36
+ if (!isRunning)
37
+ return false;
38
+ const client = await worker.client;
39
+ const pingResult = await client.ping();
40
+ if (pingResult !== 'PONG') {
41
+ throw ErrorFactory.createWorkerError(`Redis ping failed: ${pingResult}`);
42
+ }
43
+ Logger.debug(`Worker health verification passed for ${_name} ${_queueName}`);
44
+ return true;
45
+ };
46
+ const updateState = (state, isHealthy, errorMsg, latency) => {
47
+ const now = new Date();
48
+ state.lastCheck = now;
49
+ // Determine status (healthy > degraded > critical)
50
+ let status;
51
+ if (isHealthy) {
52
+ status = 'healthy';
53
+ }
54
+ else if (state.consecutiveFailures < config.failureThreshold) {
55
+ status = 'degraded';
56
+ }
57
+ else {
58
+ status = 'critical';
59
+ }
60
+ // Create Check Result
61
+ const result = {
62
+ timestamp: now,
63
+ status,
64
+ latency,
65
+ message: errorMsg,
66
+ };
67
+ // Add to history
68
+ state.history.push(result);
69
+ if (state.history.length > config.historyLimit) {
70
+ state.history.shift();
71
+ }
72
+ // Callbacks
73
+ if (!isHealthy && state.config?.degradedCallback) {
74
+ state.config.degradedCallback(state.name, result);
75
+ }
76
+ if (result.status === 'critical' && state.config?.criticalCallback) {
77
+ state.config.criticalCallback(state.name, result);
78
+ }
79
+ if (isHealthy) {
80
+ state.consecutiveFailures = 0;
81
+ if (state.status !== WorkerCreationStatus.RUNNING) {
82
+ persistStatusChange(state.name, WorkerCreationStatus.RUNNING);
83
+ state.status = WorkerCreationStatus.RUNNING;
84
+ Logger.info(`Worker ${state.name} recovered to RUNNING`);
85
+ }
86
+ const jitter = Math.floor(Math.random() * 500); //NOSONAR
87
+ state.nextCheck = new Date(now.getTime() + config.intervalHealthyMs + jitter);
88
+ }
89
+ else {
90
+ state.consecutiveFailures++;
91
+ if (state.consecutiveFailures >= config.failureThreshold &&
92
+ state.status !== WorkerCreationStatus.FAILED) {
93
+ persistStatusChange(state.name, WorkerCreationStatus.FAILED, errorMsg);
94
+ state.status = WorkerCreationStatus.FAILED;
95
+ Logger.warn(`Worker ${state.name} marked FAILED after ${state.consecutiveFailures} checks`, {
96
+ error: errorMsg,
97
+ });
98
+ }
99
+ const jitter = Math.floor(Math.random() * 500); //NOSONAR
100
+ state.nextCheck = new Date(now.getTime() + config.intervalSuspectMs + jitter);
101
+ }
102
+ };
103
+ const performCheck = async (state) => {
104
+ const startTime = Date.now();
105
+ let isHealthy = false;
106
+ let errorMsg;
107
+ try {
108
+ if (!state.worker) {
109
+ throw ErrorFactory.createWorkerError('Worker instance not available');
110
+ }
111
+ isHealthy = await Promise.race([
112
+ verifyWorkerHealth(state.worker, state.name, state.queueName || 'unknown'),
113
+ new Promise((_, reject) => {
114
+ // eslint-disable-next-line
115
+ const id = setTimeout(() => {
116
+ reject(ErrorFactory.createWorkerError('Health check timeout'));
117
+ }, config.checkTimeoutMs);
118
+ // Unref to prevent holding event loop if everything else finishes
119
+ id.unref();
120
+ }),
121
+ ]);
122
+ }
123
+ catch (err) {
124
+ isHealthy = false;
125
+ errorMsg = err.message;
126
+ }
127
+ const duration = Date.now() - startTime;
128
+ updateState(state, isHealthy, errorMsg, duration);
129
+ };
130
+ const scheduleCheck = async (state) => {
131
+ state.inProgress = true;
132
+ runningChecks++;
133
+ performCheck(state).finally(() => {
134
+ state.inProgress = false;
135
+ runningChecks--;
136
+ });
137
+ };
138
+ const tick = async () => {
139
+ const now = new Date();
140
+ const candidates = [];
141
+ for (const state of registry.values()) {
142
+ if (runningChecks >= config.concurrencyLimit)
143
+ break;
144
+ // Skip if checks are paused or if worker instance is missing (wait for register)
145
+ if (!state.worker && !state.queueName)
146
+ continue;
147
+ if (!state.inProgress && state.nextCheck <= now) {
148
+ candidates.push(state);
149
+ }
150
+ }
151
+ for (const candidate of candidates) {
152
+ if (runningChecks >= config.concurrencyLimit)
153
+ break;
154
+ scheduleCheck(candidate);
155
+ }
156
+ };
157
+ const start = () => {
158
+ if (timer)
159
+ return;
160
+ timer = setInterval(() => tick(), config.tickIntervalMs);
161
+ Logger.debug('HealthMonitor started');
162
+ };
163
+ const stop = () => {
164
+ if (timer) {
165
+ clearInterval(timer);
166
+ timer = null;
167
+ }
168
+ Logger.debug('HealthMonitor stopped');
169
+ };
170
+ // Exported Public Methods
171
+ const configure = (newConfig) => {
172
+ config = { ...config, ...newConfig };
173
+ if (timer) {
174
+ stop();
175
+ start();
176
+ }
177
+ };
178
+ const register = (name, worker, queueName) => {
179
+ let state = registry.get(name);
180
+ if (state) {
181
+ // update existing entry (maybe created by startMonitoring)
182
+ state.worker = worker;
183
+ state.queueName = queueName;
184
+ }
185
+ else {
186
+ // Add jitter
187
+ const initialDelay = Math.floor(Math.random() * 5000); //NOSONAR
188
+ state = {
189
+ name,
190
+ worker,
191
+ queueName,
192
+ status: WorkerCreationStatus.STARTING,
193
+ lastCheck: new Date(),
194
+ nextCheck: new Date(Date.now() + initialDelay),
195
+ consecutiveFailures: 0,
196
+ inProgress: false,
197
+ history: [],
198
+ };
199
+ registry.set(name, state);
200
+ }
201
+ if (!timer) {
202
+ start();
203
+ }
204
+ };
205
+ const startMonitoring = (name, monitorConfig) => {
206
+ const state = registry.get(name);
207
+ if (state) {
208
+ if (monitorConfig)
209
+ state.config = { ...state.config, ...monitorConfig };
210
+ }
211
+ else {
212
+ // Worker instance not yet registered, create placeholder
213
+ const initialDelay = Math.floor(Math.random() * 5000); //NOSONAR
214
+ registry.set(name, {
215
+ name,
216
+ status: WorkerCreationStatus.STARTING,
217
+ lastCheck: new Date(),
218
+ nextCheck: new Date(Date.now() + initialDelay),
219
+ consecutiveFailures: 0,
220
+ inProgress: false,
221
+ history: [],
222
+ config: monitorConfig,
223
+ });
224
+ }
225
+ if (!timer)
226
+ start();
227
+ };
228
+ const unregister = (name) => {
229
+ registry.delete(name);
230
+ if (registry.size === 0) {
231
+ stop();
232
+ }
233
+ };
234
+ const stopMonitoring = (name) => {
235
+ unregister(name);
236
+ };
237
+ const updateConfig = (name, monitorConfig) => {
238
+ startMonitoring(name, monitorConfig);
239
+ };
240
+ const getCurrentHealth = (name) => {
241
+ const state = registry.get(name);
242
+ if (!state || state.history.length === 0)
243
+ return null;
244
+ return state.history[state.history.length - 1];
245
+ };
246
+ const getHealthHistory = (name, limit) => {
247
+ const state = registry.get(name);
248
+ if (!state)
249
+ return [];
250
+ const history = state.history;
251
+ return limit ? history.slice(-limit) : history;
252
+ };
253
+ const getHealthTrend = (name) => {
254
+ const history = getHealthHistory(name, 10);
255
+ const uptime = history.filter((h) => h.status === 'healthy').length / (history.length || 1);
256
+ return { uptime, samples: history.length };
257
+ };
258
+ const getSummary = async () => {
259
+ const summary = {
260
+ total: registry.size,
261
+ healthy: 0,
262
+ degraded: 0,
263
+ critical: 0,
264
+ details: [],
265
+ };
266
+ for (const [name, state] of registry) {
267
+ const lastResult = state.history[state.history.length - 1];
268
+ const status = lastResult?.status || 'unknown';
269
+ if (status === 'healthy')
270
+ summary.healthy++;
271
+ else if (status === 'degraded')
272
+ summary.degraded++;
273
+ else if (status === 'critical')
274
+ summary.critical++;
275
+ summary.details.push({
276
+ name,
277
+ status,
278
+ lastCheck: state.lastCheck,
279
+ });
280
+ }
281
+ return summary;
282
+ };
283
+ const shutdown = () => {
284
+ stop();
285
+ registry.clear();
286
+ };
287
+ export const HealthMonitor = Object.freeze({
288
+ configure,
289
+ register,
290
+ unregister,
291
+ start,
292
+ stop,
293
+ startMonitoring,
294
+ stopMonitoring,
295
+ updateConfig,
296
+ getCurrentHealth,
297
+ getHealthHistory,
298
+ getHealthTrend,
299
+ getSummary,
300
+ shutdown,
301
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Multi-Queue Worker Support
3
+ * Enable workers to process multiple queues with different priorities
4
+ * Sealed namespace for immutability
5
+ */
6
+ import { type Job } from 'bullmq';
7
+ export type QueueConfig = {
8
+ name: string;
9
+ concurrency: number;
10
+ priority: number;
11
+ enabled: boolean;
12
+ rateLimit?: {
13
+ max: number;
14
+ duration: number;
15
+ };
16
+ };
17
+ export type MultiQueueWorkerConfig = {
18
+ workerName: string;
19
+ queues: QueueConfig[];
20
+ processor: (job: Job) => Promise<unknown>;
21
+ sharedConcurrency?: number;
22
+ defaultConcurrency?: number;
23
+ };
24
+ export type QueueStats = {
25
+ queueName: string;
26
+ processed: number;
27
+ failed: number;
28
+ active: number;
29
+ waiting: number;
30
+ enabled: boolean;
31
+ lastProcessedAt?: Date;
32
+ };
33
+ /**
34
+ * Multi-Queue Worker Manager - Sealed namespace
35
+ */
36
+ export declare const MultiQueueWorker: Readonly<{
37
+ /**
38
+ * Create multi-queue worker
39
+ */
40
+ create(config: MultiQueueWorkerConfig): void;
41
+ /**
42
+ * Start processing for a specific queue
43
+ */
44
+ startQueue(workerName: string, queueName: string): Promise<void>;
45
+ /**
46
+ * Stop processing for a specific queue
47
+ */
48
+ stopQueue(workerName: string, queueName: string): Promise<void>;
49
+ /**
50
+ * Start all queues
51
+ */
52
+ startAll(workerName: string): Promise<void>;
53
+ /**
54
+ * Stop all queues
55
+ */
56
+ stopAll(workerName: string): Promise<void>;
57
+ /**
58
+ * Update queue priority
59
+ */
60
+ updateQueuePriority(workerName: string, queueName: string, priority: number): void;
61
+ /**
62
+ * Update queue concurrency
63
+ */
64
+ updateQueueConcurrency(workerName: string, queueName: string, concurrency: number): Promise<void>;
65
+ /**
66
+ * Get stats for a queue
67
+ */
68
+ getQueueStats(workerName: string, queueName: string): Promise<QueueStats>;
69
+ /**
70
+ * Get stats for all queues
71
+ */
72
+ getAllStats(workerName: string): Promise<ReadonlyArray<QueueStats>>;
73
+ /**
74
+ * Get configuration
75
+ */
76
+ getConfig(workerName: string): MultiQueueWorkerConfig | null;
77
+ /**
78
+ * List all multi-queue workers
79
+ */
80
+ list(): string[];
81
+ /**
82
+ * Remove multi-queue worker
83
+ */
84
+ remove(workerName: string): Promise<void>;
85
+ /**
86
+ * Shutdown all multi-queue workers
87
+ */
88
+ shutdown(): Promise<void>;
89
+ }>;
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Multi-Queue Worker Support
3
+ * Enable workers to process multiple queues with different priorities
4
+ * Sealed namespace for immutability
5
+ */
6
+ import { ErrorFactory, Logger } from '@zintrust/core';
7
+ import { Worker } from 'bullmq';
8
+ import { PriorityQueue } from './PriorityQueue';
9
+ // Internal state
10
+ const multiQueueWorkers = new Map();
11
+ /**
12
+ * Helper: Create worker for a queue
13
+ */
14
+ const createQueueWorker = (workerName, queueConfig, processor) => {
15
+ const queue = PriorityQueue.getQueueInstance(queueConfig.name);
16
+ const connection = queue.opts.connection;
17
+ const workerOptions = {
18
+ connection,
19
+ concurrency: queueConfig.concurrency,
20
+ limiter: queueConfig.rateLimit,
21
+ autorun: queueConfig.enabled,
22
+ prefix: queue.opts.prefix,
23
+ };
24
+ const worker = new Worker(queueConfig.name, async (job) => {
25
+ Logger.debug(`Processing job from queue: ${queueConfig.name}`, {
26
+ jobId: job.id,
27
+ workerName,
28
+ });
29
+ return processor(job);
30
+ }, workerOptions);
31
+ // Set up event listeners
32
+ worker.on('completed', (job) => {
33
+ const stats = multiQueueWorkers.get(workerName)?.stats.get(queueConfig.name);
34
+ if (stats) {
35
+ stats.processed++;
36
+ stats.lastProcessedAt = new Date();
37
+ }
38
+ Logger.debug(`Job completed from queue: ${queueConfig.name}`, {
39
+ jobId: job.id,
40
+ workerName,
41
+ });
42
+ });
43
+ worker.on('failed', (job, error) => {
44
+ const stats = multiQueueWorkers.get(workerName)?.stats.get(queueConfig.name);
45
+ if (stats) {
46
+ stats.failed++;
47
+ }
48
+ Logger.error(`Job failed from queue: ${queueConfig.name}`, error, 'workers');
49
+ Logger.debug('Queue job failure details', {
50
+ jobId: job?.id,
51
+ workerName,
52
+ queueName: queueConfig.name,
53
+ });
54
+ });
55
+ worker.on('active', (_job) => {
56
+ const stats = multiQueueWorkers.get(workerName)?.stats.get(queueConfig.name);
57
+ if (stats) {
58
+ stats.active++;
59
+ }
60
+ });
61
+ return worker;
62
+ };
63
+ /**
64
+ * Helper: Initialize stats for queue
65
+ */
66
+ const initializeQueueStats = (queueName, enabled) => {
67
+ return {
68
+ queueName,
69
+ processed: 0,
70
+ failed: 0,
71
+ active: 0,
72
+ waiting: 0,
73
+ enabled,
74
+ };
75
+ };
76
+ /**
77
+ * Multi-Queue Worker Manager - Sealed namespace
78
+ */
79
+ export const MultiQueueWorker = Object.freeze({
80
+ /**
81
+ * Create multi-queue worker
82
+ */
83
+ create(config) {
84
+ if (multiQueueWorkers.has(config.workerName)) {
85
+ throw ErrorFactory.createWorkerError(`Multi-queue worker "${config.workerName}" already exists`);
86
+ }
87
+ const workers = new Map();
88
+ const stats = new Map();
89
+ // Sort queues by priority (higher first)
90
+ const sortedQueues = [...config.queues].sort((a, b) => b.priority - a.priority);
91
+ // Create workers for each queue
92
+ for (const queueConfig of sortedQueues) {
93
+ const worker = createQueueWorker(config.workerName, queueConfig, config.processor);
94
+ workers.set(queueConfig.name, worker);
95
+ stats.set(queueConfig.name, initializeQueueStats(queueConfig.name, queueConfig.enabled));
96
+ }
97
+ multiQueueWorkers.set(config.workerName, {
98
+ config,
99
+ workers,
100
+ stats,
101
+ });
102
+ Logger.info(`Multi-queue worker created: ${config.workerName}`, {
103
+ queues: sortedQueues.map((q) => q.name),
104
+ totalConcurrency: sortedQueues.reduce((sum, q) => sum + q.concurrency, 0),
105
+ });
106
+ },
107
+ /**
108
+ * Start processing for a specific queue
109
+ */
110
+ async startQueue(workerName, queueName) {
111
+ const mqw = multiQueueWorkers.get(workerName);
112
+ if (!mqw) {
113
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
114
+ }
115
+ const worker = mqw.workers.get(queueName);
116
+ if (!worker) {
117
+ throw ErrorFactory.createNotFoundError(`Queue "${queueName}" not found in worker "${workerName}"`);
118
+ }
119
+ await worker.run();
120
+ const stats = mqw.stats.get(queueName);
121
+ if (stats) {
122
+ stats.enabled = true;
123
+ }
124
+ Logger.info(`Queue started: ${queueName}`, { workerName });
125
+ },
126
+ /**
127
+ * Stop processing for a specific queue
128
+ */
129
+ async stopQueue(workerName, queueName) {
130
+ const mqw = multiQueueWorkers.get(workerName);
131
+ if (!mqw) {
132
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
133
+ }
134
+ const worker = mqw.workers.get(queueName);
135
+ if (!worker) {
136
+ throw ErrorFactory.createNotFoundError(`Queue "${queueName}" not found in worker "${workerName}"`);
137
+ }
138
+ await worker.pause();
139
+ const stats = mqw.stats.get(queueName);
140
+ if (stats) {
141
+ stats.enabled = false;
142
+ }
143
+ Logger.info(`Queue stopped: ${queueName}`, { workerName });
144
+ },
145
+ /**
146
+ * Start all queues
147
+ */
148
+ async startAll(workerName) {
149
+ const mqw = multiQueueWorkers.get(workerName);
150
+ if (!mqw) {
151
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
152
+ }
153
+ const promises = Array.from(mqw.workers.keys()).map(async (queueName) => MultiQueueWorker.startQueue(workerName, queueName));
154
+ await Promise.all(promises);
155
+ Logger.info(`All queues started for worker: ${workerName}`);
156
+ },
157
+ /**
158
+ * Stop all queues
159
+ */
160
+ async stopAll(workerName) {
161
+ const mqw = multiQueueWorkers.get(workerName);
162
+ if (!mqw) {
163
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
164
+ }
165
+ const promises = Array.from(mqw.workers.keys()).map(async (queueName) => MultiQueueWorker.stopQueue(workerName, queueName));
166
+ await Promise.all(promises);
167
+ Logger.info(`All queues stopped for worker: ${workerName}`);
168
+ },
169
+ /**
170
+ * Update queue priority
171
+ */
172
+ updateQueuePriority(workerName, queueName, priority) {
173
+ const mqw = multiQueueWorkers.get(workerName);
174
+ if (!mqw) {
175
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
176
+ }
177
+ const queueConfig = mqw.config.queues.find((q) => q.name === queueName);
178
+ if (!queueConfig) {
179
+ throw ErrorFactory.createNotFoundError(`Queue "${queueName}" not found in worker "${workerName}"`);
180
+ }
181
+ queueConfig.priority = priority;
182
+ Logger.info(`Queue priority updated: ${queueName}`, { workerName, priority });
183
+ },
184
+ /**
185
+ * Update queue concurrency
186
+ */
187
+ async updateQueueConcurrency(workerName, queueName, concurrency) {
188
+ const mqw = multiQueueWorkers.get(workerName);
189
+ if (!mqw) {
190
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
191
+ }
192
+ const worker = mqw.workers.get(queueName);
193
+ if (!worker) {
194
+ throw ErrorFactory.createNotFoundError(`Queue "${queueName}" not found in worker "${workerName}"`);
195
+ }
196
+ const queueConfig = mqw.config.queues.find((q) => q.name === queueName);
197
+ if (!queueConfig) {
198
+ throw ErrorFactory.createNotFoundError(`Queue "${queueName}" not found in worker "${workerName}"`);
199
+ }
200
+ queueConfig.concurrency = concurrency;
201
+ // Update worker concurrency (requires restart in BullMQ)
202
+ await worker.close();
203
+ const newWorker = createQueueWorker(workerName, queueConfig, mqw.config.processor);
204
+ mqw.workers.set(queueName, newWorker);
205
+ Logger.info(`Queue concurrency updated: ${queueName}`, { workerName, concurrency });
206
+ },
207
+ /**
208
+ * Get stats for a queue
209
+ */
210
+ async getQueueStats(workerName, queueName) {
211
+ const mqw = multiQueueWorkers.get(workerName);
212
+ if (!mqw) {
213
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
214
+ }
215
+ const stats = mqw.stats.get(queueName);
216
+ if (!stats) {
217
+ throw ErrorFactory.createNotFoundError(`Stats for queue "${queueName}" not found in worker "${workerName}"`);
218
+ }
219
+ // Update waiting count from queue
220
+ PriorityQueue.getQueueInstance(queueName);
221
+ const queueInfo = await PriorityQueue.getQueueInfo(queueName);
222
+ stats.waiting = queueInfo.jobCounts.waiting;
223
+ return { ...stats };
224
+ },
225
+ /**
226
+ * Get stats for all queues
227
+ */
228
+ async getAllStats(workerName) {
229
+ const mqw = multiQueueWorkers.get(workerName);
230
+ if (!mqw) {
231
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
232
+ }
233
+ const allStats = await Promise.all(Array.from(mqw.workers.keys()).map(async (queueName) => MultiQueueWorker.getQueueStats(workerName, queueName)));
234
+ return allStats;
235
+ },
236
+ /**
237
+ * Get configuration
238
+ */
239
+ getConfig(workerName) {
240
+ const mqw = multiQueueWorkers.get(workerName);
241
+ return mqw ? { ...mqw.config } : null;
242
+ },
243
+ /**
244
+ * List all multi-queue workers
245
+ */
246
+ list() {
247
+ return Array.from(multiQueueWorkers.keys());
248
+ },
249
+ /**
250
+ * Remove multi-queue worker
251
+ */
252
+ async remove(workerName) {
253
+ const mqw = multiQueueWorkers.get(workerName);
254
+ if (!mqw) {
255
+ throw ErrorFactory.createNotFoundError(`Multi-queue worker "${workerName}" not found`);
256
+ }
257
+ // Close all workers
258
+ const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
259
+ await Promise.all(closePromises);
260
+ multiQueueWorkers.delete(workerName);
261
+ Logger.info(`Multi-queue worker removed: ${workerName}`);
262
+ },
263
+ /**
264
+ * Shutdown all multi-queue workers
265
+ */
266
+ async shutdown() {
267
+ Logger.info('MultiQueueWorker shutting down...');
268
+ const shutdownPromises = Array.from(multiQueueWorkers.values()).map(async (mqw) => {
269
+ const closePromises = Array.from(mqw.workers.values()).map(async (worker) => worker.close());
270
+ await Promise.all(closePromises);
271
+ });
272
+ await Promise.all(shutdownPromises);
273
+ multiQueueWorkers.clear();
274
+ Logger.info('MultiQueueWorker shutdown complete');
275
+ },
276
+ });
277
+ // Graceful shutdown handled by WorkerShutdown
@@ -0,0 +1,21 @@
1
+ /**
2
+ * NotificationWorker - Processes queued notifications
3
+ *
4
+ * This worker dequeues notification messages and sends them using the Notification service.
5
+ * Use with Queue.dequeue() in a background process or cron job.
6
+ */
7
+ export declare const NotificationWorker: Readonly<{
8
+ processOne: (queueName?: string, driverName?: string) => Promise<boolean>;
9
+ processAll: (queueName?: string, driverName?: string) => Promise<number>;
10
+ runOnce: (opts?: {
11
+ queueName?: string;
12
+ driverName?: string;
13
+ maxItems?: number;
14
+ }) => Promise<number>;
15
+ startWorker: (opts?: {
16
+ queueName?: string;
17
+ driverName?: string;
18
+ signal?: AbortSignal;
19
+ }) => Promise<number>;
20
+ }>;
21
+ export default NotificationWorker;