chahuadev-framework-en / modules /context-manager.js
chahuadev
Update README
857cdcf
/**
* 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;