@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,102 @@
1
+ /**
2
+ * Anomaly Detection
3
+ * Statistical anomaly detection with lightweight baselines
4
+ * Sealed namespace for immutability
5
+ */
6
+ import { type MetricType } from './WorkerMetrics';
7
+ export interface IAnomalyConfig {
8
+ workerName: string;
9
+ metrics: MetricType[];
10
+ sensitivity: number;
11
+ learningPeriod: number;
12
+ alertThreshold: number;
13
+ autoAdjust: boolean;
14
+ }
15
+ export interface IMetric {
16
+ metricType: MetricType;
17
+ value: number;
18
+ timestamp: Date;
19
+ }
20
+ export interface IAnomaly {
21
+ id: string;
22
+ timestamp: Date;
23
+ workerName: string;
24
+ metric: MetricType;
25
+ actual: number;
26
+ expected: number;
27
+ deviation: number;
28
+ confidence: number;
29
+ severity: 'low' | 'medium' | 'high' | 'critical';
30
+ possibleCauses: string[];
31
+ recommendations: string[];
32
+ }
33
+ export interface IPrediction {
34
+ workerName: string;
35
+ horizonHours: number;
36
+ riskScore: number;
37
+ expectedErrorRate: number;
38
+ summary: string;
39
+ }
40
+ export interface IRootCauseAnalysis {
41
+ anomalyId: string;
42
+ suspectedCauses: string[];
43
+ supportingSignals: Record<string, number>;
44
+ }
45
+ export interface IForecast {
46
+ workerName: string;
47
+ metric: MetricType;
48
+ horizonHours: number;
49
+ forecast: number;
50
+ confidence: number;
51
+ }
52
+ export interface IRecommendation {
53
+ action: string;
54
+ reason: string;
55
+ priority: 'low' | 'medium' | 'high';
56
+ }
57
+ /**
58
+ * Anomaly Detection - Sealed namespace
59
+ */
60
+ export declare const AnomalyDetection: Readonly<{
61
+ /**
62
+ * Configure anomaly detection for a worker
63
+ */
64
+ configure(config: IAnomalyConfig): void;
65
+ /**
66
+ * Train baseline model
67
+ */
68
+ trainModel(workerName: string, historicalData: IMetric[]): void;
69
+ /**
70
+ * Update baseline model with recent data
71
+ */
72
+ updateModel(workerName: string, recentData: IMetric[]): void;
73
+ /**
74
+ * Detect anomalies for a worker
75
+ */
76
+ detectAnomalies(workerName: string): Promise<IAnomaly[]>;
77
+ /**
78
+ * Predict failure risk for a worker
79
+ */
80
+ predictFailure(workerName: string, horizonHours: number): Promise<IPrediction>;
81
+ /**
82
+ * Analyze root cause for an anomaly
83
+ */
84
+ analyzeRootCause(anomaly: IAnomaly): IRootCauseAnalysis;
85
+ /**
86
+ * Forecast a metric
87
+ */
88
+ forecastMetric(workerName: string, metric: MetricType, hours: number): Promise<IForecast>;
89
+ /**
90
+ * Generate recommendations for an anomaly
91
+ */
92
+ getRecommendations(anomaly: IAnomaly): IRecommendation[];
93
+ /**
94
+ * Attempt auto-remediation
95
+ */
96
+ autoRemediate(_anomaly: IAnomaly): boolean;
97
+ /**
98
+ * Helper: build training data from metrics
99
+ */
100
+ buildTrainingData(workerName: string): Promise<IMetric[]>;
101
+ }>;
102
+ export default AnomalyDetection;
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Anomaly Detection
3
+ * Statistical anomaly detection with lightweight baselines
4
+ * Sealed namespace for immutability
5
+ */
6
+ import { ErrorFactory, Logger, generateUuid } from '@zintrust/core';
7
+ import { ResourceMonitor } from './ResourceMonitor';
8
+ import { WorkerMetrics } from './WorkerMetrics';
9
+ const configs = new Map();
10
+ const models = new Map();
11
+ const updateStats = (stats, value) => {
12
+ const count = stats.count + 1;
13
+ const delta = value - stats.mean;
14
+ const mean = stats.mean + delta / count;
15
+ const delta2 = value - mean;
16
+ const variance = stats.variance + delta * delta2;
17
+ return {
18
+ mean,
19
+ variance,
20
+ count,
21
+ updatedAt: new Date(),
22
+ };
23
+ };
24
+ const buildStats = (values) => {
25
+ if (values.length === 0) {
26
+ return { mean: 0, variance: 0, count: 0, updatedAt: new Date() };
27
+ }
28
+ let mean = 0;
29
+ let variance = 0;
30
+ let count = 0;
31
+ values.forEach((value) => {
32
+ const updated = updateStats({ mean, variance, count, updatedAt: new Date() }, value);
33
+ mean = updated.mean;
34
+ variance = updated.variance;
35
+ count = updated.count;
36
+ });
37
+ return { mean, variance, count, updatedAt: new Date() };
38
+ };
39
+ const getStdDev = (stats) => {
40
+ if (stats.count <= 1)
41
+ return 0;
42
+ return Math.sqrt(stats.variance / (stats.count - 1));
43
+ };
44
+ const getThreshold = (sensitivity) => {
45
+ const clamped = Math.min(1, Math.max(0, sensitivity));
46
+ return Math.min(3, Math.max(1, 3 - clamped * 2));
47
+ };
48
+ const buildPossibleCauses = (metric) => {
49
+ switch (metric) {
50
+ case 'duration':
51
+ return ['Increased processing time', 'Downstream dependency latency'];
52
+ case 'errors':
53
+ return ['Increased failure rate', 'New error conditions'];
54
+ case 'cpu':
55
+ return ['Resource saturation', 'Inefficient processing logic'];
56
+ case 'memory':
57
+ return ['Memory leak risk', 'Increased payload size'];
58
+ case 'queue-size':
59
+ return ['Traffic spike', 'Worker throttling'];
60
+ default:
61
+ return ['Unexpected workload change'];
62
+ }
63
+ };
64
+ const buildRecommendations = (metric) => {
65
+ switch (metric) {
66
+ case 'duration':
67
+ return ['Review slow job traces', 'Scale worker concurrency temporarily'];
68
+ case 'errors':
69
+ return ['Inspect recent failures', 'Review circuit breaker events'];
70
+ case 'cpu':
71
+ return ['Add capacity or optimize processing', 'Monitor CPU hotspots'];
72
+ case 'memory':
73
+ return ['Inspect memory usage', 'Enable heap snapshots'];
74
+ default:
75
+ return ['Monitor trends and adjust thresholds'];
76
+ }
77
+ };
78
+ const selectSeverity = (zScore) => {
79
+ if (zScore >= 3.5)
80
+ return 'critical';
81
+ if (zScore >= 2.5)
82
+ return 'high';
83
+ if (zScore >= 1.8)
84
+ return 'medium';
85
+ return 'low';
86
+ };
87
+ const ensureConfig = (workerName) => {
88
+ const config = configs.get(workerName);
89
+ if (!config) {
90
+ throw ErrorFactory.createNotFoundError(`Anomaly config not found for worker "${workerName}"`);
91
+ }
92
+ return config;
93
+ };
94
+ const ensureModelMap = (workerName) => {
95
+ let map = models.get(workerName);
96
+ if (!map) {
97
+ map = new Map();
98
+ models.set(workerName, map);
99
+ }
100
+ return map;
101
+ };
102
+ const mapPoints = (metric, points) => points.map((point) => ({
103
+ metricType: metric,
104
+ value: point.value,
105
+ timestamp: point.timestamp,
106
+ }));
107
+ /**
108
+ * Anomaly Detection - Sealed namespace
109
+ */
110
+ export const AnomalyDetection = Object.freeze({
111
+ /**
112
+ * Configure anomaly detection for a worker
113
+ */
114
+ configure(config) {
115
+ configs.set(config.workerName, { ...config });
116
+ Logger.info(`Anomaly detection configured for ${config.workerName}`);
117
+ },
118
+ /**
119
+ * Train baseline model
120
+ */
121
+ trainModel(workerName, historicalData) {
122
+ const config = ensureConfig(workerName);
123
+ const modelMap = ensureModelMap(workerName);
124
+ const metrics = config.metrics;
125
+ metrics.forEach((metric) => {
126
+ const values = historicalData
127
+ .filter((item) => item.metricType === metric)
128
+ .map((item) => item.value);
129
+ modelMap.set(metric, buildStats(values));
130
+ });
131
+ Logger.info(`Anomaly model trained for ${workerName}`);
132
+ },
133
+ /**
134
+ * Update baseline model with recent data
135
+ */
136
+ updateModel(workerName, recentData) {
137
+ ensureConfig(workerName);
138
+ const modelMap = ensureModelMap(workerName);
139
+ recentData.forEach((item) => {
140
+ const current = modelMap.get(item.metricType) ?? {
141
+ mean: 0,
142
+ variance: 0,
143
+ count: 0,
144
+ updatedAt: new Date(),
145
+ };
146
+ modelMap.set(item.metricType, updateStats(current, item.value));
147
+ });
148
+ },
149
+ /**
150
+ * Detect anomalies for a worker
151
+ */
152
+ async detectAnomalies(workerName) {
153
+ const config = ensureConfig(workerName);
154
+ const modelMap = ensureModelMap(workerName);
155
+ const range = {
156
+ start: new Date(Date.now() - 60 * 60 * 1000),
157
+ end: new Date(),
158
+ };
159
+ const results = await Promise.all(config.metrics.map(async (metric) => {
160
+ const entry = await WorkerMetrics.query({
161
+ workerName,
162
+ metricType: metric,
163
+ granularity: 'hourly',
164
+ startDate: range.start,
165
+ endDate: range.end,
166
+ });
167
+ const points = entry.points;
168
+ if (points.length === 0)
169
+ return null;
170
+ const stats = modelMap.get(metric) ?? buildStats(points.map((point) => point.value));
171
+ modelMap.set(metric, stats);
172
+ const latest = points.at(-1);
173
+ if (!latest)
174
+ return null;
175
+ const stdDev = getStdDev(stats);
176
+ if (stdDev === 0)
177
+ return null;
178
+ const zScore = Math.abs((latest.value - stats.mean) / stdDev);
179
+ const threshold = getThreshold(config.sensitivity);
180
+ const confidence = Math.min(1, zScore / threshold);
181
+ if (zScore < threshold || confidence < config.alertThreshold)
182
+ return null;
183
+ return {
184
+ id: generateUuid(),
185
+ timestamp: latest.timestamp,
186
+ workerName,
187
+ metric,
188
+ actual: latest.value,
189
+ expected: stats.mean,
190
+ deviation: zScore,
191
+ confidence,
192
+ severity: selectSeverity(zScore),
193
+ possibleCauses: buildPossibleCauses(metric),
194
+ recommendations: buildRecommendations(metric),
195
+ };
196
+ }));
197
+ return results.filter((item) => item !== null);
198
+ },
199
+ /**
200
+ * Predict failure risk for a worker
201
+ */
202
+ async predictFailure(workerName, horizonHours) {
203
+ ensureConfig(workerName);
204
+ const range = {
205
+ start: new Date(Date.now() - 24 * 60 * 60 * 1000),
206
+ end: new Date(),
207
+ };
208
+ const [errors, processed] = await Promise.all([
209
+ WorkerMetrics.aggregate({
210
+ workerName,
211
+ metricType: 'errors',
212
+ granularity: 'hourly',
213
+ startDate: range.start,
214
+ endDate: range.end,
215
+ }),
216
+ WorkerMetrics.aggregate({
217
+ workerName,
218
+ metricType: 'processed',
219
+ granularity: 'hourly',
220
+ startDate: range.start,
221
+ endDate: range.end,
222
+ }),
223
+ ]);
224
+ const errorRate = processed.total > 0 ? errors.total / processed.total : 0;
225
+ const riskScore = Math.min(1, errorRate * 5);
226
+ let summary = 'Low failure risk detected';
227
+ if (riskScore >= 0.8) {
228
+ summary = 'High failure risk detected';
229
+ }
230
+ else if (riskScore >= 0.4) {
231
+ summary = 'Moderate failure risk detected';
232
+ }
233
+ return {
234
+ workerName,
235
+ horizonHours,
236
+ riskScore,
237
+ expectedErrorRate: errorRate,
238
+ summary,
239
+ };
240
+ },
241
+ /**
242
+ * Analyze root cause for an anomaly
243
+ */
244
+ analyzeRootCause(anomaly) {
245
+ const usage = ResourceMonitor.getCurrentUsage(anomaly.workerName);
246
+ const signals = {
247
+ cpu: usage.cpu,
248
+ memory: usage.memory.percent,
249
+ };
250
+ const suspected = [...anomaly.possibleCauses];
251
+ if (usage.cpu > 80)
252
+ suspected.push('CPU saturation');
253
+ if (usage.memory.percent > 80)
254
+ suspected.push('Memory pressure');
255
+ return {
256
+ anomalyId: anomaly.id,
257
+ suspectedCauses: suspected,
258
+ supportingSignals: signals,
259
+ };
260
+ },
261
+ /**
262
+ * Forecast a metric
263
+ */
264
+ async forecastMetric(workerName, metric, hours) {
265
+ ensureConfig(workerName);
266
+ const entry = await WorkerMetrics.query({
267
+ workerName,
268
+ metricType: metric,
269
+ granularity: 'hourly',
270
+ startDate: new Date(Date.now() - 24 * 60 * 60 * 1000),
271
+ endDate: new Date(),
272
+ });
273
+ const values = entry.points.map((point) => point.value);
274
+ const average = values.length > 0 ? values.reduce((sum, v) => sum + v, 0) / values.length : 0;
275
+ return {
276
+ workerName,
277
+ metric,
278
+ horizonHours: hours,
279
+ forecast: average,
280
+ confidence: values.length > 10 ? 0.7 : 0.4,
281
+ };
282
+ },
283
+ /**
284
+ * Generate recommendations for an anomaly
285
+ */
286
+ getRecommendations(anomaly) {
287
+ return anomaly.recommendations.map((rec) => ({
288
+ action: rec,
289
+ reason: `Metric ${anomaly.metric} deviated from baseline`,
290
+ priority: anomaly.severity === 'critical' ? 'high' : 'medium',
291
+ }));
292
+ },
293
+ /**
294
+ * Attempt auto-remediation
295
+ */
296
+ autoRemediate(_anomaly) {
297
+ return false;
298
+ },
299
+ /**
300
+ * Helper: build training data from metrics
301
+ */
302
+ async buildTrainingData(workerName) {
303
+ const config = ensureConfig(workerName);
304
+ const range = {
305
+ start: new Date(Date.now() - config.learningPeriod * 24 * 60 * 60 * 1000),
306
+ end: new Date(),
307
+ };
308
+ const batches = await Promise.all(config.metrics.map(async (metric) => {
309
+ const entry = await WorkerMetrics.query({
310
+ workerName,
311
+ metricType: metric,
312
+ granularity: 'daily',
313
+ startDate: range.start,
314
+ endDate: range.end,
315
+ });
316
+ return mapPoints(metric, entry.points);
317
+ }));
318
+ return batches.flat();
319
+ },
320
+ });
321
+ export default AnomalyDetection;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Worker Auto-Scaler
3
+ * Automatic worker scaling based on queue depth, resource usage, and cost optimization
4
+ * Sealed namespace for immutability
5
+ */
6
+ export type ScalingDecision = {
7
+ workerName: string;
8
+ action: 'scale-up' | 'scale-down' | 'no-change';
9
+ currentConcurrency: number;
10
+ targetConcurrency: number;
11
+ reason: string;
12
+ metrics: {
13
+ queueDepth: number;
14
+ avgProcessingTime: number;
15
+ cpuUsage: number;
16
+ memoryUsage: number;
17
+ errorRate: number;
18
+ costPerHour: number;
19
+ };
20
+ timestamp: Date;
21
+ };
22
+ export type ScalingPolicy = {
23
+ minConcurrency: number;
24
+ maxConcurrency: number;
25
+ scaleUpThreshold: {
26
+ queueDepth: number;
27
+ cpuUsage: number;
28
+ memoryUsage: number;
29
+ };
30
+ scaleDownThreshold: {
31
+ queueDepth: number;
32
+ cpuUsage: number;
33
+ memoryUsage: number;
34
+ };
35
+ cooldownPeriod: number;
36
+ aggressiveness: 'conservative' | 'moderate' | 'aggressive';
37
+ };
38
+ export type CostOptimizationStrategy = {
39
+ enabled: boolean;
40
+ maxCostPerHour: number;
41
+ preferSpotInstances: boolean;
42
+ offPeakSchedule?: {
43
+ start: string;
44
+ end: string;
45
+ timezone: string;
46
+ reductionPercentage: number;
47
+ };
48
+ budgetAlerts: {
49
+ dailyLimit: number;
50
+ weeklyLimit: number;
51
+ monthlyLimit: number;
52
+ };
53
+ };
54
+ export type AutoScalerConfig = {
55
+ enabled: boolean;
56
+ checkInterval: number;
57
+ scalingPolicies: Map<string, ScalingPolicy>;
58
+ costOptimization: CostOptimizationStrategy;
59
+ };
60
+ /**
61
+ * Worker Auto-Scaler - Sealed namespace
62
+ */
63
+ export declare const AutoScaler: Readonly<{
64
+ /**
65
+ * Initialize auto-scaler with configuration
66
+ */
67
+ initialize(autoScalerConfig: AutoScalerConfig): void;
68
+ /**
69
+ * Start auto-scaling checks
70
+ */
71
+ start(): void;
72
+ /**
73
+ * Stop auto-scaling checks
74
+ */
75
+ stop(): void;
76
+ /**
77
+ * Evaluate scaling decision for a worker
78
+ */
79
+ evaluate(workerName: string, metrics: ScalingDecision["metrics"]): ScalingDecision;
80
+ /**
81
+ * Get last scaling decision
82
+ */
83
+ getLastDecision(workerName: string): ScalingDecision | null;
84
+ /**
85
+ * Get scaling history
86
+ */
87
+ getHistory(workerName: string, limit?: number): ReadonlyArray<ScalingDecision>;
88
+ /**
89
+ * Clear scaling history for a worker
90
+ */
91
+ clearHistory(workerName: string): void;
92
+ /**
93
+ * Get cost summary
94
+ */
95
+ getCostSummary(): {
96
+ currentHourlyCost: number;
97
+ dailyCost: number;
98
+ weeklyCost: number;
99
+ monthlyCost: number;
100
+ budgetLimits: CostOptimizationStrategy["budgetAlerts"];
101
+ utilizationPercentage: {
102
+ daily: number;
103
+ weekly: number;
104
+ monthly: number;
105
+ };
106
+ };
107
+ /**
108
+ * Set scaling policy for a worker
109
+ */
110
+ setScalingPolicy(workerName: string, policy: ScalingPolicy): void;
111
+ /**
112
+ * Get scaling policy for a worker
113
+ */
114
+ getScalingPolicy(workerName: string): ScalingPolicy | null;
115
+ /**
116
+ * Check if currently in off-peak period
117
+ */
118
+ isOffPeak(): boolean;
119
+ /**
120
+ * Get configuration
121
+ */
122
+ getConfig(): AutoScalerConfig | null;
123
+ /**
124
+ * Shutdown
125
+ */
126
+ shutdown(): void;
127
+ }>;