fortify2-js
Version:
MOST POWERFUL JavaScript Security Library! Military-grade cryptography + 19 enhanced object methods + quantum-resistant algorithms + perfect TypeScript support. More powerful than Lodash with built-in security.
233 lines (229 loc) • 6.8 kB
JavaScript
'use strict';
var smartCache = require('./smart-cache.js');
var analyticsEngine = require('./analytics-engine.js');
var index = require('../memory/index.js');
/**
* FortifyJS - Enhanced Performance Monitor
* Advanced performance tracking with smart caching and analytics
*/
class PerformanceMonitor {
constructor(cacheConfig) {
this.auditLog = [];
this.performanceHistory = [];
this.lastCleanupTime = Date.now();
this.stats = {
executionCount: 0,
totalExecutionTime: 0,
averageExecutionTime: 0,
memoryUsage: 0,
cacheHits: 0,
cacheMisses: 0,
errorCount: 0,
lastExecuted: new Date(),
securityEvents: 0,
};
this.smartCache = new smartCache.SmartCache(cacheConfig);
this.analyticsEngine = new analyticsEngine.AnalyticsEngine();
}
/**
* Update execution statistics
*/
updateStats(context, success) {
const executionTime = performance.now() - context.startTime;
this.stats.executionCount++;
this.stats.totalExecutionTime += executionTime;
this.stats.averageExecutionTime =
this.stats.totalExecutionTime / this.stats.executionCount;
this.stats.lastExecuted = new Date();
this.stats.memoryUsage = this.getCurrentMemoryUsage();
if (!success) {
this.stats.errorCount++;
}
// Update audit entry
context.auditEntry.executionTime = executionTime;
context.auditEntry.success = success;
context.auditEntry.memoryUsage = this.stats.memoryUsage;
}
/**
* Add entry to audit log
*/
addAuditEntry(entry) {
this.auditLog.push(entry);
// Limit audit log size
if (this.auditLog.length > 1000) {
this.auditLog.splice(0, 100);
}
}
/**
* Increment security events counter
*/
incrementSecurityEvents() {
this.stats.securityEvents++;
}
/**
* Record cache hit
*/
recordCacheHit() {
this.stats.cacheHits++;
}
/**
* Record cache miss
*/
recordCacheMiss() {
this.stats.cacheMisses++;
}
/**
* Get cached result with smart caching
*/
getCachedResult(key) {
return this.smartCache.get(key);
}
/**
* Cache result with smart management
*/
cacheResult(key, result, ttl) {
this.smartCache.set(key, result, ttl);
}
/**
* Clear cache
*/
clearCache() {
this.smartCache.clear();
}
/**
* Clean up old cache entries with smart cleanup
*/
cleanupOldCacheEntries(maxAge = 300000) {
// Smart cache handles this automatically, but we can trigger manual cleanup
const memoryStats = index.memoryManager.getStats();
if (memoryStats.pressure > 0.7) {
this.smartCache.handleMemoryPressure("medium");
}
else if (memoryStats.pressure > 0.5) {
this.smartCache.handleMemoryPressure("low");
}
this.lastCleanupTime = Date.now();
}
/**
* Get current statistics
*/
getStats() {
return { ...this.stats };
}
/**
* Get audit log
*/
getAuditLog() {
return [...this.auditLog];
}
/**
* Clear audit log
*/
clearAuditLog() {
this.auditLog.length = 0;
}
/**
* Get current memory usage
*/
getCurrentMemoryUsage() {
return process.memoryUsage?.()?.heapUsed || 0;
}
/**
* Get enhanced cache statistics
*/
getCacheStats() {
const smartCacheStats = this.smartCache.getStats();
return {
...smartCacheStats,
totalHits: this.stats.cacheHits,
totalMisses: this.stats.cacheMisses,
};
}
/**
* Update performance metrics with analytics
*/
updatePerformanceMetrics(metrics) {
this.performanceHistory.push(metrics);
// Limit history size
if (this.performanceHistory.length > 100) {
this.performanceHistory.splice(0, this.performanceHistory.length - 100);
}
// Update analytics
this.analyticsEngine.updatePerformanceMetrics(metrics);
// Adapt cache strategy based on performance
this.smartCache.adaptStrategy(metrics);
}
/**
* Get analytics data
*/
getAnalyticsData() {
return this.analyticsEngine.getAnalyticsData();
}
/**
* Get optimization suggestions
*/
getOptimizationSuggestions() {
return this.analyticsEngine.generateOptimizationSuggestions();
}
/**
* Warm cache with predicted entries
*/
warmCache() {
const patterns = this.analyticsEngine.getExecutionPatterns();
const predictions = this.analyticsEngine.predictNextExecutions();
// Warm cache with high-value patterns
const warmingData = patterns
.slice(0, 10) // Top 10 patterns
.map((pattern) => ({
key: pattern.parametersHash,
value: null, // Would need actual cached values
priority: pattern.cacheWorthiness,
}));
this.smartCache.warmCache(warmingData);
// Map predictions to the correct format
const mappedPredictions = predictions.map((p) => ({
key: p.parametersHash,
probability: p.probability,
}));
this.smartCache.preloadPredictedEntries(mappedPredictions);
}
/**
* Handle memory pressure intelligently
*/
handleMemoryPressure(level) {
this.smartCache.handleMemoryPressure(level);
if (level === "high") {
// Aggressive cleanup
this.auditLog.splice(0, Math.floor(this.auditLog.length * 0.5));
this.performanceHistory.splice(0, Math.floor(this.performanceHistory.length * 0.5));
}
else if (level === "medium") {
// Moderate cleanup
this.auditLog.splice(0, Math.floor(this.auditLog.length * 0.25));
}
}
/**
* Get performance trends
*/
getPerformanceTrends() {
return [...this.performanceHistory];
}
/**
* Detect anomalies in current execution
*/
detectAnomalies(auditEntry) {
this.analyticsEngine.analyzeExecution(auditEntry);
return this.analyticsEngine.getAnalyticsData().anomalies;
}
/**
* Destroy and cleanup resources
*/
destroy() {
this.smartCache.destroy();
this.analyticsEngine.clearAnalytics();
this.auditLog.length = 0;
this.performanceHistory.length = 0;
}
}
exports.PerformanceMonitor = PerformanceMonitor;
//# sourceMappingURL=performance-monitor.js.map