beddel 0.1.0

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 (236) hide show
  1. package/README.md +297 -0
  2. package/dist/agents/agentRegistry.d.ts +68 -0
  3. package/dist/agents/agentRegistry.d.ts.map +1 -0
  4. package/dist/agents/agentRegistry.js +222 -0
  5. package/dist/agents/agentRegistry.js.map +1 -0
  6. package/dist/agents/formatter-agent.d.ts +10 -0
  7. package/dist/agents/formatter-agent.d.ts.map +1 -0
  8. package/dist/agents/formatter-agent.js +49 -0
  9. package/dist/agents/formatter-agent.js.map +1 -0
  10. package/dist/agents/genkit-agent.d.ts +12 -0
  11. package/dist/agents/genkit-agent.d.ts.map +1 -0
  12. package/dist/agents/genkit-agent.js +119 -0
  13. package/dist/agents/genkit-agent.js.map +1 -0
  14. package/dist/agents/i18n-messages.d.ts +17 -0
  15. package/dist/agents/i18n-messages.d.ts.map +1 -0
  16. package/dist/agents/i18n-messages.js +92 -0
  17. package/dist/agents/i18n-messages.js.map +1 -0
  18. package/dist/agents/index.d.ts +10 -0
  19. package/dist/agents/index.d.ts.map +1 -0
  20. package/dist/agents/index.js +26 -0
  21. package/dist/agents/index.js.map +1 -0
  22. package/dist/agents/pipeline.d.ts +15 -0
  23. package/dist/agents/pipeline.d.ts.map +1 -0
  24. package/dist/agents/pipeline.js +45 -0
  25. package/dist/agents/pipeline.js.map +1 -0
  26. package/dist/agents/schema-factory.d.ts +40 -0
  27. package/dist/agents/schema-factory.d.ts.map +1 -0
  28. package/dist/agents/schema-factory.js +121 -0
  29. package/dist/agents/schema-factory.js.map +1 -0
  30. package/dist/agents/translation-validators.d.ts +26 -0
  31. package/dist/agents/translation-validators.d.ts.map +1 -0
  32. package/dist/agents/translation-validators.js +77 -0
  33. package/dist/agents/translation-validators.js.map +1 -0
  34. package/dist/agents/translator-agents.d.ts +184 -0
  35. package/dist/agents/translator-agents.d.ts.map +1 -0
  36. package/dist/agents/translator-agents.js +613 -0
  37. package/dist/agents/translator-agents.js.map +1 -0
  38. package/dist/agents/types/translation.types.d.ts +100 -0
  39. package/dist/agents/types/translation.types.d.ts.map +1 -0
  40. package/dist/agents/types/translation.types.js +3 -0
  41. package/dist/agents/types/translation.types.js.map +1 -0
  42. package/dist/agents/validator-agent.d.ts +42 -0
  43. package/dist/agents/validator-agent.d.ts.map +1 -0
  44. package/dist/agents/validator-agent.js +122 -0
  45. package/dist/agents/validator-agent.js.map +1 -0
  46. package/dist/audit/auditTrail.d.ts +55 -0
  47. package/dist/audit/auditTrail.d.ts.map +1 -0
  48. package/dist/audit/auditTrail.js +93 -0
  49. package/dist/audit/auditTrail.js.map +1 -0
  50. package/dist/compliance/gdprEngine.d.ts +44 -0
  51. package/dist/compliance/gdprEngine.d.ts.map +1 -0
  52. package/dist/compliance/gdprEngine.js +178 -0
  53. package/dist/compliance/gdprEngine.js.map +1 -0
  54. package/dist/compliance/lgpdEngine.d.ts +51 -0
  55. package/dist/compliance/lgpdEngine.d.ts.map +1 -0
  56. package/dist/compliance/lgpdEngine.js +221 -0
  57. package/dist/compliance/lgpdEngine.js.map +1 -0
  58. package/dist/config.d.ts +78 -0
  59. package/dist/config.d.ts.map +1 -0
  60. package/dist/config.js +77 -0
  61. package/dist/config.js.map +1 -0
  62. package/dist/errors.d.ts +17 -0
  63. package/dist/errors.d.ts.map +1 -0
  64. package/dist/errors.js +40 -0
  65. package/dist/errors.js.map +1 -0
  66. package/dist/firebase/tenantManager.d.ts +84 -0
  67. package/dist/firebase/tenantManager.d.ts.map +1 -0
  68. package/dist/firebase/tenantManager.js +378 -0
  69. package/dist/firebase/tenantManager.js.map +1 -0
  70. package/dist/index.d.ts +36 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +118 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/integration/secure-yaml-runtime.d.ts +68 -0
  75. package/dist/integration/secure-yaml-runtime.d.ts.map +1 -0
  76. package/dist/integration/secure-yaml-runtime.js +245 -0
  77. package/dist/integration/secure-yaml-runtime.js.map +1 -0
  78. package/dist/parser/secure-yaml-parser.d.ts +62 -0
  79. package/dist/parser/secure-yaml-parser.d.ts.map +1 -0
  80. package/dist/parser/secure-yaml-parser.js +234 -0
  81. package/dist/parser/secure-yaml-parser.js.map +1 -0
  82. package/dist/performance/autoscaling.d.ts +100 -0
  83. package/dist/performance/autoscaling.d.ts.map +1 -0
  84. package/dist/performance/autoscaling.js +339 -0
  85. package/dist/performance/autoscaling.js.map +1 -0
  86. package/dist/performance/benchmark.d.ts +104 -0
  87. package/dist/performance/benchmark.d.ts.map +1 -0
  88. package/dist/performance/benchmark.js +514 -0
  89. package/dist/performance/benchmark.js.map +1 -0
  90. package/dist/performance/index.d.ts +14 -0
  91. package/dist/performance/index.d.ts.map +1 -0
  92. package/dist/performance/index.js +35 -0
  93. package/dist/performance/index.js.map +1 -0
  94. package/dist/performance/monitor.d.ts +126 -0
  95. package/dist/performance/monitor.d.ts.map +1 -0
  96. package/dist/performance/monitor.js +324 -0
  97. package/dist/performance/monitor.js.map +1 -0
  98. package/dist/performance/streaming.d.ts +82 -0
  99. package/dist/performance/streaming.d.ts.map +1 -0
  100. package/dist/performance/streaming.js +287 -0
  101. package/dist/performance/streaming.js.map +1 -0
  102. package/dist/runtime/audit.d.ts +240 -0
  103. package/dist/runtime/audit.d.ts.map +1 -0
  104. package/dist/runtime/audit.js +641 -0
  105. package/dist/runtime/audit.js.map +1 -0
  106. package/dist/runtime/declarativeAgentRuntime.d.ts +123 -0
  107. package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -0
  108. package/dist/runtime/declarativeAgentRuntime.js +576 -0
  109. package/dist/runtime/declarativeAgentRuntime.js.map +1 -0
  110. package/dist/runtime/isolatedRuntime.d.ts +119 -0
  111. package/dist/runtime/isolatedRuntime.d.ts.map +1 -0
  112. package/dist/runtime/isolatedRuntime.js +425 -0
  113. package/dist/runtime/isolatedRuntime.js.map +1 -0
  114. package/dist/runtime/schemaCompiler.d.ts +35 -0
  115. package/dist/runtime/schemaCompiler.d.ts.map +1 -0
  116. package/dist/runtime/schemaCompiler.js +151 -0
  117. package/dist/runtime/schemaCompiler.js.map +1 -0
  118. package/dist/runtime/simpleRuntime.d.ts +57 -0
  119. package/dist/runtime/simpleRuntime.d.ts.map +1 -0
  120. package/dist/runtime/simpleRuntime.js +187 -0
  121. package/dist/runtime/simpleRuntime.js.map +1 -0
  122. package/dist/security/dashboard.d.ts +89 -0
  123. package/dist/security/dashboard.d.ts.map +1 -0
  124. package/dist/security/dashboard.js +300 -0
  125. package/dist/security/dashboard.js.map +1 -0
  126. package/dist/security/hardening.d.ts +130 -0
  127. package/dist/security/hardening.d.ts.map +1 -0
  128. package/dist/security/hardening.js +414 -0
  129. package/dist/security/hardening.js.map +1 -0
  130. package/dist/security/index.d.ts +128 -0
  131. package/dist/security/index.d.ts.map +1 -0
  132. package/dist/security/index.js +353 -0
  133. package/dist/security/index.js.map +1 -0
  134. package/dist/security/monitor.d.ts +88 -0
  135. package/dist/security/monitor.d.ts.map +1 -0
  136. package/dist/security/monitor.js +356 -0
  137. package/dist/security/monitor.js.map +1 -0
  138. package/dist/security/scanner.d.ts +104 -0
  139. package/dist/security/scanner.d.ts.map +1 -0
  140. package/dist/security/scanner.js +298 -0
  141. package/dist/security/scanner.js.map +1 -0
  142. package/dist/security/score.d.ts +150 -0
  143. package/dist/security/score.d.ts.map +1 -0
  144. package/dist/security/score.js +983 -0
  145. package/dist/security/score.js.map +1 -0
  146. package/dist/security/test-security.d.ts +22 -0
  147. package/dist/security/test-security.d.ts.map +1 -0
  148. package/dist/security/test-security.js +154 -0
  149. package/dist/security/test-security.js.map +1 -0
  150. package/dist/security/threatDetector.d.ts +39 -0
  151. package/dist/security/threatDetector.d.ts.map +1 -0
  152. package/dist/security/threatDetector.js +354 -0
  153. package/dist/security/threatDetector.js.map +1 -0
  154. package/dist/security/validation.d.ts +69 -0
  155. package/dist/security/validation.d.ts.map +1 -0
  156. package/dist/security/validation.js +286 -0
  157. package/dist/security/validation.js.map +1 -0
  158. package/dist/server/api/clientsRoute.d.ts +9 -0
  159. package/dist/server/api/clientsRoute.d.ts.map +1 -0
  160. package/dist/server/api/clientsRoute.js +71 -0
  161. package/dist/server/api/clientsRoute.js.map +1 -0
  162. package/dist/server/api/endpointsRoute.d.ts +8 -0
  163. package/dist/server/api/endpointsRoute.d.ts.map +1 -0
  164. package/dist/server/api/endpointsRoute.js +76 -0
  165. package/dist/server/api/endpointsRoute.js.map +1 -0
  166. package/dist/server/api/graphql.d.ts +9 -0
  167. package/dist/server/api/graphql.d.ts.map +1 -0
  168. package/dist/server/api/graphql.js +180 -0
  169. package/dist/server/api/graphql.js.map +1 -0
  170. package/dist/server/errors.d.ts +19 -0
  171. package/dist/server/errors.d.ts.map +1 -0
  172. package/dist/server/errors.js +42 -0
  173. package/dist/server/errors.js.map +1 -0
  174. package/dist/server/index.d.ts +7 -0
  175. package/dist/server/index.d.ts.map +1 -0
  176. package/dist/server/index.js +24 -0
  177. package/dist/server/index.js.map +1 -0
  178. package/dist/server/kvStore.d.ts +27 -0
  179. package/dist/server/kvStore.d.ts.map +1 -0
  180. package/dist/server/kvStore.js +128 -0
  181. package/dist/server/kvStore.js.map +1 -0
  182. package/dist/server/runtimeSecurity.d.ts +28 -0
  183. package/dist/server/runtimeSecurity.d.ts.map +1 -0
  184. package/dist/server/runtimeSecurity.js +85 -0
  185. package/dist/server/runtimeSecurity.js.map +1 -0
  186. package/dist/server/types.d.ts +53 -0
  187. package/dist/server/types.d.ts.map +1 -0
  188. package/dist/server/types.js +8 -0
  189. package/dist/server/types.js.map +1 -0
  190. package/dist/types/executionContext.d.ts +16 -0
  191. package/dist/types/executionContext.d.ts.map +1 -0
  192. package/dist/types/executionContext.js +3 -0
  193. package/dist/types/executionContext.js.map +1 -0
  194. package/package.json +77 -0
  195. package/src/agents/agentRegistry.ts +272 -0
  196. package/src/agents/image-agent.yaml +86 -0
  197. package/src/agents/joker-agent.yaml +47 -0
  198. package/src/agents/translator-agent.yaml +80 -0
  199. package/src/audit/auditTrail.ts +134 -0
  200. package/src/compliance/gdprEngine.ts +209 -0
  201. package/src/compliance/lgpdEngine.ts +268 -0
  202. package/src/config.ts +179 -0
  203. package/src/errors.ts +35 -0
  204. package/src/firebase/tenantManager.ts +443 -0
  205. package/src/index.ts +125 -0
  206. package/src/integration/secure-yaml-runtime.ts +341 -0
  207. package/src/parser/secure-yaml-parser.ts +273 -0
  208. package/src/performance/autoscaling.ts +495 -0
  209. package/src/performance/benchmark.ts +644 -0
  210. package/src/performance/index.ts +34 -0
  211. package/src/performance/monitor.ts +469 -0
  212. package/src/performance/streaming.ts +317 -0
  213. package/src/runtime/audit.ts +907 -0
  214. package/src/runtime/declarativeAgentRuntime.ts +836 -0
  215. package/src/runtime/isolatedRuntime.ts +572 -0
  216. package/src/runtime/schemaCompiler.ts +228 -0
  217. package/src/runtime/simpleRuntime.ts +201 -0
  218. package/src/security/dashboard.ts +462 -0
  219. package/src/security/hardening.ts +560 -0
  220. package/src/security/index.ts +439 -0
  221. package/src/security/monitor.ts +490 -0
  222. package/src/security/scanner.ts +368 -0
  223. package/src/security/score.ts +1138 -0
  224. package/src/security/threatDetector.ts +481 -0
  225. package/src/security/validation.ts +365 -0
  226. package/src/server/api/clientsRoute.ts +92 -0
  227. package/src/server/api/endpointsRoute.ts +97 -0
  228. package/src/server/api/graphql.ts +249 -0
  229. package/src/server/errors.ts +38 -0
  230. package/src/server/index.ts +6 -0
  231. package/src/server/kvStore.ts +152 -0
  232. package/src/server/runtimeSecurity.ts +102 -0
  233. package/src/server/types.ts +60 -0
  234. package/src/types/executionContext.ts +16 -0
  235. package/tools/seed.ts +365 -0
  236. package/tools/test-endpoints.ts +174 -0
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Autoscaling System - Dynamic Pool Management
3
+ * Automatically adjusts isolate pool size based on performance metrics
4
+ */
5
+ import { performanceMonitor } from "./monitor";
6
+ import { IsolatedRuntimeManager } from "../runtime/isolatedRuntime";
7
+
8
+ export interface AutoscaleConfig {
9
+ enabled: boolean;
10
+ minPoolSize: number;
11
+ maxPoolSize: number;
12
+ scaleUpThreshold: number; // Scale up if execution time exceeds this
13
+ scaleDownThreshold: number; // Scale down if execution time below this
14
+ scaleInterval: number; // Check interval in ms
15
+ scaleUpFactor: number; // Multiply current size by this when scaling up
16
+ scaleDownFactor: number; // Multiply current size by this when scaling down
17
+ metricsWindow: number; // Window size for metrics analysis in ms
18
+ safetyMargin: number; // Safety factor for scaling decisions
19
+ }
20
+
21
+ export interface AutoscaleDecision {
22
+ action: "scale_up" | "scale_down" | "maintain";
23
+ currentSize: number;
24
+ targetSize: number;
25
+ reason: string;
26
+ timestamp: Date;
27
+ metrics: {
28
+ avgExecutionTime: number;
29
+ avgMemoryUsage: number;
30
+ successRate: number;
31
+ poolUtilization: number;
32
+ };
33
+ }
34
+
35
+ export class AutoscaleSystem {
36
+ private isRunning = false;
37
+ private currentDecision: AutoscaleDecision | null = null;
38
+ private scalingHistory: AutoscaleDecision[] = [];
39
+ private lastScaleTime = 0;
40
+
41
+ private readonly defaultConfig: AutoscaleConfig = {
42
+ enabled: true,
43
+ minPoolSize: 5,
44
+ maxPoolSize: 100,
45
+ scaleUpThreshold: 55, // 55ms - slightly above target
46
+ scaleDownThreshold: 30, // 30ms - comfortable below target
47
+ scaleInterval: 30000, // 30 seconds
48
+ scaleUpFactor: 1.25, // Increase by 25%
49
+ scaleDownFactor: 0.8, // Decrease by 20%
50
+ metricsWindow: 60000, // 1 minute window
51
+ safetyMargin: 1.2, // 20% safety margin
52
+ };
53
+
54
+ constructor(
55
+ private runtimeManager: IsolatedRuntimeManager,
56
+ private config: AutoscaleConfig
57
+ ) {}
58
+
59
+ /**
60
+ * Start autoscaling monitoring
61
+ */
62
+ public start(): void {
63
+ if (this.isRunning) return;
64
+
65
+ this.isRunning = true;
66
+ this.lastScaleTime = Date.now();
67
+
68
+ // Start monitoring loop
69
+ this.monitoringLoop();
70
+ }
71
+
72
+ /**
73
+ * Stop autoscaling monitoring
74
+ */
75
+ public stop(): void {
76
+ this.isRunning = false;
77
+ }
78
+
79
+ /**
80
+ * Main monitoring loop
81
+ */
82
+ private monitoringLoop(): void {
83
+ if (!this.isRunning) return;
84
+
85
+ this.evaluateScalingDecision()
86
+ .then((decision) => {
87
+ if (decision.action !== "maintain") {
88
+ this.executeScalingDecision(decision);
89
+ }
90
+
91
+ this.currentDecision = decision;
92
+ this.scalingHistory.push(decision);
93
+
94
+ // Keep only last 100 decisions
95
+ if (this.scalingHistory.length > 100) {
96
+ this.scalingHistory.shift();
97
+ }
98
+ })
99
+ .catch((error) => {
100
+ console.error("Autoscaling evaluation error:", error);
101
+ });
102
+
103
+ // Schedule next evaluation
104
+ setTimeout(() => this.monitoringLoop(), this.config.scaleInterval);
105
+ }
106
+
107
+ /**
108
+ * Evaluate scaling decision based on current metrics
109
+ */
110
+ private async evaluateScalingDecision(): Promise<AutoscaleDecision> {
111
+ const currentPoolStats = this.runtimeManager.getPoolStats();
112
+ const performanceSnapshot = performanceMonitor.getSnapshot();
113
+
114
+ const recentMetricsWindow = performanceMonitor.getStats(
115
+ "executionTime",
116
+ this.config.metricsWindow
117
+ );
118
+
119
+ // Calculate current average metrics
120
+ const avgExecutionTime = recentMetricsWindow.average;
121
+ const successRate = performanceSnapshot.averages["successRate"] || 99.9;
122
+ const avgMemoryUsage = performanceSnapshot.averages["memoryUsage"] || 2.0;
123
+
124
+ // Calculate current pool utilization
125
+ const totalIsolates = currentPoolStats.totalIsolates;
126
+ const activeExecutions = currentPoolStats.activeExecutions;
127
+ const poolUtilization = activeExecutions / totalIsolates || 0;
128
+
129
+ const currentSize = totalIsolates;
130
+ let targetSize = currentSize;
131
+ let action: "scale_up" | "scale_down" | "maintain" = "maintain";
132
+ let reason = "Performance within acceptable ranges";
133
+
134
+ const now = Date.now();
135
+
136
+ // Prevent frequent scaling (rate limiting)
137
+ if (now - this.lastScaleTime < this.config.scaleInterval / 2) {
138
+ return {
139
+ action: "maintain",
140
+ currentSize,
141
+ targetSize: currentSize,
142
+ reason: "Rate limiting in effect",
143
+ timestamp: new Date(now),
144
+ metrics: {
145
+ avgExecutionTime,
146
+ avgMemoryUsage,
147
+ successRate,
148
+ poolUtilization,
149
+ },
150
+ };
151
+ }
152
+
153
+ // High memory usage detection
154
+ if (avgMemoryUsage > 5.0) {
155
+ // >5MB average usage
156
+ action = "scale_up";
157
+ targetSize = Math.min(
158
+ this.config.maxPoolSize,
159
+ Math.max(currentSize * this.config.safetyMargin, currentSize + 2)
160
+ );
161
+ reason = `High memory usage detected (${avgMemoryUsage.toFixed(
162
+ 1
163
+ )}MB avg)`;
164
+ }
165
+ // Long execution time detection
166
+ else if (
167
+ avgExecutionTime >
168
+ this.config.scaleUpThreshold * this.config.safetyMargin
169
+ ) {
170
+ action = "scale_up";
171
+ targetSize = Math.min(
172
+ this.config.maxPoolSize,
173
+ Math.ceil(currentSize * this.config.scaleUpFactor)
174
+ );
175
+ reason = `Execution time exceed threshold (${avgExecutionTime.toFixed(
176
+ 1
177
+ )}ms > ${this.config.scaleUpThreshold}ms)`;
178
+ }
179
+ // High pool utilization detection
180
+ else if (poolUtilization > 0.8) {
181
+ action = "scale_up";
182
+ targetSize = Math.min(
183
+ this.config.maxPoolSize,
184
+ Math.ceil(currentSize * this.config.scaleUpFactor)
185
+ );
186
+ reason = `High pool utilization (${(poolUtilization * 100).toFixed(1)}%)`;
187
+ }
188
+ // Low pool utilization and fast execution
189
+ else if (
190
+ avgExecutionTime < this.config.scaleDownThreshold &&
191
+ poolUtilization < 0.3 &&
192
+ currentSize > this.config.minPoolSize * 2
193
+ ) {
194
+ action = "scale_down";
195
+ targetSize = Math.max(
196
+ this.config.minPoolSize,
197
+ Math.ceil(currentSize * this.config.scaleDownFactor)
198
+ );
199
+ reason = `Low utilization and fast execution (${avgExecutionTime.toFixed(
200
+ 1
201
+ )}ms < ${this.config.scaleDownThreshold}ms)`;
202
+ }
203
+
204
+ // Ensure targetSize is within bounds
205
+ targetSize = Math.max(this.config.minPoolSize, targetSize);
206
+ targetSize = Math.min(this.config.maxPoolSize, targetSize);
207
+
208
+ // If action is to scale but targetSize equals currentSize, maintain current size
209
+ if (action !== "maintain" && targetSize === currentSize) {
210
+ action = "maintain";
211
+ reason = "Target size equals current size";
212
+ }
213
+
214
+ return {
215
+ action,
216
+ currentSize,
217
+ targetSize,
218
+ reason,
219
+ timestamp: new Date(now),
220
+ metrics: {
221
+ avgExecutionTime,
222
+ avgMemoryUsage,
223
+ successRate,
224
+ poolUtilization,
225
+ },
226
+ };
227
+ }
228
+
229
+ /**
230
+ * Execute scaling decision
231
+ */
232
+ private executeScalingDecision(decision: AutoscaleDecision): void {
233
+ if (!this.config.enabled) return;
234
+
235
+ const currentTime = Date.now();
236
+ const timeSinceLastScale = currentTime - this.lastScaleTime;
237
+
238
+ // Additional safety check for scaling frequency
239
+ if (timeSinceLastScale < this.config.scaleInterval / 3) {
240
+ return; // Too soon to scale again
241
+ }
242
+
243
+ console.log(
244
+ `[AUTOSCALE] ${decision.action.toUpperCase()}: Current: ${
245
+ decision.currentSize
246
+ } -> Target: ${decision.targetSize}`
247
+ );
248
+ console.log(`[AUTOSCALE] Reason: ${decision.reason}`);
249
+ console.log(
250
+ `[AUTOSCALE] Metrics: Execution=${decision.metrics.avgExecutionTime.toFixed(
251
+ 1
252
+ )}ms, Memory=${decision.metrics.avgMemoryUsage.toFixed(
253
+ 1
254
+ )}MB, Utilization=${decision.metrics.poolUtilization.toFixed(1)}`
255
+ );
256
+
257
+ if (decision.action === "scale_up") {
258
+ this.scaleUp(decision.targetSize);
259
+ } else if (decision.action === "scale_down") {
260
+ this.scaleDown(decision.targetSize);
261
+ }
262
+
263
+ this.lastScaleTime = currentTime;
264
+ }
265
+
266
+ /**
267
+ * Scale up pool size
268
+ */
269
+ private scaleUp(targetSize: number): void {
270
+ const currentStats = this.runtimeManager.getPoolStats();
271
+ const currentSize = currentStats.totalIsolates;
272
+
273
+ // Validate scaling decisions
274
+ if (targetSize < currentSize || targetSize > this.config.maxPoolSize) {
275
+ console.warn(
276
+ `[AUTOSCALE] Invalid scale-up target: ${targetSize} (current: ${currentSize}, max: ${this.config.maxPoolSize})`
277
+ );
278
+ return;
279
+ }
280
+
281
+ // Pool scaling is handled by the runtime manager
282
+ console.log(`[AUTOSCALE] Scaling up from ${currentSize} to ${targetSize}`);
283
+
284
+ // The actual pool scaling would be implemented in the IsolatedRuntimeManager
285
+ // For now, we log the intention
286
+ console.log(
287
+ `[AUTOSCALE EVENT] scale_up from: ${currentSize}, to: ${targetSize}`
288
+ );
289
+ // Pool scaling logic would go here
290
+ }
291
+
292
+ /**
293
+ * Scale down pool size
294
+ */
295
+ private scaleDown(targetSize: number): void {
296
+ const currentStats = this.runtimeManager.getPoolStats();
297
+ const currentSize = currentStats.totalIsolates;
298
+
299
+ // Validate scaling decisions
300
+ if (targetSize > currentSize || targetSize < this.config.minPoolSize) {
301
+ console.warn(
302
+ `[AUTOSCALE] Invalid scale-down target: ${targetSize} (current: ${currentSize}, min: ${this.config.minPoolSize})`
303
+ );
304
+ return;
305
+ }
306
+
307
+ console.log(
308
+ `[AUTOSCALE] Scaling down from ${currentSize} to ${targetSize}`
309
+ );
310
+
311
+ console.log(
312
+ `[AUTOSCALE] scale_down from: ${currentSize}, to: ${targetSize}`
313
+ );
314
+ // Pool scaling logic would go here
315
+ }
316
+
317
+ /**
318
+ * Get current autoscaling status
319
+ */
320
+ public getStatus(): {
321
+ isRunning: boolean;
322
+ currentDecision: AutoscaleDecision | null;
323
+ lastScaleTime: Date;
324
+ scalingHistory: AutoscaleDecision[];
325
+ config: AutoscaleConfig;
326
+ } {
327
+ return {
328
+ isRunning: this.isRunning,
329
+ currentDecision: this.currentDecision,
330
+ lastScaleTime: new Date(this.lastScaleTime),
331
+ scalingHistory: [...this.scalingHistory],
332
+ config: { ...this.config },
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Update autoscaling configuration
338
+ */
339
+ public updateConfig(newConfig: Partial<AutoscaleConfig>): void {
340
+ this.config = { ...this.config, ...newConfig };
341
+ console.log("[AUTOSCALE] Configuration updated");
342
+ }
343
+
344
+ /**
345
+ * Get scaling recommendations
346
+ */
347
+ public getRecommendations(): string[] {
348
+ const snapshot = performanceMonitor.getSnapshot();
349
+ const alerts = performanceMonitor.getAlerts(); // Use proper method
350
+ const currentStats = this.getCurrentStats();
351
+
352
+ const recommendations: string[] = [];
353
+
354
+ // High execution time recommendation
355
+ if (currentStats.avgExecutionTime > this.config.scaleUpThreshold) {
356
+ recommendations.push(
357
+ `Execution time (${currentStats.avgExecutionTime.toFixed(
358
+ 1
359
+ )}ms) exceeds scale-up threshold (${
360
+ this.config.scaleUpThreshold
361
+ }ms). Consider scaling up.`
362
+ );
363
+ }
364
+
365
+ // Memory usage recommendation
366
+ if (currentStats.avgMemoryUsage > 3.0) {
367
+ recommendations.push(
368
+ `High memory usage detected (${currentStats.avgMemoryUsage.toFixed(
369
+ 1
370
+ )}MB). Review memory patterns and consider scaling adjustments.`
371
+ );
372
+ }
373
+
374
+ // Critical violation recommendation
375
+ if (alerts.criticals.length > 5) {
376
+ recommendations.push(
377
+ `Multiple critical violations detected (${alerts.criticals.length}). Immediate attention recommended.`
378
+ );
379
+ }
380
+
381
+ return recommendations;
382
+ }
383
+
384
+ /**
385
+ * Get current performance stats for scaling decisions
386
+ */
387
+ private getCurrentStats(): {
388
+ avgExecutionTime: number;
389
+ avgMemoryUsage: number;
390
+ successRate: number;
391
+ } {
392
+ const snapshot = performanceMonitor.getSnapshot();
393
+ return {
394
+ avgExecutionTime: snapshot.averages["executionTime"] || 50,
395
+ avgMemoryUsage: snapshot.averages["memoryUsage"] || 2,
396
+ successRate: snapshot.averages["successRate"] || 99.9,
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Predict optimal pool size based on current metrics
402
+ */
403
+ public predictOptimalPoolSize(): {
404
+ recommended: number;
405
+ current: number;
406
+ confidence: "high" | "medium" | "low";
407
+ factors: string[];
408
+ } {
409
+ const currentStats = this.runtimeManager.getPoolStats();
410
+ const currentSize = currentStats.totalIsolates;
411
+
412
+ const snapshot = performanceMonitor.getSnapshot();
413
+ const avgExecutionTime = snapshot.averages["executionTime"] || 50;
414
+ const poolUtilization = currentStats.activeExecutions / currentSize || 0;
415
+
416
+ let recommended = currentSize;
417
+ let confidence: "high" | "medium" | "low" = "medium";
418
+ const factors: string[] = [];
419
+
420
+ // Performance-based recommendation
421
+ if (avgExecutionTime > this.config.scaleUpThreshold * 2) {
422
+ recommended = Math.ceil(currentSize * 1.5);
423
+ confidence = "high";
424
+ factors.push(`High execution time (${avgExecutionTime.toFixed(1)}ms)`);
425
+ } else if (avgExecutionTime < this.config.scaleDownThreshold / 2) {
426
+ recommended = Math.max(
427
+ this.config.minPoolSize,
428
+ Math.floor(currentSize * 0.7)
429
+ );
430
+ factors.push(`Low execution time (${avgExecutionTime.toFixed(1)}ms)`);
431
+ }
432
+
433
+ // Utilization-based recommendation
434
+ if (poolUtilization > 0.9) {
435
+ recommended = Math.ceil(recommended * 1.2);
436
+ confidence = "high";
437
+ factors.push(
438
+ `High pool utilization (${(poolUtilization * 100).toFixed(1)}%)`
439
+ );
440
+ } else if (poolUtilization < 0.2) {
441
+ recommended = Math.floor(recommended * 0.8);
442
+ factors.push(
443
+ `Low pool utilization (${(poolUtilization * 100).toFixed(1)}%)`
444
+ );
445
+ }
446
+
447
+ // Ensure bounds
448
+ recommended = Math.max(this.config.minPoolSize, recommended);
449
+ recommended = Math.min(this.config.maxPoolSize, recommended);
450
+
451
+ return {
452
+ recommended,
453
+ current: currentSize,
454
+ confidence,
455
+ factors,
456
+ };
457
+ }
458
+ }
459
+
460
+ // Global autoscaling instance
461
+ export let autoscaleSystem: AutoscaleSystem | null = null;
462
+
463
+ export function initializeAutoscaling(
464
+ runtimeManager: IsolatedRuntimeManager,
465
+ config?: Partial<AutoscaleConfig>
466
+ ): AutoscaleSystem {
467
+ const baseConfig: AutoscaleConfig = {
468
+ enabled: true,
469
+ minPoolSize: 5,
470
+ maxPoolSize: 100,
471
+ scaleUpThreshold: 55,
472
+ scaleDownThreshold: 30,
473
+ scaleInterval: 30000,
474
+ scaleUpFactor: 1.25,
475
+ scaleDownFactor: 0.8,
476
+ metricsWindow: 60000,
477
+ safetyMargin: 1.2,
478
+ };
479
+
480
+ // Merge with default config
481
+ const mergedConfig: AutoscaleConfig = {
482
+ ...baseConfig,
483
+ ...config,
484
+ };
485
+
486
+ autoscaleSystem = new AutoscaleSystem(runtimeManager, mergedConfig);
487
+ return autoscaleSystem;
488
+ }
489
+
490
+ // Make config accessible
491
+ export function getAutoscalingConfig(): AutoscaleConfig | null {
492
+ return autoscaleSystem ? autoscaleSystem.getStatus().config : null;
493
+ }
494
+
495
+ export default AutoscaleSystem;