mcp-image 0.1.0 → 0.2.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 (178) hide show
  1. package/README.md +41 -17
  2. package/dist/api/geminiClient.d.ts +2 -12
  3. package/dist/api/geminiClient.d.ts.map +1 -1
  4. package/dist/api/geminiClient.js +28 -56
  5. package/dist/api/geminiClient.js.map +1 -1
  6. package/dist/api/geminiTextClient.d.ts +42 -0
  7. package/dist/api/geminiTextClient.d.ts.map +1 -0
  8. package/dist/api/geminiTextClient.js +198 -0
  9. package/dist/api/geminiTextClient.js.map +1 -0
  10. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.d.ts +84 -0
  11. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.d.ts.map +1 -0
  12. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.js +100 -0
  13. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.js.map +1 -0
  14. package/dist/business/bestPracticesEngine.d.ts +149 -0
  15. package/dist/business/bestPracticesEngine.d.ts.map +1 -0
  16. package/dist/business/bestPracticesEngine.js +781 -0
  17. package/dist/business/bestPracticesEngine.js.map +1 -0
  18. package/dist/business/complexityAssessment.d.ts +132 -0
  19. package/dist/business/complexityAssessment.d.ts.map +1 -0
  20. package/dist/business/complexityAssessment.js +488 -0
  21. package/dist/business/complexityAssessment.js.map +1 -0
  22. package/dist/business/fallbackStrategies.d.ts +177 -0
  23. package/dist/business/fallbackStrategies.d.ts.map +1 -0
  24. package/dist/business/fallbackStrategies.js +368 -0
  25. package/dist/business/fallbackStrategies.js.map +1 -0
  26. package/dist/business/imageGenerator.d.ts.map +1 -1
  27. package/dist/business/imageGenerator.js +26 -5
  28. package/dist/business/imageGenerator.js.map +1 -1
  29. package/dist/business/multiImage/aspectRatioController.d.ts +77 -0
  30. package/dist/business/multiImage/aspectRatioController.d.ts.map +1 -0
  31. package/dist/business/multiImage/aspectRatioController.js +580 -0
  32. package/dist/business/multiImage/aspectRatioController.js.map +1 -0
  33. package/dist/business/multiImage/multiImageCoordinator.d.ts +142 -0
  34. package/dist/business/multiImage/multiImageCoordinator.d.ts.map +1 -0
  35. package/dist/business/multiImage/multiImageCoordinator.js +801 -0
  36. package/dist/business/multiImage/multiImageCoordinator.js.map +1 -0
  37. package/dist/business/pomlTemplateEngine.d.ts +206 -0
  38. package/dist/business/pomlTemplateEngine.d.ts.map +1 -0
  39. package/dist/business/pomlTemplateEngine.js +737 -0
  40. package/dist/business/pomlTemplateEngine.js.map +1 -0
  41. package/dist/business/promptOrchestrator.d.ts +173 -0
  42. package/dist/business/promptOrchestrator.d.ts.map +1 -0
  43. package/dist/business/promptOrchestrator.js +490 -0
  44. package/dist/business/promptOrchestrator.js.map +1 -0
  45. package/dist/business/responseBuilder.d.ts +2 -2
  46. package/dist/business/responseBuilder.d.ts.map +1 -1
  47. package/dist/business/responseBuilder.js +6 -1
  48. package/dist/business/responseBuilder.js.map +1 -1
  49. package/dist/business/structuredPromptGenerator.d.ts +54 -0
  50. package/dist/business/structuredPromptGenerator.d.ts.map +1 -0
  51. package/dist/business/structuredPromptGenerator.js +208 -0
  52. package/dist/business/structuredPromptGenerator.js.map +1 -0
  53. package/dist/business/templateNormalizer.d.ts +81 -0
  54. package/dist/business/templateNormalizer.d.ts.map +1 -0
  55. package/dist/business/templateNormalizer.js +659 -0
  56. package/dist/business/templateNormalizer.js.map +1 -0
  57. package/dist/documentation/apiContractValidation.d.ts +62 -0
  58. package/dist/documentation/apiContractValidation.d.ts.map +1 -0
  59. package/dist/documentation/apiContractValidation.js +305 -0
  60. package/dist/documentation/apiContractValidation.js.map +1 -0
  61. package/dist/infrastructure/concurrency/concurrencyManager.d.ts +101 -0
  62. package/dist/infrastructure/concurrency/concurrencyManager.d.ts.map +1 -0
  63. package/dist/infrastructure/concurrency/concurrencyManager.js +345 -0
  64. package/dist/infrastructure/concurrency/concurrencyManager.js.map +1 -0
  65. package/dist/infrastructure/config/secureConfigManager.d.ts +319 -0
  66. package/dist/infrastructure/config/secureConfigManager.d.ts.map +1 -0
  67. package/dist/infrastructure/config/secureConfigManager.js +600 -0
  68. package/dist/infrastructure/config/secureConfigManager.js.map +1 -0
  69. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.d.ts +229 -0
  70. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.d.ts.map +1 -0
  71. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.js +61 -0
  72. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.js.map +1 -0
  73. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.d.ts +133 -0
  74. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.d.ts.map +1 -0
  75. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.js +569 -0
  76. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.js.map +1 -0
  77. package/dist/infrastructure/mcp/MCPSamplingClient.d.ts +19 -0
  78. package/dist/infrastructure/mcp/MCPSamplingClient.d.ts.map +1 -0
  79. package/dist/infrastructure/mcp/MCPSamplingClient.js +31 -0
  80. package/dist/infrastructure/mcp/MCPSamplingClient.js.map +1 -0
  81. package/dist/infrastructure/mcp/RealMCPSamplingClient.d.ts +59 -0
  82. package/dist/infrastructure/mcp/RealMCPSamplingClient.d.ts.map +1 -0
  83. package/dist/infrastructure/mcp/RealMCPSamplingClient.js +271 -0
  84. package/dist/infrastructure/mcp/RealMCPSamplingClient.js.map +1 -0
  85. package/dist/infrastructure/metadata/generationMetadata.d.ts +72 -0
  86. package/dist/infrastructure/metadata/generationMetadata.d.ts.map +1 -0
  87. package/dist/infrastructure/metadata/generationMetadata.js +228 -0
  88. package/dist/infrastructure/metadata/generationMetadata.js.map +1 -0
  89. package/dist/infrastructure/monitoring/OrchestrationMetrics.d.ts +106 -0
  90. package/dist/infrastructure/monitoring/OrchestrationMetrics.d.ts.map +1 -0
  91. package/dist/infrastructure/monitoring/OrchestrationMetrics.js +456 -0
  92. package/dist/infrastructure/monitoring/OrchestrationMetrics.js.map +1 -0
  93. package/dist/infrastructure/monitoring/alertingSystem.d.ts +135 -0
  94. package/dist/infrastructure/monitoring/alertingSystem.d.ts.map +1 -0
  95. package/dist/infrastructure/monitoring/alertingSystem.js +549 -0
  96. package/dist/infrastructure/monitoring/alertingSystem.js.map +1 -0
  97. package/dist/infrastructure/optimization/performanceOptimizer.d.ts +89 -0
  98. package/dist/infrastructure/optimization/performanceOptimizer.d.ts.map +1 -0
  99. package/dist/infrastructure/optimization/performanceOptimizer.js +375 -0
  100. package/dist/infrastructure/optimization/performanceOptimizer.js.map +1 -0
  101. package/dist/infrastructure/security/AdvancedContentFilter.d.ts +99 -0
  102. package/dist/infrastructure/security/AdvancedContentFilter.d.ts.map +1 -0
  103. package/dist/infrastructure/security/AdvancedContentFilter.js +363 -0
  104. package/dist/infrastructure/security/AdvancedContentFilter.js.map +1 -0
  105. package/dist/infrastructure/security/MCPSecurityValidator.d.ts +62 -0
  106. package/dist/infrastructure/security/MCPSecurityValidator.d.ts.map +1 -0
  107. package/dist/infrastructure/security/MCPSecurityValidator.js +129 -0
  108. package/dist/infrastructure/security/MCPSecurityValidator.js.map +1 -0
  109. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.d.ts +304 -0
  110. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.d.ts.map +1 -0
  111. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.js +61 -0
  112. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.js.map +1 -0
  113. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.d.ts +62 -0
  114. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.d.ts.map +1 -0
  115. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.js +591 -0
  116. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.js.map +1 -0
  117. package/dist/infrastructure/security/SecureMCPClient.d.ts +154 -0
  118. package/dist/infrastructure/security/SecureMCPClient.d.ts.map +1 -0
  119. package/dist/infrastructure/security/SecureMCPClient.js +292 -0
  120. package/dist/infrastructure/security/SecureMCPClient.js.map +1 -0
  121. package/dist/infrastructure/security/SecurityIncidentManager.d.ts +142 -0
  122. package/dist/infrastructure/security/SecurityIncidentManager.d.ts.map +1 -0
  123. package/dist/infrastructure/security/SecurityIncidentManager.js +260 -0
  124. package/dist/infrastructure/security/SecurityIncidentManager.js.map +1 -0
  125. package/dist/infrastructure/security/apiKeyManager.d.ts +297 -0
  126. package/dist/infrastructure/security/apiKeyManager.d.ts.map +1 -0
  127. package/dist/infrastructure/security/apiKeyManager.js +254 -0
  128. package/dist/infrastructure/security/apiKeyManager.js.map +1 -0
  129. package/dist/infrastructure/security/dataSanitizer.d.ts +157 -0
  130. package/dist/infrastructure/security/dataSanitizer.d.ts.map +1 -0
  131. package/dist/infrastructure/security/dataSanitizer.js +525 -0
  132. package/dist/infrastructure/security/dataSanitizer.js.map +1 -0
  133. package/dist/infrastructure/validation/inputValidator.d.ts +54 -0
  134. package/dist/infrastructure/validation/inputValidator.d.ts.map +1 -0
  135. package/dist/infrastructure/validation/inputValidator.js +362 -0
  136. package/dist/infrastructure/validation/inputValidator.js.map +1 -0
  137. package/dist/integration/parameterOptimizer.d.ts +69 -0
  138. package/dist/integration/parameterOptimizer.d.ts.map +1 -0
  139. package/dist/integration/parameterOptimizer.js +317 -0
  140. package/dist/integration/parameterOptimizer.js.map +1 -0
  141. package/dist/integration/twoStageProcessor.d.ts +66 -0
  142. package/dist/integration/twoStageProcessor.d.ts.map +1 -0
  143. package/dist/integration/twoStageProcessor.js +348 -0
  144. package/dist/integration/twoStageProcessor.js.map +1 -0
  145. package/dist/server/handlers/structuredPromptHandler.d.ts +65 -0
  146. package/dist/server/handlers/structuredPromptHandler.d.ts.map +1 -0
  147. package/dist/server/handlers/structuredPromptHandler.js +314 -0
  148. package/dist/server/handlers/structuredPromptHandler.js.map +1 -0
  149. package/dist/server/mcpServer.d.ts +16 -35
  150. package/dist/server/mcpServer.d.ts.map +1 -1
  151. package/dist/server/mcpServer.js +111 -150
  152. package/dist/server/mcpServer.js.map +1 -1
  153. package/dist/server/mcpServerWithOrchestration.d.ts +98 -0
  154. package/dist/server/mcpServerWithOrchestration.d.ts.map +1 -0
  155. package/dist/server/mcpServerWithOrchestration.js +284 -0
  156. package/dist/server/mcpServerWithOrchestration.js.map +1 -0
  157. package/dist/types/mcpOrchestrationTypes.d.ts +135 -0
  158. package/dist/types/mcpOrchestrationTypes.d.ts.map +1 -0
  159. package/dist/types/mcpOrchestrationTypes.js +28 -0
  160. package/dist/types/mcpOrchestrationTypes.js.map +1 -0
  161. package/dist/types/multiImageTypes.d.ts +328 -0
  162. package/dist/types/multiImageTypes.d.ts.map +1 -0
  163. package/dist/types/multiImageTypes.js +27 -0
  164. package/dist/types/multiImageTypes.js.map +1 -0
  165. package/dist/types/performanceTypes.d.ts +300 -0
  166. package/dist/types/performanceTypes.d.ts.map +1 -0
  167. package/dist/types/performanceTypes.js +50 -0
  168. package/dist/types/performanceTypes.js.map +1 -0
  169. package/dist/types/twoStageTypes.d.ts +123 -0
  170. package/dist/types/twoStageTypes.d.ts.map +1 -0
  171. package/dist/types/twoStageTypes.js +7 -0
  172. package/dist/types/twoStageTypes.js.map +1 -0
  173. package/dist/utils/config.d.ts +1 -0
  174. package/dist/utils/config.d.ts.map +1 -1
  175. package/dist/utils/config.js +1 -0
  176. package/dist/utils/config.js.map +1 -1
  177. package/package.json +11 -4
  178. package/vitest.config.mjs +0 -47
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ /**
3
+ * Concurrency Manager - Resource competition and concurrent operation management
4
+ * Prevents system overload and manages resource allocation across concurrent operations
5
+ * Provides intelligent queuing and resource contention resolution
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.ConcurrencyManager = exports.ResourceContentionError = void 0;
9
+ const result_1 = require("../../types/result");
10
+ const orchestrationErrorHandler_1 = require("../errorHandling/orchestrationErrorHandler");
11
+ /**
12
+ * Resource contention error
13
+ */
14
+ class ResourceContentionError extends Error {
15
+ constructor(message, metadata = {}) {
16
+ super(message);
17
+ this.metadata = metadata;
18
+ this.name = 'ResourceContentionError';
19
+ }
20
+ }
21
+ exports.ResourceContentionError = ResourceContentionError;
22
+ /**
23
+ * Default resource limits
24
+ */
25
+ const DEFAULT_RESOURCE_LIMITS = {
26
+ maxMemory: 1024 * 1024 * 1024, // 1GB
27
+ maxCpu: 80, // 80% CPU usage
28
+ maxNetworkBandwidth: 100 * 1024 * 1024, // 100MB/s
29
+ maxConcurrentOperations: 10,
30
+ maxConcurrentConnections: 50,
31
+ };
32
+ /**
33
+ * ConcurrencyManager implementation for resource and operation management
34
+ */
35
+ class ConcurrencyManager {
36
+ constructor(resourceLimits = DEFAULT_RESOURCE_LIMITS) {
37
+ this.activeOperations = new Map();
38
+ this.operationQueue = [];
39
+ this.nextOperationId = 1;
40
+ this.resourceLimits = { ...resourceLimits };
41
+ this.currentUsage = {
42
+ memory: 0,
43
+ cpu: 0,
44
+ networkBandwidth: 0,
45
+ concurrentOperations: 0,
46
+ concurrentConnections: 0,
47
+ };
48
+ }
49
+ /**
50
+ * Manage concurrent operation with resource allocation
51
+ */
52
+ async manageConcurrentOperation(operation, resourceRequirements, priority = orchestrationErrorHandler_1.OperationPriority.NORMAL) {
53
+ // Check resource availability
54
+ const resourceCheck = await this.checkResourceAvailability(resourceRequirements);
55
+ if (!resourceCheck.available) {
56
+ return this.handleResourceContention(operation, priority, resourceRequirements);
57
+ }
58
+ // Execute with resource management
59
+ const operationId = this.generateOperationId();
60
+ try {
61
+ this.trackOperation(operationId, resourceRequirements);
62
+ const result = await operation();
63
+ return (0, result_1.Ok)(result);
64
+ }
65
+ catch (error) {
66
+ return (0, result_1.Err)(new ResourceContentionError(`Operation failed: ${error}`, {
67
+ operationId,
68
+ requirements: resourceRequirements,
69
+ }));
70
+ }
71
+ finally {
72
+ this.releaseOperation(operationId);
73
+ }
74
+ }
75
+ /**
76
+ * Check if resources are available for the operation
77
+ */
78
+ async checkResourceAvailability(requirements) {
79
+ const wouldExceedMemory = this.currentUsage.memory + requirements.memory > this.resourceLimits.maxMemory;
80
+ const wouldExceedCpu = this.currentUsage.cpu + requirements.cpu > this.resourceLimits.maxCpu;
81
+ const wouldExceedBandwidth = this.currentUsage.networkBandwidth + requirements.networkBandwidth >
82
+ this.resourceLimits.maxNetworkBandwidth;
83
+ const wouldExceedOperations = this.currentUsage.concurrentOperations + 1 > this.resourceLimits.maxConcurrentOperations;
84
+ const wouldExceedConnections = this.currentUsage.concurrentConnections + requirements.concurrentConnections >
85
+ this.resourceLimits.maxConcurrentConnections;
86
+ const available = !wouldExceedMemory &&
87
+ !wouldExceedCpu &&
88
+ !wouldExceedBandwidth &&
89
+ !wouldExceedOperations &&
90
+ !wouldExceedConnections;
91
+ let reason;
92
+ if (!available) {
93
+ const issues = [];
94
+ if (wouldExceedMemory)
95
+ issues.push('memory');
96
+ if (wouldExceedCpu)
97
+ issues.push('cpu');
98
+ if (wouldExceedBandwidth)
99
+ issues.push('bandwidth');
100
+ if (wouldExceedOperations)
101
+ issues.push('concurrent operations');
102
+ if (wouldExceedConnections)
103
+ issues.push('concurrent connections');
104
+ reason = `Resource limits exceeded: ${issues.join(', ')}`;
105
+ }
106
+ return {
107
+ available,
108
+ currentUsage: { ...this.currentUsage },
109
+ estimatedWaitTime: available ? 0 : this.estimateWaitTime(requirements),
110
+ reason: reason || 'Unknown reason',
111
+ };
112
+ }
113
+ /**
114
+ * Handle resource contention with queuing or rejection
115
+ */
116
+ async handleResourceContention(operation, priority, requirements) {
117
+ if (priority === orchestrationErrorHandler_1.OperationPriority.HIGH || priority === orchestrationErrorHandler_1.OperationPriority.CRITICAL) {
118
+ // Queue high priority operations
119
+ return this.queueOperation(operation, priority, requirements);
120
+ }
121
+ // Reject low priority operations with guidance
122
+ const estimatedWait = this.estimateWaitTime(requirements);
123
+ return (0, result_1.Err)(new ResourceContentionError('System busy - try again in a few moments', {
124
+ estimatedWait,
125
+ currentLoad: this.calculateCurrentLoad(),
126
+ suggestion: 'Consider reducing request complexity or trying again later',
127
+ }));
128
+ }
129
+ /**
130
+ * Queue operation for later execution
131
+ */
132
+ async queueOperation(operation, priority, requirements) {
133
+ const queuedOperation = {
134
+ id: this.generateOperationId(),
135
+ operation: operation,
136
+ priority,
137
+ requirements,
138
+ queuedAt: new Date(),
139
+ estimatedDuration: this.estimateOperationDuration(requirements),
140
+ };
141
+ // Insert into queue based on priority
142
+ this.insertIntoQueue(queuedOperation);
143
+ // Wait for operation to be processed
144
+ return new Promise((resolve) => {
145
+ const checkQueue = async () => {
146
+ const resourceCheck = await this.checkResourceAvailability(requirements);
147
+ if (resourceCheck.available && this.operationQueue[0]?.id === queuedOperation.id) {
148
+ // Remove from queue and execute
149
+ this.operationQueue.shift();
150
+ const operationId = queuedOperation.id;
151
+ try {
152
+ this.trackOperation(operationId, requirements);
153
+ const result = await queuedOperation.operation();
154
+ resolve((0, result_1.Ok)(result));
155
+ }
156
+ catch (error) {
157
+ resolve((0, result_1.Err)(new ResourceContentionError(`Queued operation failed: ${error}`, {
158
+ operationId,
159
+ queuedAt: queuedOperation.queuedAt,
160
+ })));
161
+ }
162
+ finally {
163
+ this.releaseOperation(operationId);
164
+ }
165
+ }
166
+ else {
167
+ // Check again after a delay
168
+ setTimeout(checkQueue, 1000);
169
+ }
170
+ };
171
+ checkQueue();
172
+ });
173
+ }
174
+ /**
175
+ * Insert operation into priority-based queue
176
+ */
177
+ insertIntoQueue(operation) {
178
+ const priorityOrder = {
179
+ [orchestrationErrorHandler_1.OperationPriority.CRITICAL]: 0,
180
+ [orchestrationErrorHandler_1.OperationPriority.HIGH]: 1,
181
+ [orchestrationErrorHandler_1.OperationPriority.NORMAL]: 2,
182
+ [orchestrationErrorHandler_1.OperationPriority.LOW]: 3,
183
+ };
184
+ const insertIndex = this.operationQueue.findIndex((queued) => priorityOrder[queued.priority] > priorityOrder[operation.priority]);
185
+ if (insertIndex === -1) {
186
+ this.operationQueue.push(operation);
187
+ }
188
+ else {
189
+ this.operationQueue.splice(insertIndex, 0, operation);
190
+ }
191
+ }
192
+ /**
193
+ * Track active operation and update resource usage
194
+ */
195
+ trackOperation(operationId, requirements) {
196
+ const tracking = {
197
+ id: operationId,
198
+ startTime: new Date(),
199
+ requirements,
200
+ estimatedEndTime: new Date(Date.now() + this.estimateOperationDuration(requirements)),
201
+ actualUsage: {},
202
+ };
203
+ this.activeOperations.set(operationId, tracking);
204
+ // Update current usage
205
+ this.currentUsage.memory += requirements.memory;
206
+ this.currentUsage.cpu += requirements.cpu;
207
+ this.currentUsage.networkBandwidth += requirements.networkBandwidth;
208
+ this.currentUsage.concurrentOperations += 1;
209
+ this.currentUsage.concurrentConnections += requirements.concurrentConnections;
210
+ }
211
+ /**
212
+ * Release operation and free resources
213
+ */
214
+ releaseOperation(operationId) {
215
+ const tracking = this.activeOperations.get(operationId);
216
+ if (!tracking)
217
+ return;
218
+ // Update current usage
219
+ this.currentUsage.memory -= tracking.requirements.memory;
220
+ this.currentUsage.cpu -= tracking.requirements.cpu;
221
+ this.currentUsage.networkBandwidth -= tracking.requirements.networkBandwidth;
222
+ this.currentUsage.concurrentOperations -= 1;
223
+ this.currentUsage.concurrentConnections -= tracking.requirements.concurrentConnections;
224
+ // Ensure no negative values
225
+ this.currentUsage.memory = Math.max(0, this.currentUsage.memory);
226
+ this.currentUsage.cpu = Math.max(0, this.currentUsage.cpu);
227
+ this.currentUsage.networkBandwidth = Math.max(0, this.currentUsage.networkBandwidth);
228
+ this.currentUsage.concurrentOperations = Math.max(0, this.currentUsage.concurrentOperations);
229
+ this.currentUsage.concurrentConnections = Math.max(0, this.currentUsage.concurrentConnections);
230
+ this.activeOperations.delete(operationId);
231
+ }
232
+ /**
233
+ * Generate unique operation ID
234
+ */
235
+ generateOperationId() {
236
+ return `op-${Date.now()}-${this.nextOperationId++}`;
237
+ }
238
+ /**
239
+ * Estimate wait time for resource availability
240
+ */
241
+ estimateWaitTime(requirements) {
242
+ const activeOps = Array.from(this.activeOperations.values());
243
+ if (activeOps.length === 0)
244
+ return 0;
245
+ // Find the operation that would free enough resources
246
+ const sortedByEndTime = activeOps.sort((a, b) => a.estimatedEndTime.getTime() - b.estimatedEndTime.getTime());
247
+ for (const op of sortedByEndTime) {
248
+ const timeUntilEnd = Math.max(0, op.estimatedEndTime.getTime() - Date.now());
249
+ // Simulate releasing this operation
250
+ const projectedUsage = {
251
+ memory: this.currentUsage.memory - op.requirements.memory,
252
+ cpu: this.currentUsage.cpu - op.requirements.cpu,
253
+ networkBandwidth: this.currentUsage.networkBandwidth - op.requirements.networkBandwidth,
254
+ concurrentOperations: this.currentUsage.concurrentOperations - 1,
255
+ concurrentConnections: this.currentUsage.concurrentConnections - op.requirements.concurrentConnections,
256
+ };
257
+ // Check if resources would be available
258
+ const wouldHaveResources = projectedUsage.memory + requirements.memory <= this.resourceLimits.maxMemory &&
259
+ projectedUsage.cpu + requirements.cpu <= this.resourceLimits.maxCpu &&
260
+ projectedUsage.networkBandwidth + requirements.networkBandwidth <=
261
+ this.resourceLimits.maxNetworkBandwidth &&
262
+ projectedUsage.concurrentOperations + 1 <= this.resourceLimits.maxConcurrentOperations &&
263
+ projectedUsage.concurrentConnections + requirements.concurrentConnections <=
264
+ this.resourceLimits.maxConcurrentConnections;
265
+ if (wouldHaveResources) {
266
+ return timeUntilEnd;
267
+ }
268
+ }
269
+ // Fallback: estimate based on average operation duration
270
+ const avgDuration = this.calculateAverageOperationDuration();
271
+ return avgDuration * 0.5; // Conservative estimate
272
+ }
273
+ /**
274
+ * Estimate operation duration based on resource requirements
275
+ */
276
+ estimateOperationDuration(requirements) {
277
+ // Base duration on resource complexity
278
+ const memoryFactor = requirements.memory / (1024 * 1024); // MB
279
+ const cpuFactor = requirements.cpu;
280
+ const networkFactor = requirements.networkBandwidth / (1024 * 1024); // MB/s
281
+ // Estimate based on empirical factors (in milliseconds)
282
+ const baseDuration = 5000; // 5 seconds base
283
+ const estimatedDuration = baseDuration + memoryFactor * 100 + cpuFactor * 200 + networkFactor * 50;
284
+ return Math.max(1000, estimatedDuration); // Minimum 1 second
285
+ }
286
+ /**
287
+ * Calculate average operation duration from active operations
288
+ */
289
+ calculateAverageOperationDuration() {
290
+ const activeOps = Array.from(this.activeOperations.values());
291
+ if (activeOps.length === 0)
292
+ return 10000; // Default 10 seconds
293
+ const totalEstimatedDuration = activeOps.reduce((sum, op) => sum + (op.estimatedEndTime.getTime() - op.startTime.getTime()), 0);
294
+ return totalEstimatedDuration / activeOps.length;
295
+ }
296
+ /**
297
+ * Calculate current system load percentage
298
+ */
299
+ calculateCurrentLoad() {
300
+ const memoryLoad = (this.currentUsage.memory / this.resourceLimits.maxMemory) * 100;
301
+ const cpuLoad = (this.currentUsage.cpu / this.resourceLimits.maxCpu) * 100;
302
+ const networkLoad = (this.currentUsage.networkBandwidth / this.resourceLimits.maxNetworkBandwidth) * 100;
303
+ const operationLoad = (this.currentUsage.concurrentOperations / this.resourceLimits.maxConcurrentOperations) * 100;
304
+ const connectionLoad = (this.currentUsage.concurrentConnections / this.resourceLimits.maxConcurrentConnections) * 100;
305
+ return Math.max(memoryLoad, cpuLoad, networkLoad, operationLoad, connectionLoad);
306
+ }
307
+ /**
308
+ * Get current system status
309
+ */
310
+ getSystemStatus() {
311
+ return {
312
+ currentUsage: { ...this.currentUsage },
313
+ resourceLimits: { ...this.resourceLimits },
314
+ activeOperations: this.activeOperations.size,
315
+ queuedOperations: this.operationQueue.length,
316
+ currentLoad: this.calculateCurrentLoad(),
317
+ };
318
+ }
319
+ /**
320
+ * Force cleanup of stale operations
321
+ */
322
+ cleanup() {
323
+ const now = Date.now();
324
+ const staleThreshold = 5 * 60 * 1000; // 5 minutes
325
+ for (const [id, tracking] of this.activeOperations.entries()) {
326
+ if (now - tracking.startTime.getTime() > staleThreshold) {
327
+ this.releaseOperation(id);
328
+ }
329
+ }
330
+ // Clean up old queued operations
331
+ const maxQueueAge = 10 * 60 * 1000; // 10 minutes
332
+ let i = 0;
333
+ while (i < this.operationQueue.length) {
334
+ const queuedOp = this.operationQueue[i];
335
+ if (queuedOp && now - queuedOp.queuedAt.getTime() > maxQueueAge) {
336
+ this.operationQueue.splice(i, 1);
337
+ }
338
+ else {
339
+ i++;
340
+ }
341
+ }
342
+ }
343
+ }
344
+ exports.ConcurrencyManager = ConcurrencyManager;
345
+ //# sourceMappingURL=concurrencyManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"concurrencyManager.js","sourceRoot":"","sources":["../../../src/infrastructure/concurrency/concurrencyManager.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAGH,+CAA4C;AAK5C,0FAA8E;AAmC9E;;GAEG;AACH,MAAa,uBAAwB,SAAQ,KAAK;IAChD,YACE,OAAe,EACC,WAAoC,EAAE;QAEtD,KAAK,CAAC,OAAO,CAAC,CAAA;QAFE,aAAQ,GAAR,QAAQ,CAA8B;QAGtD,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAA;IACvC,CAAC;CACF;AARD,0DAQC;AAaD;;GAEG;AACH,MAAM,uBAAuB,GAAmB;IAC9C,SAAS,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,MAAM;IACrC,MAAM,EAAE,EAAE,EAAE,gBAAgB;IAC5B,mBAAmB,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,UAAU;IAClD,uBAAuB,EAAE,EAAE;IAC3B,wBAAwB,EAAE,EAAE;CAC7B,CAAA;AAED;;GAEG;AACH,MAAa,kBAAkB;IAO7B,YAAY,iBAAiC,uBAAuB;QANnD,qBAAgB,GAAmC,IAAI,GAAG,EAAE,CAAA;QAC5D,mBAAc,GAAsB,EAAE,CAAA;QAG/C,oBAAe,GAAG,CAAC,CAAA;QAGzB,IAAI,CAAC,cAAc,GAAG,EAAE,GAAG,cAAc,EAAE,CAAA;QAC3C,IAAI,CAAC,YAAY,GAAG;YAClB,MAAM,EAAE,CAAC;YACT,GAAG,EAAE,CAAC;YACN,gBA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rieval, and management of configuration data
4
+ * Addresses CONFIG4, CONFIG5 requirements and supports security framework
5
+ */
6
+ /**
7
+ * Secure configuration data structure
8
+ */
9
+ export interface SecureConfig {
10
+ config: ConfigData;
11
+ metadata: ConfigMetadata;
12
+ }
13
+ /**
14
+ * Configuration data (generic structure)
15
+ */
16
+ export interface ConfigData {
17
+ [key: string]: unknown;
18
+ }
19
+ /**
20
+ * Configuration metadata
21
+ */
22
+ export interface ConfigMetadata {
23
+ lastUpdated: number;
24
+ version: string;
25
+ checksum: string;
26
+ encryptedAt?: number;
27
+ updatedBy?: string;
28
+ }
29
+ /**
30
+ * Encrypted configuration store
31
+ */
32
+ export interface EncryptedConfigStore {
33
+ store(component: string, encryptedData: EncryptedConfigData): Promise<void>;
34
+ retrieve(component: string): Promise<EncryptedConfigData>;
35
+ exists(component: string): Promise<boolean>;
36
+ delete(component: string): Promise<void>;
37
+ list(): Promise<string[]>;
38
+ backup(): Promise<ConfigBackup>;
39
+ restore(backup: ConfigBackup): Promise<void>;
40
+ }
41
+ /**
42
+ * Encrypted configuration data
43
+ */
44
+ export interface EncryptedConfigData {
45
+ encryptedContent: string;
46
+ encryptionMethod: string;
47
+ lastUpdated: number;
48
+ version: string;
49
+ checksum: string;
50
+ salt?: string;
51
+ iv?: string;
52
+ }
53
+ /**
54
+ * Configuration backup
55
+ */
56
+ export interface ConfigBackup {
57
+ backupId: string;
58
+ timestamp: number;
59
+ components: Record<string, EncryptedConfigData>;
60
+ metadata: {
61
+ totalComponents: number;
62
+ backupSize: number;
63
+ checksum: string;
64
+ };
65
+ }
66
+ /**
67
+ * Configuration validator
68
+ */
69
+ export interface ConfigValidator {
70
+ validate(component: string, config: ConfigData): Promise<ConfigValidationResult>;
71
+ getSchema(component: string): ConfigSchema | null;
72
+ registerSchema(component: string, schema: ConfigSchema): void;
73
+ }
74
+ /**
75
+ * Configuration validation result
76
+ */
77
+ export interface ConfigValidationResult {
78
+ valid: boolean;
79
+ errors: ConfigValidationError[];
80
+ warnings: ConfigValidationWarning[];
81
+ }
82
+ /**
83
+ * Configuration validation error
84
+ */
85
+ export interface ConfigValidationError {
86
+ field: string;
87
+ message: string;
88
+ severity: 'error' | 'warning';
89
+ code: string;
90
+ }
91
+ /**
92
+ * Configuration validation warning
93
+ */
94
+ export interface ConfigValidationWarning {
95
+ field: string;
96
+ message: string;
97
+ recommendation: string;
98
+ code: string;
99
+ }
100
+ /**
101
+ * Configuration schema definition
102
+ */
103
+ export interface ConfigSchema {
104
+ type: 'object';
105
+ properties: Record<string, ConfigPropertySchema>;
106
+ required?: string[];
107
+ additionalProperties?: boolean;
108
+ }
109
+ /**
110
+ * Configuration property schema
111
+ */
112
+ export interface ConfigPropertySchema {
113
+ type: 'string' | 'number' | 'boolean' | 'object' | 'array';
114
+ description?: string;
115
+ required?: boolean;
116
+ default?: unknown;
117
+ enum?: unknown[];
118
+ minimum?: number;
119
+ maximum?: number;
120
+ minLength?: number;
121
+ maxLength?: number;
122
+ pattern?: string;
123
+ items?: ConfigPropertySchema;
124
+ properties?: Record<string, ConfigPropertySchema>;
125
+ }
126
+ /**
127
+ * Configuration audit logger
128
+ */
129
+ export interface ConfigAuditLogger {
130
+ logAccess(event: ConfigAccessEvent): Promise<void>;
131
+ logUpdate(event: ConfigUpdateEvent): Promise<void>;
132
+ logDeletion(event: ConfigDeletionEvent): Promise<void>;
133
+ getAuditHistory(component: string, timeRange: TimeRange): Promise<ConfigAuditEvent[]>;
134
+ searchAuditLogs(criteria: AuditSearchCriteria): Promise<ConfigAuditEvent[]>;
135
+ }
136
+ /**
137
+ * Configuration access event
138
+ */
139
+ export interface ConfigAccessEvent {
140
+ component: string;
141
+ timestamp: number;
142
+ accessType: 'read' | 'list' | 'exists';
143
+ userId?: string;
144
+ sessionId?: string;
145
+ ipAddress?: string;
146
+ success: boolean;
147
+ error?: string;
148
+ }
149
+ /**
150
+ * Configuration update event
151
+ */
152
+ export interface ConfigUpdateEvent {
153
+ component: string;
154
+ timestamp: number;
155
+ updatedBy: string;
156
+ backupId: string;
157
+ changes?: ConfigChange[];
158
+ success: boolean;
159
+ error?: string;
160
+ }
161
+ /**
162
+ * Configuration deletion event
163
+ */
164
+ export interface ConfigDeletionEvent {
165
+ component: string;
166
+ timestamp: number;
167
+ deletedBy: string;
168
+ reason: string;
169
+ backupId: string;
170
+ success: boolean;
171
+ error?: string;
172
+ }
173
+ /**
174
+ * Generic configuration audit event
175
+ */
176
+ export interface ConfigAuditEvent {
177
+ eventId: string;
178
+ eventType: 'access' | 'update' | 'deletion' | 'backup' | 'restore';
179
+ component: string;
180
+ timestamp: number;
181
+ userId?: string;
182
+ details: Record<string, unknown>;
183
+ success: boolean;
184
+ error?: string;
185
+ }
186
+ /**
187
+ * Configuration change details
188
+ */
189
+ export interface ConfigChange {
190
+ field: string;
191
+ oldValue: unknown;
192
+ newValue: unknown;
193
+ changeType: 'added' | 'modified' | 'removed';
194
+ }
195
+ /**
196
+ * Time range for queries
197
+ */
198
+ export interface TimeRange {
199
+ start: number;
200
+ end: number;
201
+ }
202
+ /**
203
+ * Audit search criteria
204
+ */
205
+ export interface AuditSearchCriteria {
206
+ component?: string;
207
+ eventType?: string;
208
+ userId?: string;
209
+ timeRange?: TimeRange;
210
+ success?: boolean;
211
+ limit?: number;
212
+ offset?: number;
213
+ }
214
+ /**
215
+ * Configuration update authorization
216
+ */
217
+ export interface ConfigUpdateAuthorization {
218
+ userId: string;
219
+ permissions: string[];
220
+ sessionId: string;
221
+ timestamp: number;
222
+ reason?: string;
223
+ }
224
+ /**
225
+ * Authorization validation result
226
+ */
227
+ export interface AuthorizationResult {
228
+ authorized: boolean;
229
+ reason?: string;
230
+ permissions: string[];
231
+ restrictions: string[];
232
+ }
233
+ /**
234
+ * Configuration update result
235
+ */
236
+ export interface ConfigUpdateResult {
237
+ success: boolean;
238
+ backupId?: string;
239
+ errors?: ConfigValidationError[];
240
+ warnings?: ConfigValidationWarning[];
241
+ }
242
+ /**
243
+ * Configuration errors
244
+ */
245
+ export declare class InvalidConfigurationError extends Error {
246
+ constructor(errors: ConfigValidationError[]);
247
+ }
248
+ export declare class UnauthorizedConfigUpdateError extends Error {
249
+ constructor(reason: string);
250
+ }
251
+ export declare class ConfigurationUpdateFailedError extends Error {
252
+ constructor(message: string);
253
+ }
254
+ /**
255
+ * Secure Configuration Manager - Main implementation
256
+ */
257
+ export declare class SecureConfigManager {
258
+ private encryptedConfig;
259
+ private configValidators;
260
+ private configAuditLogger;
261
+ constructor();
262
+ /**
263
+ * Get secure configuration for component
264
+ */
265
+ getSecureConfiguration(component: string, userId?: string): Promise<SecureConfig>;
266
+ /**
267
+ * Update secure configuration
268
+ */
269
+ updateSecureConfiguration(component: string, newConfig: ConfigData, authorization: ConfigUpdateAuthorization): Promise<ConfigUpdateResult>;
270
+ /**
271
+ * Decrypt configuration data
272
+ */
273
+ private decryptConfiguration;
274
+ /**
275
+ * Encrypt configuration data
276
+ */
277
+ private encryptConfiguration;
278
+ /**
279
+ * Validate configuration
280
+ */
281
+ private validateConfiguration;
282
+ /**
283
+ * Validate update authorization
284
+ */
285
+ private validateUpdateAuthorization;
286
+ /**
287
+ * Create configuration backup
288
+ */
289
+ private createConfigurationBackup;
290
+ /**
291
+ * Restore from backup
292
+ */
293
+ private restoreFromBackup;
294
+ /**
295
+ * Generate checksum
296
+ */
297
+ private generateChecksum;
298
+ /**
299
+ * Register configuration schema
300
+ */
301
+ registerSchema(component: string, schema: ConfigSchema): void;
302
+ /**
303
+ * Get configuration audit history
304
+ */
305
+ getAuditHistory(component: string, timeRange: TimeRange): Promise<ConfigAuditEvent[]>;
306
+ /**
307
+ * Delete configuration
308
+ */
309
+ deleteConfiguration(component: string, authorization: ConfigUpdateAuthorization, reason: string): Promise<void>;
310
+ /**
311
+ * List all configuration components
312
+ */
313
+ listComponents(): Promise<string[]>;
314
+ /**
315
+ * Check if configuration exists
316
+ */
317
+ hasConfiguration(component: string): Promise<boolean>;
318
+ }
319
+ //# sourceMappingURL=secureConfigManager.d.ts.map