@soulcraft/brainy 0.53.0 → 0.54.1

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.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Adaptive Backpressure System
3
+ * Automatically manages request flow and prevents system overload
4
+ * Self-healing with pattern learning for optimal throughput
5
+ */
6
+ import { createModuleLogger } from './logger.js';
7
+ /**
8
+ * Self-healing backpressure manager that learns from load patterns
9
+ */
10
+ export class AdaptiveBackpressure {
11
+ constructor() {
12
+ this.logger = createModuleLogger('AdaptiveBackpressure');
13
+ // Queue management
14
+ this.queue = [];
15
+ // Active operations tracking
16
+ this.activeOperations = new Set();
17
+ this.maxConcurrent = 100;
18
+ // Metrics tracking
19
+ this.metrics = {
20
+ queueDepth: 0,
21
+ processingRate: 0,
22
+ errorRate: 0,
23
+ latency: 0,
24
+ throughput: 0
25
+ };
26
+ // Configuration that adapts over time
27
+ this.config = {
28
+ maxQueueDepth: 1000,
29
+ targetLatency: 1000, // 1 second target
30
+ minThroughput: 10, // Minimum 10 ops/sec
31
+ adaptationRate: 0.1 // How quickly to adapt
32
+ };
33
+ // Historical patterns for learning
34
+ this.patterns = [];
35
+ // Circuit breaker state
36
+ this.circuitState = 'closed';
37
+ this.circuitOpenTime = 0;
38
+ this.circuitFailures = 0;
39
+ this.circuitThreshold = 5;
40
+ this.circuitTimeout = 30000; // 30 seconds
41
+ // Performance tracking
42
+ this.operationTimes = new Map();
43
+ this.completedOps = [];
44
+ this.errorOps = 0;
45
+ this.lastAdaptation = Date.now();
46
+ }
47
+ /**
48
+ * Request permission to proceed with an operation
49
+ */
50
+ async requestPermission(operationId, priority = 1) {
51
+ // Check circuit breaker
52
+ if (this.isCircuitOpen()) {
53
+ throw new Error('Circuit breaker is open - system is recovering');
54
+ }
55
+ // Fast path for low load
56
+ if (this.activeOperations.size < this.maxConcurrent * 0.5 && this.queue.length === 0) {
57
+ this.activeOperations.add(operationId);
58
+ this.operationTimes.set(operationId, Date.now());
59
+ return;
60
+ }
61
+ // Check if we need to queue
62
+ if (this.activeOperations.size >= this.maxConcurrent) {
63
+ // Check queue depth
64
+ if (this.queue.length >= this.config.maxQueueDepth) {
65
+ throw new Error('Backpressure queue is full - try again later');
66
+ }
67
+ // Add to queue and wait
68
+ return new Promise((resolve) => {
69
+ this.queue.push({
70
+ id: operationId,
71
+ priority,
72
+ timestamp: Date.now(),
73
+ resolve
74
+ });
75
+ // Sort queue by priority (higher priority first)
76
+ this.queue.sort((a, b) => b.priority - a.priority);
77
+ // Update metrics
78
+ this.metrics.queueDepth = this.queue.length;
79
+ });
80
+ }
81
+ // Add to active operations
82
+ this.activeOperations.add(operationId);
83
+ this.operationTimes.set(operationId, Date.now());
84
+ }
85
+ /**
86
+ * Release permission after operation completes
87
+ */
88
+ releasePermission(operationId, success = true) {
89
+ // Remove from active operations
90
+ this.activeOperations.delete(operationId);
91
+ // Track completion time
92
+ const startTime = this.operationTimes.get(operationId);
93
+ if (startTime) {
94
+ const duration = Date.now() - startTime;
95
+ this.completedOps.push(duration);
96
+ this.operationTimes.delete(operationId);
97
+ // Keep array bounded
98
+ if (this.completedOps.length > 1000) {
99
+ this.completedOps = this.completedOps.slice(-500);
100
+ }
101
+ }
102
+ // Track errors for circuit breaker
103
+ if (!success) {
104
+ this.errorOps++;
105
+ this.circuitFailures++;
106
+ // Check if we should open circuit
107
+ if (this.circuitFailures >= this.circuitThreshold) {
108
+ this.openCircuit();
109
+ }
110
+ }
111
+ else {
112
+ // Reset circuit failures on success
113
+ if (this.circuitState === 'half-open') {
114
+ this.closeCircuit();
115
+ }
116
+ }
117
+ // Process queue if there are waiting operations
118
+ if (this.queue.length > 0 && this.activeOperations.size < this.maxConcurrent) {
119
+ const next = this.queue.shift();
120
+ if (next) {
121
+ this.activeOperations.add(next.id);
122
+ this.operationTimes.set(next.id, Date.now());
123
+ next.resolve();
124
+ // Update metrics
125
+ this.metrics.queueDepth = this.queue.length;
126
+ }
127
+ }
128
+ // Adapt configuration periodically
129
+ this.adaptIfNeeded();
130
+ }
131
+ /**
132
+ * Check if circuit breaker is open
133
+ */
134
+ isCircuitOpen() {
135
+ if (this.circuitState === 'open') {
136
+ // Check if timeout has passed
137
+ if (Date.now() - this.circuitOpenTime > this.circuitTimeout) {
138
+ this.circuitState = 'half-open';
139
+ this.logger.info('Circuit breaker entering half-open state');
140
+ return false;
141
+ }
142
+ return true;
143
+ }
144
+ return false;
145
+ }
146
+ /**
147
+ * Open the circuit breaker
148
+ */
149
+ openCircuit() {
150
+ if (this.circuitState !== 'open') {
151
+ this.circuitState = 'open';
152
+ this.circuitOpenTime = Date.now();
153
+ this.logger.warn('Circuit breaker opened due to high error rate');
154
+ // Reduce load immediately
155
+ this.maxConcurrent = Math.max(10, Math.floor(this.maxConcurrent * 0.3));
156
+ }
157
+ }
158
+ /**
159
+ * Close the circuit breaker
160
+ */
161
+ closeCircuit() {
162
+ this.circuitState = 'closed';
163
+ this.circuitFailures = 0;
164
+ this.logger.info('Circuit breaker closed - system recovered');
165
+ // Gradually increase capacity
166
+ this.maxConcurrent = Math.min(500, Math.floor(this.maxConcurrent * 1.5));
167
+ }
168
+ /**
169
+ * Adapt configuration based on metrics
170
+ */
171
+ adaptIfNeeded() {
172
+ const now = Date.now();
173
+ if (now - this.lastAdaptation < 5000) { // Adapt every 5 seconds
174
+ return;
175
+ }
176
+ this.lastAdaptation = now;
177
+ this.updateMetrics();
178
+ // Learn from current patterns
179
+ this.learnPattern();
180
+ // Adapt based on metrics
181
+ this.adaptConfiguration();
182
+ }
183
+ /**
184
+ * Update current metrics
185
+ */
186
+ updateMetrics() {
187
+ // Calculate processing rate
188
+ this.metrics.processingRate = this.completedOps.length > 0
189
+ ? 1000 / (this.completedOps.reduce((a, b) => a + b, 0) / this.completedOps.length)
190
+ : 0;
191
+ // Calculate error rate
192
+ const totalOps = this.completedOps.length + this.errorOps;
193
+ this.metrics.errorRate = totalOps > 0 ? this.errorOps / totalOps : 0;
194
+ // Calculate average latency
195
+ this.metrics.latency = this.completedOps.length > 0
196
+ ? this.completedOps.reduce((a, b) => a + b, 0) / this.completedOps.length
197
+ : 0;
198
+ // Calculate throughput
199
+ this.metrics.throughput = this.activeOperations.size + this.metrics.processingRate;
200
+ // Reset error counter periodically
201
+ if (this.completedOps.length > 100) {
202
+ this.errorOps = Math.floor(this.errorOps * 0.9); // Decay error count
203
+ }
204
+ }
205
+ /**
206
+ * Learn from current load patterns
207
+ */
208
+ learnPattern() {
209
+ const currentLoad = this.activeOperations.size + this.queue.length;
210
+ const optimalConcurrency = this.calculateOptimalConcurrency();
211
+ this.patterns.push({
212
+ timestamp: Date.now(),
213
+ load: currentLoad,
214
+ optimal: optimalConcurrency
215
+ });
216
+ // Keep patterns bounded
217
+ if (this.patterns.length > 1000) {
218
+ this.patterns = this.patterns.slice(-500);
219
+ }
220
+ }
221
+ /**
222
+ * Calculate optimal concurrency based on Little's Law
223
+ */
224
+ calculateOptimalConcurrency() {
225
+ // Little's Law: L = λ * W
226
+ // L = number of requests in system
227
+ // λ = arrival rate
228
+ // W = average time in system
229
+ if (this.metrics.latency === 0 || this.metrics.processingRate === 0) {
230
+ return this.maxConcurrent; // Keep current if no data
231
+ }
232
+ // Target: Keep latency under target while maximizing throughput
233
+ const targetConcurrency = Math.ceil(this.metrics.processingRate * (this.config.targetLatency / 1000));
234
+ // Adjust based on error rate
235
+ const errorAdjustment = 1 - (this.metrics.errorRate * 2); // Reduce by up to 50% for errors
236
+ // Apply adjustment
237
+ const adjusted = Math.floor(targetConcurrency * errorAdjustment);
238
+ // Apply bounds
239
+ return Math.max(10, Math.min(500, adjusted));
240
+ }
241
+ /**
242
+ * Adapt configuration based on metrics and patterns
243
+ */
244
+ adaptConfiguration() {
245
+ const optimal = this.calculateOptimalConcurrency();
246
+ const current = this.maxConcurrent;
247
+ // Smooth adaptation using exponential moving average
248
+ const newConcurrency = Math.floor(current * (1 - this.config.adaptationRate) +
249
+ optimal * this.config.adaptationRate);
250
+ // Check if adaptation is needed
251
+ if (Math.abs(newConcurrency - current) > current * 0.1) { // 10% threshold
252
+ const oldValue = this.maxConcurrent;
253
+ this.maxConcurrent = newConcurrency;
254
+ this.logger.debug('Adapted concurrency', {
255
+ from: oldValue,
256
+ to: newConcurrency,
257
+ metrics: this.metrics
258
+ });
259
+ }
260
+ // Adapt queue depth based on throughput
261
+ if (this.metrics.throughput > 0) {
262
+ // Allow queue depth to be 10 seconds worth of throughput
263
+ this.config.maxQueueDepth = Math.max(100, Math.min(10000, Math.floor(this.metrics.throughput * 10)));
264
+ }
265
+ // Adapt circuit breaker threshold based on error patterns
266
+ if (this.metrics.errorRate < 0.01 && this.circuitThreshold > 5) {
267
+ this.circuitThreshold = Math.max(5, this.circuitThreshold - 1);
268
+ }
269
+ else if (this.metrics.errorRate > 0.05 && this.circuitThreshold < 20) {
270
+ this.circuitThreshold = Math.min(20, this.circuitThreshold + 1);
271
+ }
272
+ }
273
+ /**
274
+ * Predict future load based on patterns
275
+ */
276
+ predictLoad(futureSeconds = 60) {
277
+ if (this.patterns.length < 10) {
278
+ return this.maxConcurrent; // Not enough data
279
+ }
280
+ // Simple linear regression on recent patterns
281
+ const recentPatterns = this.patterns.slice(-50);
282
+ const n = recentPatterns.length;
283
+ // Calculate averages
284
+ let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
285
+ const startTime = recentPatterns[0].timestamp;
286
+ recentPatterns.forEach(p => {
287
+ const x = (p.timestamp - startTime) / 1000; // Time in seconds
288
+ const y = p.load;
289
+ sumX += x;
290
+ sumY += y;
291
+ sumXY += x * y;
292
+ sumX2 += x * x;
293
+ });
294
+ // Calculate slope and intercept
295
+ const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
296
+ const intercept = (sumY - slope * sumX) / n;
297
+ // Predict future load
298
+ const currentTime = (Date.now() - startTime) / 1000;
299
+ const predictedLoad = intercept + slope * (currentTime + futureSeconds);
300
+ return Math.max(0, Math.min(this.config.maxQueueDepth, Math.floor(predictedLoad)));
301
+ }
302
+ /**
303
+ * Get current configuration and metrics
304
+ */
305
+ getStatus() {
306
+ return {
307
+ config: { ...this.config },
308
+ metrics: { ...this.metrics },
309
+ circuit: this.circuitState,
310
+ maxConcurrent: this.maxConcurrent,
311
+ activeOps: this.activeOperations.size,
312
+ queueLength: this.queue.length
313
+ };
314
+ }
315
+ /**
316
+ * Reset to default state
317
+ */
318
+ reset() {
319
+ this.queue = [];
320
+ this.activeOperations.clear();
321
+ this.operationTimes.clear();
322
+ this.completedOps = [];
323
+ this.errorOps = 0;
324
+ this.patterns = [];
325
+ this.circuitState = 'closed';
326
+ this.circuitFailures = 0;
327
+ this.maxConcurrent = 100;
328
+ this.logger.info('Backpressure system reset to defaults');
329
+ }
330
+ }
331
+ // Global singleton instance
332
+ let globalBackpressure = null;
333
+ /**
334
+ * Get the global backpressure instance
335
+ */
336
+ export function getGlobalBackpressure() {
337
+ if (!globalBackpressure) {
338
+ globalBackpressure = new AdaptiveBackpressure();
339
+ }
340
+ return globalBackpressure;
341
+ }
342
+ //# sourceMappingURL=adaptiveBackpressure.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptiveBackpressure.js","sourceRoot":"","sources":["../../src/utils/adaptiveBackpressure.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAiBhD;;GAEG;AACH,MAAM,OAAO,oBAAoB;IAAjC;QACU,WAAM,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;QAE3D,mBAAmB;QACX,UAAK,GAKR,EAAE,CAAA;QAEP,6BAA6B;QACrB,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAA;QACpC,kBAAa,GAAG,GAAG,CAAA;QAE3B,mBAAmB;QACX,YAAO,GAAwB;YACrC,UAAU,EAAE,CAAC;YACb,cAAc,EAAE,CAAC;YACjB,SAAS,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;YACV,UAAU,EAAE,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IAAI,CAAC,aAAa;YACjC,SAAS,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI;YACrC,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM;SAC/B,CAAA;IACH,CAAC;IAED;;OAEG;IACI,KAAK;QACV,IAAI,CAAC,KAAK,GAAG,EAAE,CAAA;QACf,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAA;QAC7B,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA;QAC3B,IAAI,CAAC,YAAY,GAAG,EAAE,CAAA;QACtB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAA;QACjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAA;QAC5B,IAAI,CAAC,eAAe,GAAG,CAAC,CAAA;QACxB,IAAI,CAAC,aAAa,GAAG,GAAG,CAAA;QAExB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAA;IAC3D,CAAC;CACF;AAED,4BAA4B;AAC5B,IAAI,kBAAkB,GAAgC,IAAI,CAAA;AAE1D;;GAEG;AACH,MAAM,UAAU,qBAAqB;IACnC,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,kBAAkB,GAAG,IAAI,oBAAoB,EAAE,CAAA;IACjD,CAAC;IACD,OAAO,kBAAkB,CAAA;AAC3B,CAAC"}
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Adaptive Socket Manager
3
+ * Automatically manages socket pools and connection settings based on load patterns
4
+ * Zero-configuration approach that learns and adapts to workload characteristics
5
+ */
6
+ import { NodeHttpHandler } from '@smithy/node-http-handler';
7
+ interface LoadMetrics {
8
+ requestsPerSecond: number;
9
+ pendingRequests: number;
10
+ socketUtilization: number;
11
+ errorRate: number;
12
+ latencyP50: number;
13
+ latencyP95: number;
14
+ memoryUsage: number;
15
+ }
16
+ interface AdaptiveConfig {
17
+ maxSockets: number;
18
+ maxFreeSockets: number;
19
+ keepAliveTimeout: number;
20
+ connectionTimeout: number;
21
+ socketTimeout: number;
22
+ batchSize: number;
23
+ }
24
+ /**
25
+ * Adaptive Socket Manager that automatically scales based on load patterns
26
+ */
27
+ export declare class AdaptiveSocketManager {
28
+ private logger;
29
+ private config;
30
+ private metrics;
31
+ private history;
32
+ private maxHistorySize;
33
+ private lastAdaptationTime;
34
+ private adaptationInterval;
35
+ private consecutiveHighLoad;
36
+ private consecutiveLowLoad;
37
+ private requestStartTimes;
38
+ private requestLatencies;
39
+ private errorCount;
40
+ private successCount;
41
+ private lastMetricReset;
42
+ private currentAgent;
43
+ private currentHandler;
44
+ /**
45
+ * Get or create an optimized HTTP handler
46
+ */
47
+ getHttpHandler(): NodeHttpHandler;
48
+ /**
49
+ * Get current batch size recommendation
50
+ */
51
+ getBatchSize(): number;
52
+ /**
53
+ * Track request start
54
+ */
55
+ trackRequestStart(requestId: string): void;
56
+ /**
57
+ * Track request completion
58
+ */
59
+ trackRequestComplete(requestId: string, success: boolean): void;
60
+ /**
61
+ * Check if we should adapt configuration
62
+ */
63
+ private adaptIfNeeded;
64
+ /**
65
+ * Update current metrics
66
+ */
67
+ private updateMetrics;
68
+ /**
69
+ * Analyze metrics and adapt configuration
70
+ */
71
+ private analyzeAndAdapt;
72
+ /**
73
+ * Detect high load conditions
74
+ */
75
+ private detectHighLoad;
76
+ /**
77
+ * Detect low load conditions
78
+ */
79
+ private detectLowLoad;
80
+ /**
81
+ * Scale up resources for high load
82
+ */
83
+ private scaleUp;
84
+ /**
85
+ * Scale down resources for low load
86
+ */
87
+ private scaleDown;
88
+ /**
89
+ * Handle error conditions by adjusting configuration
90
+ */
91
+ private handleErrors;
92
+ /**
93
+ * Check if we should recreate the handler
94
+ */
95
+ private shouldRecreateHandler;
96
+ /**
97
+ * Get current configuration (for monitoring)
98
+ */
99
+ getConfig(): Readonly<AdaptiveConfig>;
100
+ /**
101
+ * Get current metrics (for monitoring)
102
+ */
103
+ getMetrics(): Readonly<LoadMetrics>;
104
+ /**
105
+ * Predict optimal configuration based on historical data
106
+ */
107
+ predictOptimalConfig(): AdaptiveConfig;
108
+ /**
109
+ * Reset to default configuration
110
+ */
111
+ reset(): void;
112
+ }
113
+ /**
114
+ * Get the global socket manager instance
115
+ */
116
+ export declare function getGlobalSocketManager(): AdaptiveSocketManager;
117
+ export {};