Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 2x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 14x 1x 1x 1x 12x 12x 12x 1x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 11x 11x 4x 4x 4x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 11x 6x 6x 11x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 11x 33x 33x 33x 33x 33x 33x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x 12x 12x 12x 11x 11x 11x 12x 12x 11x 11x 11x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 12x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 20x 20x 20x 20x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 2x 2x 6x 2x 2x 2x 2x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x | /**
* Advanced BuildHive Agent - Enhanced Agent Implementation
*
* Enhanced agent class with advanced features including:
* - Auto-update capabilities
* - Configuration hot-reloading
* - Advanced health checks
* - Performance optimization
*
* Requirements: 6.1
*/
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { EventEmitter } from 'events';
import { BuildHiveAgent, JobResult } from './agent.js';
import { AgentConfig } from './config/types.js';
import { ConfigLoader } from './config/loader.js';
import { createLogger } from './utils/logger.js';
import { AgentCapabilities, JobSubmissionRequest } from './types.js';
const logger = createLogger('advanced-agent');
export interface HealthCheckResult {
status: 'healthy' | 'warning' | 'critical';
checks: {
[key: string]: {
status: 'pass' | 'warn' | 'fail';
message: string;
value?: number;
threshold?: number;
};
};
timestamp: Date;
overallScore: number; // 0-100
}
export interface UpdateInfo {
currentVersion: string;
latestVersion: string;
updateAvailable: boolean;
releaseNotes?: string;
downloadUrl?: string;
critical?: boolean;
}
export interface PerformanceMetrics {
jobThroughput: number; // jobs per hour
averageJobDuration: number; // seconds
resourceEfficiency: number; // 0-100
errorRate: number; // percentage
uptime: number; // seconds
memoryLeakDetection: boolean;
cpuOptimization: number; // 0-100
}
export class AdvancedBuildHiveAgent extends EventEmitter {
private baseAgent: BuildHiveAgent;
private config: AgentConfig;
private configWatcher: fs.FSWatcher | null = null;
private configFileHash: string | null = null;
private healthCheckInterval: NodeJS.Timeout | null = null;
private updateCheckInterval: NodeJS.Timeout | null = null;
private performanceTracker: PerformanceTracker;
private isUpdating = false;
private lastHealthCheck: HealthCheckResult | null = null;
private jobHistory: Array<{ duration: number; success: boolean; timestamp: Date }> = [];
constructor(config: AgentConfig) {
super();
this.config = config;
this.baseAgent = new BuildHiveAgent(config);
this.performanceTracker = new PerformanceTracker();
this.setupAdvancedFeatures();
}
/**
* Start the advanced agent
*/
async start(): Promise<void> {
logger.info('Starting Advanced BuildHive Agent with enhanced features');
try {
// Start base agent
await this.baseAgent.start();
// Start advanced features
await this.startConfigWatcher();
await this.startHealthChecks();
await this.startUpdateChecker();
await this.startPerformanceOptimization();
logger.info('Advanced BuildHive Agent started successfully');
this.emit('started');
} catch (error) {
logger.error('Failed to start advanced agent:', error);
await this.cleanup();
throw error;
}
}
/**
* Stop the advanced agent
*/
async stop(): Promise<void> {
logger.info('Stopping Advanced BuildHive Agent...');
try {
await this.cleanup();
await this.baseAgent.stop();
logger.info('Advanced BuildHive Agent stopped successfully');
this.emit('stopped');
} catch (error) {
logger.error('Error during advanced agent shutdown:', error);
throw error;
}
}
/**
* Execute a job with performance tracking
*/
async executeJob(job: JobSubmissionRequest): Promise<JobResult> {
const startTime = Date.now();
try {
const result = await this.baseAgent.executeJob(job);
// Track performance
const duration = (Date.now() - startTime) / 1000;
this.jobHistory.push({
duration,
success: result.status === 'COMPLETED',
timestamp: new Date()
});
// Keep only last 100 jobs for performance tracking
if (this.jobHistory.length > 100) {
this.jobHistory = this.jobHistory.slice(-100);
}
this.performanceTracker.recordJob(duration, result.status === 'COMPLETED');
return result;
} catch (error) {
const duration = (Date.now() - startTime) / 1000;
this.jobHistory.push({
duration,
success: false,
timestamp: new Date()
});
this.performanceTracker.recordJob(duration, false);
throw error;
}
}
/**
* Get comprehensive agent status including advanced metrics
*/
getAdvancedStatus(): {
basic: ReturnType<BuildHiveAgent['getStatus']>;
health: HealthCheckResult | null;
performance: PerformanceMetrics;
updateInfo: UpdateInfo | null;
configStatus: {
lastReload: Date | null;
watcherActive: boolean;
configFile: string | null;
};
} {
return {
basic: this.baseAgent.getStatus(),
health: this.lastHealthCheck,
performance: this.performanceTracker.getMetrics(),
updateInfo: null, // Will be populated by update checker
configStatus: {
lastReload: null, // Will be tracked
watcherActive: this.configWatcher !== null,
configFile: ConfigLoader.findConfigFile()
}
};
}
/**
* Perform manual health check
*/
async performHealthCheck(): Promise<HealthCheckResult> {
logger.debug('Performing comprehensive health check');
const checks: HealthCheckResult['checks'] = {};
let totalScore = 0;
let checkCount = 0;
// System resource checks
const systemMetrics = await this.getSystemMetrics();
// CPU usage check
checks.cpuUsage = {
status: systemMetrics.cpuUsage > 90 ? 'fail' : systemMetrics.cpuUsage > 70 ? 'warn' : 'pass',
message: `CPU usage: ${systemMetrics.cpuUsage.toFixed(1)}%`,
value: systemMetrics.cpuUsage,
threshold: 70
};
totalScore += checks.cpuUsage.status === 'pass' ? 100 : checks.cpuUsage.status === 'warn' ? 50 : 0;
checkCount++;
// Memory usage check
checks.memoryUsage = {
status: systemMetrics.memoryUsage > 90 ? 'fail' : systemMetrics.memoryUsage > 80 ? 'warn' : 'pass',
message: `Memory usage: ${systemMetrics.memoryUsage.toFixed(1)}%`,
value: systemMetrics.memoryUsage,
threshold: 80
};
totalScore += checks.memoryUsage.status === 'pass' ? 100 : checks.memoryUsage.status === 'warn' ? 50 : 0;
checkCount++;
// Disk usage check
checks.diskUsage = {
status: systemMetrics.diskUsage > 95 ? 'fail' : systemMetrics.diskUsage > 85 ? 'warn' : 'pass',
message: `Disk usage: ${systemMetrics.diskUsage.toFixed(1)}%`,
value: systemMetrics.diskUsage,
threshold: 85
};
totalScore += checks.diskUsage.status === 'pass' ? 100 : checks.diskUsage.status === 'warn' ? 50 : 0;
checkCount++;
// Job performance check
const performance = this.performanceTracker.getMetrics();
checks.jobPerformance = {
status: performance.errorRate > 20 ? 'fail' : performance.errorRate > 10 ? 'warn' : 'pass',
message: `Job error rate: ${performance.errorRate.toFixed(1)}%`,
value: performance.errorRate,
threshold: 10
};
totalScore += checks.jobPerformance.status === 'pass' ? 100 : checks.jobPerformance.status === 'warn' ? 50 : 0;
checkCount++;
// Connection health check
const baseStatus = this.baseAgent.getStatus();
checks.connectivity = {
status: baseStatus.isRunning ? 'pass' : 'fail',
message: baseStatus.isRunning ? 'Connected to platform' : 'Disconnected from platform'
};
totalScore += checks.connectivity.status === 'pass' ? 100 : 0;
checkCount++;
// Docker health check
checks.dockerHealth = await this.checkDockerHealth();
totalScore += checks.dockerHealth.status === 'pass' ? 100 : checks.dockerHealth.status === 'warn' ? 50 : 0;
checkCount++;
const overallScore = checkCount > 0 ? totalScore / checkCount : 0;
const status: HealthCheckResult['status'] =
overallScore >= 80 ? 'healthy' :
overallScore >= 60 ? 'warning' : 'critical';
const result: HealthCheckResult = {
status,
checks,
timestamp: new Date(),
overallScore
};
this.lastHealthCheck = result;
this.emit('healthCheck', result);
return result;
}
/**
* Trigger manual configuration reload
*/
async reloadConfiguration(): Promise<void> {
logger.info('Manually reloading configuration');
try {
const newConfig = await ConfigLoader.load();
await this.applyConfigurationChanges(newConfig);
logger.info('Configuration reloaded successfully');
this.emit('configReloaded', newConfig);
} catch (error) {
logger.error('Failed to reload configuration:', error);
this.emit('configReloadError', error);
throw error;
}
}
/**
* Check for and apply updates
*/
async checkForUpdates(): Promise<UpdateInfo> {
logger.debug('Checking for agent updates');
try {
// In a real implementation, this would check a remote update server
const updateInfo: UpdateInfo = {
currentVersion: this.getCurrentVersion(),
latestVersion: await this.getLatestVersion(),
updateAvailable: false
};
updateInfo.updateAvailable = this.compareVersions(updateInfo.latestVersion, updateInfo.currentVersion) > 0;
if (updateInfo.updateAvailable) {
logger.info(`Update available: ${updateInfo.currentVersion} -> ${updateInfo.latestVersion}`);
this.emit('updateAvailable', updateInfo);
if (this.config.enableAutoUpdates) {
await this.performUpdate(updateInfo);
}
}
return updateInfo;
} catch (error) {
logger.error('Failed to check for updates:', error);
throw error;
}
}
/**
* Setup advanced features
*/
private setupAdvancedFeatures(): void {
// Set up performance optimization
this.optimizePerformance();
// Set up event handlers
this.on('healthCheck', (result: HealthCheckResult) => {
if (result.status === 'critical') {
logger.warn('Critical health check failure detected');
// Could trigger alerts or recovery actions
}
});
this.on('configReloaded', (config: AgentConfig) => {
logger.info('Configuration successfully reloaded');
});
this.on('updateAvailable', (updateInfo: UpdateInfo) => {
logger.info(`Update available: ${updateInfo.latestVersion}`);
});
}
/**
* Start configuration file watcher for hot-reloading
*/
private async startConfigWatcher(): Promise<void> {
const configFile = ConfigLoader.findConfigFile();
if (!configFile) {
logger.debug('No configuration file found, skipping config watcher');
return;
}
try {
// Calculate initial hash
this.configFileHash = await this.calculateFileHash(configFile);
// Watch for changes
this.configWatcher = fs.watch(configFile, async (eventType) => {
if (eventType === 'change') {
await this.handleConfigFileChange(configFile);
}
});
logger.info(`Configuration watcher started for: ${configFile}`);
} catch (error) {
logger.error('Failed to start configuration watcher:', error);
}
}
/**
* Start periodic health checks
*/
private async startHealthChecks(): Promise<void> {
// Perform initial health check
await this.performHealthCheck();
// Schedule periodic health checks
this.healthCheckInterval = setInterval(async () => {
try {
await this.performHealthCheck();
} catch (error) {
logger.error('Health check failed:', error);
}
}, 60000); // Every minute
logger.info('Health check monitoring started');
}
/**
* Start update checker
*/
private async startUpdateChecker(): Promise<void> {
if (!this.config.enableAutoUpdates) {
logger.debug('Auto-updates disabled, skipping update checker');
return;
}
// Check for updates immediately
try {
await this.checkForUpdates();
} catch (error) {
logger.error('Initial update check failed:', error);
}
// Schedule periodic update checks
this.updateCheckInterval = setInterval(async () => {
try {
await this.checkForUpdates();
} catch (error) {
logger.error('Periodic update check failed:', error);
}
}, 4 * 60 * 60 * 1000); // Every 4 hours
logger.info('Update checker started');
}
/**
* Start performance optimization
*/
private async startPerformanceOptimization(): Promise<void> {
// Enable Node.js performance optimizations
if (process.env.NODE_ENV === 'production') {
// Optimize garbage collection
if (process.argv.indexOf('--max-old-space-size') === -1) {
logger.info('Applying memory optimization settings');
}
}
// Start performance monitoring
setInterval(() => {
this.performanceTracker.collectSystemMetrics();
}, 30000); // Every 30 seconds
logger.info('Performance optimization started');
}
/**
* Handle configuration file changes
*/
private async handleConfigFileChange(configFile: string): Promise<void> {
try {
// Debounce rapid changes
await new Promise(resolve => setTimeout(resolve, 1000));
const newHash = await this.calculateFileHash(configFile);
if (newHash === this.configFileHash) {
return; // No actual change
}
logger.info('Configuration file changed, reloading...');
this.configFileHash = newHash;
const newConfig = await ConfigLoader.load();
await this.applyConfigurationChanges(newConfig);
logger.info('Configuration hot-reloaded successfully');
this.emit('configReloaded', newConfig);
} catch (error) {
logger.error('Failed to handle configuration file change:', error);
this.emit('configReloadError', error);
}
}
/**
* Apply configuration changes
*/
private async applyConfigurationChanges(newConfig: AgentConfig): Promise<void> {
const oldConfig = this.config;
this.config = newConfig;
// Check what changed and apply accordingly
if (oldConfig.heartbeatInterval !== newConfig.heartbeatInterval) {
logger.info(`Heartbeat interval changed: ${oldConfig.heartbeatInterval}s -> ${newConfig.heartbeatInterval}s`);
// Would need to restart heartbeat with new interval
}
if (oldConfig.maxConcurrentJobs !== newConfig.maxConcurrentJobs) {
logger.info(`Max concurrent jobs changed: ${oldConfig.maxConcurrentJobs} -> ${newConfig.maxConcurrentJobs}`);
// Update job capacity
}
if (oldConfig.logLevel !== newConfig.logLevel) {
logger.info(`Log level changed: ${oldConfig.logLevel} -> ${newConfig.logLevel}`);
// Update logger configuration
}
// Apply other configuration changes as needed
}
/**
* Get system metrics
*/
private async getSystemMetrics(): Promise<{
cpuUsage: number;
memoryUsage: number;
diskUsage: number;
}> {
// This would use the existing metrics collector
// For now, return mock data
return {
cpuUsage: Math.random() * 100,
memoryUsage: Math.random() * 100,
diskUsage: Math.random() * 100
};
}
/**
* Check Docker health
*/
private async checkDockerHealth(): Promise<{
status: 'pass' | 'warn' | 'fail';
message: string;
}> {
try {
// This would check Docker daemon status
// For now, return a mock check
return {
status: 'pass',
message: 'Docker daemon is running and accessible'
};
} catch (error) {
return {
status: 'fail',
message: `Docker health check failed: ${error}`
};
}
}
/**
* Calculate file hash for change detection
*/
private async calculateFileHash(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
/**
* Get current agent version
*/
private getCurrentVersion(): string {
// In a real implementation, this would read from package.json or version file
return '1.0.0';
}
/**
* Get latest available version
*/
private async getLatestVersion(): Promise<string> {
// In a real implementation, this would query a remote update server
return '1.0.0';
}
/**
* Compare version strings
*/
private compareVersions(a: string, b: string): number {
const aParts = a.split('.').map(Number);
const bParts = b.split('.').map(Number);
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
const aPart = aParts[i] || 0;
const bPart = bParts[i] || 0;
if (aPart > bPart) return 1;
if (aPart < bPart) return -1;
}
return 0;
}
/**
* Perform agent update
*/
private async performUpdate(updateInfo: UpdateInfo): Promise<void> {
if (this.isUpdating) {
logger.warn('Update already in progress');
return;
}
this.isUpdating = true;
logger.info(`Starting update to version ${updateInfo.latestVersion}`);
try {
// In a real implementation, this would:
// 1. Download the new version
// 2. Verify the download
// 3. Stop the current agent gracefully
// 4. Replace the binary
// 5. Restart the agent
this.emit('updateStarted', updateInfo);
// Mock update process
await new Promise(resolve => setTimeout(resolve, 5000));
this.emit('updateCompleted', updateInfo);
logger.info('Update completed successfully');
} catch (error) {
logger.error('Update failed:', error);
this.emit('updateFailed', { updateInfo, error });
throw error;
} finally {
this.isUpdating = false;
}
}
/**
* Optimize performance settings
*/
private optimizePerformance(): void {
// Set optimal Node.js flags for performance
if (process.env.NODE_ENV === 'production') {
// These would typically be set at startup
logger.debug('Performance optimizations applied');
}
// Configure garbage collection optimization
if (global.gc) {
setInterval(() => {
if (process.memoryUsage().heapUsed > 100 * 1024 * 1024) { // 100MB
global.gc?.();
}
}, 60000); // Every minute
}
}
/**
* Clean up resources
*/
private async cleanup(): Promise<void> {
// Stop config watcher
if (this.configWatcher) {
this.configWatcher.close();
this.configWatcher = null;
}
// Stop intervals
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
this.healthCheckInterval = null;
}
if (this.updateCheckInterval) {
clearInterval(this.updateCheckInterval);
this.updateCheckInterval = null;
}
logger.debug('Advanced agent cleanup completed');
}
}
/**
* Performance tracking utility
*/
class PerformanceTracker {
private jobStats: Array<{ duration: number; success: boolean; timestamp: Date }> = [];
private startTime = Date.now();
recordJob(duration: number, success: boolean): void {
this.jobStats.push({
duration,
success,
timestamp: new Date()
});
// Keep only last 1000 jobs
if (this.jobStats.length > 1000) {
this.jobStats = this.jobStats.slice(-1000);
}
}
getMetrics(): PerformanceMetrics {
const now = Date.now();
const uptime = (now - this.startTime) / 1000;
if (this.jobStats.length === 0) {
return {
jobThroughput: 0,
averageJobDuration: 0,
resourceEfficiency: 100,
errorRate: 0,
uptime,
memoryLeakDetection: false,
cpuOptimization: 100
};
}
const recentJobs = this.jobStats.filter(job =>
now - job.timestamp.getTime() < 60 * 60 * 1000 // Last hour
);
const totalJobs = recentJobs.length;
const successfulJobs = recentJobs.filter(job => job.success).length;
const failedJobs = totalJobs - successfulJobs;
const jobThroughput = totalJobs > 0 ? (totalJobs / (60 * 60)) * 3600 : 0; // jobs per hour
const averageJobDuration = totalJobs > 0 ?
recentJobs.reduce((sum, job) => sum + job.duration, 0) / totalJobs : 0;
const errorRate = totalJobs > 0 ? (failedJobs / totalJobs) * 100 : 0;
return {
jobThroughput,
averageJobDuration,
resourceEfficiency: Math.max(0, 100 - errorRate), // Simple efficiency calculation
errorRate,
uptime,
memoryLeakDetection: this.detectMemoryLeak(),
cpuOptimization: this.calculateCpuOptimization()
};
}
collectSystemMetrics(): void {
// Collect system metrics for performance analysis
const memUsage = process.memoryUsage();
const cpuUsage = process.cpuUsage();
// Store metrics for trend analysis
// This would be expanded in a real implementation
}
private detectMemoryLeak(): boolean {
const memUsage = process.memoryUsage();
// Simple memory leak detection based on heap growth
return memUsage.heapUsed > 500 * 1024 * 1024; // 500MB threshold
}
private calculateCpuOptimization(): number {
// Calculate CPU optimization score based on job efficiency
const recentJobs = this.jobStats.slice(-10); // Last 10 jobs
if (recentJobs.length === 0) return 100;
const avgDuration = recentJobs.reduce((sum, job) => sum + job.duration, 0) / recentJobs.length;
const successRate = recentJobs.filter(job => job.success).length / recentJobs.length;
// Simple optimization score
return Math.min(100, (successRate * 100) - (avgDuration / 60)); // Penalize long durations
}
} |