tyrion-git-mcp
Version:
Revolutionary Git MCP with Rust+WASM+TypeScript - 3x-10x performance boost vs traditional solutions
237 lines • 8.82 kB
JavaScript
// S04 Git MCP Server - Revolutionary Performance Monitor
// Tony Stark's JARVIS-Level Performance Intelligence
import { logger } from '../logger.js';
/**
* Revolutionary Performance Monitor
*
* JARVIS-level intelligence for monitoring and optimizing
* Git operation performance in real-time
*/
export class PerformanceMonitor {
metrics;
isRunning = false;
monitoringInterval = null;
constructor() {
this.metrics = this.initializeMetrics();
}
/**
* Initialize performance metrics
*/
initializeMetrics() {
return {
totalOperations: 0,
successfulOperations: 0,
failedOperations: 0,
averageLatency: 0,
operationCounts: {},
operationLatencies: {},
startTime: Date.now(),
};
}
/**
* Start performance monitoring
*/
start() {
if (this.isRunning) {
return;
}
this.isRunning = true;
this.metrics.startTime = Date.now();
// Start periodic metrics reporting
this.monitoringInterval = setInterval(() => {
this.reportMetrics();
}, 60000); // Report every minute
logger.info('📊 Performance monitoring started - JARVIS intelligence active');
}
/**
* Stop performance monitoring
*/
stop() {
if (!this.isRunning) {
return;
}
this.isRunning = false;
if (this.monitoringInterval) {
clearInterval(this.monitoringInterval);
this.monitoringInterval = null;
}
logger.info('📊 Performance monitoring stopped');
}
/**
* Record operation performance
*/
recordOperation(operation, duration, success) {
// Update total counts
this.metrics.totalOperations++;
if (success) {
this.metrics.successfulOperations++;
}
else {
this.metrics.failedOperations++;
}
// Update operation-specific metrics
if (!this.metrics.operationCounts[operation]) {
this.metrics.operationCounts[operation] = 0;
this.metrics.operationLatencies[operation] = [];
}
this.metrics.operationCounts[operation]++;
this.metrics.operationLatencies[operation].push(duration);
// Keep only last 100 latencies for each operation to prevent memory growth
if (this.metrics.operationLatencies[operation].length > 100) {
this.metrics.operationLatencies[operation].shift();
}
// Update average latency
this.updateAverageLatency();
// Log performance for significant operations
if (duration > 1000) { // Log operations over 1 second
logger.performance(operation, duration, success);
}
// Detect performance anomalies
this.detectAnomalies(operation, duration, success);
}
/**
* Update average latency
*/
updateAverageLatency() {
let totalLatency = 0;
let totalCount = 0;
for (const latencies of Object.values(this.metrics.operationLatencies)) {
for (const latency of latencies) {
totalLatency += latency;
totalCount++;
}
}
this.metrics.averageLatency = totalCount > 0 ? totalLatency / totalCount : 0;
}
/**
* Detect performance anomalies
*/
detectAnomalies(operation, duration, success) {
const latencies = this.metrics.operationLatencies[operation];
if (latencies.length < 5) {
return; // Not enough data
}
// Calculate average for this operation
const average = latencies.reduce((sum, lat) => sum + lat, 0) / latencies.length;
// Alert if current duration is significantly higher than average
if (duration > average * 3) {
logger.warn(`🐌 Performance anomaly detected: ${operation} took ${duration.toFixed(2)}ms (avg: ${average.toFixed(2)}ms)`);
}
// Alert if operation failed
if (!success) {
logger.warn(`💥 Operation failed: ${operation} after ${duration.toFixed(2)}ms`);
}
// Alert if too many recent failures
const recentLatencies = latencies.slice(-10);
const recentFailures = recentLatencies.filter(lat => lat === -1).length; // -1 indicates failure
if (recentFailures > 3) {
logger.warn(`🚨 High failure rate detected for ${operation}: ${recentFailures}/10 recent operations failed`);
}
}
/**
* Get current performance metrics
*/
getMetrics() {
return { ...this.metrics };
}
/**
* Get performance summary
*/
getPerformanceSummary() {
const uptime = Date.now() - this.metrics.startTime;
const successRate = this.metrics.totalOperations > 0
? (this.metrics.successfulOperations / this.metrics.totalOperations) * 100
: 0;
// Get top slow operations
const slowOperations = Object.entries(this.metrics.operationLatencies)
.map(([operation, latencies]) => ({
operation,
averageLatency: latencies.reduce((sum, lat) => sum + lat, 0) / latencies.length,
count: latencies.length,
}))
.sort((a, b) => b.averageLatency - a.averageLatency)
.slice(0, 5);
// Get most frequent operations
const frequentOperations = Object.entries(this.metrics.operationCounts)
.sort(([, a], [, b]) => b - a)
.slice(0, 5)
.map(([operation, count]) => ({ operation, count }));
return {
uptime: Math.floor(uptime / 1000), // seconds
totalOperations: this.metrics.totalOperations,
successfulOperations: this.metrics.successfulOperations,
failedOperations: this.metrics.failedOperations,
successRate: Math.round(successRate * 100) / 100,
averageLatency: Math.round(this.metrics.averageLatency * 100) / 100,
operationsPerSecond: this.metrics.totalOperations / (uptime / 1000),
topSlowOperations: slowOperations,
mostFrequentOperations: frequentOperations,
};
}
/**
* Report metrics periodically
*/
reportMetrics() {
const summary = this.getPerformanceSummary();
logger.info('📈 Performance Report:', {
uptime: `${summary.uptime}s`,
operations: summary.totalOperations,
successRate: `${summary.successRate}%`,
avgLatency: `${summary.averageLatency}ms`,
opsPerSec: summary.operationsPerSecond.toFixed(2),
});
// Alert on poor performance
if (summary.successRate < 95 && summary.totalOperations > 10) {
logger.warn(`⚠️ Low success rate detected: ${summary.successRate}%`);
}
if (summary.averageLatency > 500) {
logger.warn(`⚠️ High average latency detected: ${summary.averageLatency}ms`);
}
}
/**
* Reset all metrics
*/
reset() {
this.metrics = this.initializeMetrics();
logger.info('🔄 Performance metrics reset');
}
/**
* Get operation-specific statistics
*/
getOperationStats(operation) {
const latencies = this.metrics.operationLatencies[operation];
const count = this.metrics.operationCounts[operation];
if (!latencies || !count) {
return null;
}
const sortedLatencies = [...latencies].sort((a, b) => a - b);
const average = latencies.reduce((sum, lat) => sum + lat, 0) / latencies.length;
return {
operation,
count,
averageLatency: Math.round(average * 100) / 100,
minLatency: sortedLatencies[0],
maxLatency: sortedLatencies[sortedLatencies.length - 1],
medianLatency: sortedLatencies[Math.floor(sortedLatencies.length / 2)],
p95Latency: sortedLatencies[Math.floor(sortedLatencies.length * 0.95)],
p99Latency: sortedLatencies[Math.floor(sortedLatencies.length * 0.99)],
};
}
/**
* Export metrics for analysis
*/
exportMetrics() {
return {
timestamp: new Date().toISOString(),
serverInfo: {
version: '2.0.0',
architecture: 'Rust+WASM+TypeScript',
uptime: Date.now() - this.metrics.startTime,
},
metrics: this.metrics,
summary: this.getPerformanceSummary(),
operationStats: Object.keys(this.metrics.operationCounts).map(op => this.getOperationStats(op)).filter(stat => stat !== null),
};
}
}
//# sourceMappingURL=monitor.js.map