File size: 11,354 Bytes
857cdcf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | /**
* Chahuadev Framework - Context Manager Module
* Pipeline Context Object Management & Data Flow Tracking
*
* Chahua Development Thailand
* CEO: Saharath C.
* www.chahuadev.com
*/
const crypto = require('crypto');
class ContextManager {
constructor() {
this.contexts = new Map(); // Store active contexts
console.log(' Context Manager initialized');
}
/**
* Create new pipeline context
* @param {string} pipelineType - Type of pipeline (e.g., 'execution', 'api', 'validation')
* @param {Object} initialData - Initial request data
* @returns {Object} Pipeline context object
*/
create(pipelineType = 'execution', initialData = {}) {
const pipelineId = this.generatePipelineId();
const timestamp = new Date().toISOString();
const context = {
// Pipeline identification
pipelineId: pipelineId,
pipelineType: pipelineType,
timestamp: timestamp,
// Request information
request: {
command: initialData.command || '',
originalData: initialData || {},
parameters: this.parseParameters(initialData),
source: initialData.source || 'unknown'
},
// System information (will be populated by system-detector)
systemInfo: {
detectedType: null,
projectPath: null,
strategy: null,
dependencies: [],
environment: process.env.NODE_ENV || 'development'
},
// Security context
security: {
keyHash: null,
permissionLevel: 'basic',
userSession: null,
securityChecks: [],
validatedAt: null
},
// Execution tracking
execution: {
strategy: null,
startTime: null,
endTime: null,
status: 'pending', // 'pending', 'running', 'completed', 'failed'
exitCode: null,
output: null
},
// Step tracking
steps: [],
// Performance metrics
performance: {
totalTime: null,
memoryUsage: process.memoryUsage(),
cacheHit: false,
stepTimings: {}
},
// Error tracking
error: null,
// Metadata
metadata: {
createdAt: timestamp,
updatedAt: timestamp,
version: '1.0.0',
framework: 'chahuadev'
}
};
// Store context for tracking
this.contexts.set(pipelineId, context);
console.log(` Context created: ${pipelineId} (${pipelineType})`);
return context;
}
/**
* Add step result to context
* @param {Object} context - Pipeline context
* @param {string} stepName - Name of the step
* @param {string} status - Step status ('started', 'completed', 'failed')
* @param {*} result - Step result data
* @returns {Object} Updated context
*/
addStep(context, stepName, status, result = null) {
if (!context || !context.pipelineId) {
throw new Error('Invalid context provided');
}
const step = {
stepName: stepName,
timestamp: new Date().toISOString(),
status: status,
result: result,
duration: null
};
// Calculate duration if completing a step
if (status === 'completed' || status === 'failed') {
const startStep = context.steps.find(s =>
s.stepName === stepName && s.status === 'started'
);
if (startStep) {
step.duration = Date.now() - new Date(startStep.timestamp).getTime();
context.performance.stepTimings[stepName] = step.duration;
}
}
context.steps.push(step);
context.metadata.updatedAt = new Date().toISOString();
console.log(` Step added: ${stepName} (${status}) to ${context.pipelineId}`);
return context;
}
/**
* Update context security information
* @param {Object} context - Pipeline context
* @param {Object} securityData - Security validation data
* @returns {Object} Updated context
*/
updateSecurity(context, securityData) {
if (!context || !context.pipelineId) {
throw new Error('Invalid context provided');
}
context.security = {
...context.security,
...securityData,
validatedAt: new Date().toISOString()
};
context.metadata.updatedAt = new Date().toISOString();
console.log(` Security updated for: ${context.pipelineId}`);
return context;
}
/**
* Update system information
* @param {Object} context - Pipeline context
* @param {Object} systemData - System detection data
* @returns {Object} Updated context
*/
updateSystemInfo(context, systemData) {
if (!context || !context.pipelineId) {
throw new Error('Invalid context provided');
}
context.systemInfo = {
...context.systemInfo,
...systemData
};
context.metadata.updatedAt = new Date().toISOString();
console.log(` System info updated for: ${context.pipelineId}`);
return context;
}
/**
* Update execution status
* @param {Object} context - Pipeline context
* @param {string} status - Execution status
* @param {*} output - Execution output
* @param {number} exitCode - Exit code
* @returns {Object} Updated context
*/
updateExecution(context, status, output = null, exitCode = null) {
if (!context || !context.pipelineId) {
throw new Error('Invalid context provided');
}
// Set start time when execution begins
if (status === 'running' && !context.execution.startTime) {
context.execution.startTime = new Date().toISOString();
}
// Set end time when execution completes or fails
if ((status === 'completed' || status === 'failed') && !context.execution.endTime) {
context.execution.endTime = new Date().toISOString();
// Calculate total time
if (context.execution.startTime) {
const startTime = new Date(context.execution.startTime).getTime();
const endTime = new Date(context.execution.endTime).getTime();
context.performance.totalTime = endTime - startTime;
}
}
context.execution.status = status;
if (output !== null) context.execution.output = output;
if (exitCode !== null) context.execution.exitCode = exitCode;
context.metadata.updatedAt = new Date().toISOString();
console.log(` Execution updated: ${status} for ${context.pipelineId}`);
return context;
}
/**
* Set error in context
* @param {Object} context - Pipeline context
* @param {Error|string} error - Error object or message
* @returns {Object} Updated context
*/
setError(context, error) {
if (!context || !context.pipelineId) {
throw new Error('Invalid context provided');
}
const errorInfo = {
message: error.message || error,
stack: error.stack || null,
timestamp: new Date().toISOString(),
step: context.steps.length > 0 ? context.steps[context.steps.length - 1].stepName : 'unknown'
};
context.error = errorInfo;
context.execution.status = 'failed';
context.metadata.updatedAt = new Date().toISOString();
console.error(` Error set for ${context.pipelineId}:`, errorInfo.message);
return context;
}
/**
* Get context by pipeline ID
* @param {string} pipelineId - Pipeline ID
* @returns {Object|null} Context object or null if not found
*/
get(pipelineId) {
return this.contexts.get(pipelineId) || null;
}
/**
* Remove context (cleanup)
* @param {string} pipelineId - Pipeline ID
* @returns {boolean} True if removed
*/
remove(pipelineId) {
const removed = this.contexts.delete(pipelineId);
if (removed) {
console.log(` Context removed: ${pipelineId}`);
}
return removed;
}
/**
* Clear context by execution ID (alias for remove)
* @param {string} executionId - Execution ID
* @returns {boolean} True if removed
*/
clearContext(executionId) {
return this.remove(executionId);
}
/**
* Create context object (for BaseStrategy compatibility)
* @param {Object} data - Context data
* @returns {Object} Context object
*/
createContext(data) {
return data; // Return as-is since BaseStrategy creates its own context
}
/**
* Generate unique pipeline ID
* @private
* @returns {string} Pipeline ID
*/
generatePipelineId() {
const timestamp = Date.now();
const random = crypto.randomBytes(4).toString('hex');
return `pipe_${timestamp}_${random}`;
}
/**
* Parse parameters from initial data
* @private
* @param {Object} data - Initial data
* @returns {Object} Parsed parameters
*/
parseParameters(data) {
if (!data || typeof data !== 'object') {
return {};
}
// Extract common parameters
return {
timeout: data.timeout || 30000,
retry: data.retry || false,
maxRetries: data.maxRetries || 3,
silent: data.silent || false,
workingDir: data.workingDir || process.cwd()
};
}
/**
* Get all active contexts (for monitoring)
* @returns {Array} Array of context objects
*/
getAll() {
return Array.from(this.contexts.values());
}
/**
* Clean up old contexts (older than specified minutes)
* @param {number} maxAgeMinutes - Maximum age in minutes
* @returns {number} Number of cleaned contexts
*/
cleanup(maxAgeMinutes = 60) {
const cutoffTime = Date.now() - (maxAgeMinutes * 60 * 1000);
let cleaned = 0;
for (const [pipelineId, context] of this.contexts.entries()) {
const contextTime = new Date(context.metadata.createdAt).getTime();
if (contextTime < cutoffTime) {
this.contexts.delete(pipelineId);
cleaned++;
}
}
if (cleaned > 0) {
console.log(` Cleaned up ${cleaned} old contexts`);
}
return cleaned;
}
/**
* Get context manager status
* @returns {Object} Status information
*/
getStatus() {
return {
activeContexts: this.contexts.size,
memoryUsage: process.memoryUsage(),
ready: true
};
}
}
// Export class (not singleton)
module.exports = ContextManager; |