File size: 8,182 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 | /**
* executor.js - Execution Strategy Manager (Level 5)
* สำหรับ Chahuadev Framework
*
* ใช้: system-detector.js (Level 4), validation_gateway.js (Level 4)
* จัดการ: Strategy selection, execution flow, error handling
*/
const SystemDetector = require('./system-detector');
const ErrorHandler = require('./error-handler');
const ContextManager = require('./context-manager');
class Executor {
constructor() {
this.systemDetector = new SystemDetector();
this.errorHandler = new ErrorHandler();
this.contextManager = new ContextManager();
this.executionHistory = [];
this.maxHistorySize = 100;
console.log(' Executor initialized - ready for strategy execution');
}
/**
* Main execution method
*/
async execute(request) {
const executionId = this.generateExecutionId();
const startTime = Date.now();
try {
console.log(` Starting execution [${executionId}]`);
// Phase 1: Use request as-is (validation done by ValidationGateway)
const validationResult = {
success: true,
sessionId: 'exec_' + Date.now(),
userId: request.userId || 'system',
permissions: request.permissions || 'admin',
level: 'admin'
};
// Phase 2: Context Preparation
const executionContext = this.prepareExecutionContext(request, executionId, validationResult);
// Phase 3: System Detection
const detectionResult = await this.systemDetector.detect(
executionContext.projectPath,
executionContext
);
// Phase 4: Strategy Execution
const executionResult = await this.executeWithStrategy(
detectionResult.strategy,
executionContext
);
// Phase 5: Result Processing
const finalResult = this.processExecutionResult(
executionResult,
detectionResult,
executionContext,
startTime
);
this.recordExecution(finalResult);
console.log(` Execution completed [${executionId}] in ${finalResult.totalDuration}ms`);
return finalResult;
} catch (error) {
console.log(` Execution failed [${executionId}]: ${error.message}`);
const errorResult = this.handleExecutionError(error, request, executionId, startTime);
this.recordExecution(errorResult);
return errorResult;
}
}
/**
* เตรียม execution context
*/
prepareExecutionContext(request, executionId, validationResult) {
// จัดการ command และ args
let fullCommand;
if (request.args && Array.isArray(request.args) && request.args.length > 0) {
// ถ้ามี args แยกมา ให้รวมกับ command
fullCommand = `${request.command} ${request.args.join(' ')}`;
} else {
// ถ้าไม่มี args ใช้ command ตรงๆ
fullCommand = request.command;
}
const context = this.contextManager.createContext({
executionId: executionId,
command: fullCommand,
originalCommand: request.command, // เก็บ command เดิมไว้
args: request.args || [], // เก็บ args แยกไว้
projectPath: request.projectPath || process.cwd(),
options: request.options || {},
sessionId: validationResult.sessionId,
userId: validationResult.userId,
permissions: validationResult.permissions,
timestamp: Date.now(),
platform: process.platform,
nodeVersion: process.version,
isSecure: validationResult.success,
validationLevel: validationResult.level
});
console.log(` Execution context prepared: ${context.executionId}`);
return context;
}
/**
* รัน command ด้วย strategy
*/
async executeWithStrategy(strategy, executionContext) {
console.log(` Executing with strategy: ${strategy.name}`);
const strategyStatus = await strategy.getStatus();
if (strategyStatus.status !== 'READY') {
throw new Error(`Strategy not ready: ${strategy.name}`);
}
const result = await strategy.execute(executionContext);
console.log(` Strategy execution completed: ${strategy.name}`);
return result;
}
/**
* ประมวลผลผลลัพธ์
*/
processExecutionResult(executionResult, detectionResult, executionContext, startTime) {
return {
success: executionResult.success,
executionId: executionContext.executionId,
command: executionContext.command,
projectPath: executionContext.projectPath,
strategy: detectionResult.type,
confidence: detectionResult.confidence,
output: executionResult.output,
exitCode: executionResult.exitCode,
error: executionResult.error,
totalDuration: Date.now() - startTime,
strategyDuration: executionResult.duration,
sessionId: executionContext.sessionId,
userId: executionContext.userId,
timestamp: startTime,
platform: executionContext.platform
};
}
/**
* จัดการ error
*/
handleExecutionError(error, request, executionId, startTime) {
this.errorHandler.logError('EXECUTION_FAILED', error, {
executionId: executionId,
request: request
});
return {
success: false,
executionId: executionId,
error: error.message,
command: request.command,
projectPath: request.projectPath,
totalDuration: Date.now() - startTime,
timestamp: startTime,
errorType: error.constructor.name
};
}
/**
* บันทึก execution history
*/
recordExecution(result) {
this.executionHistory.unshift(result);
if (this.executionHistory.length > this.maxHistorySize) {
this.executionHistory = this.executionHistory.slice(0, this.maxHistorySize);
}
console.log(` Execution recorded: ${result.executionId}`);
}
/**
* รัน command แบบง่าย
*/
async run(command, projectPath = process.cwd(), options = {}) {
return this.execute({
command: command,
projectPath: projectPath,
options: options
});
}
/**
* รายงานสถานะ
*/
async getStatus() {
const systemStatus = await this.systemDetector.getStatus();
return {
executor: 'ExecutionManager',
status: 'READY',
components: {
systemDetector: systemStatus
},
executionHistory: {
total: this.executionHistory.length,
successful: this.executionHistory.filter(r => r.success).length,
failed: this.executionHistory.filter(r => !r.success).length
},
timestamp: Date.now()
};
}
/**
* สร้าง execution ID
*/
generateExecutionId() {
return `exec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
}
/**
* ดู execution history
*/
getHistory(limit = 10) {
return this.executionHistory.slice(0, limit);
}
/**
* ล้าง history
*/
clearHistory() {
this.executionHistory = [];
console.log(' Execution history cleared');
}
}
module.exports = Executor; |