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.
108 lines (104 loc) • 2.98 kB
JavaScript
'use strict';
var events = require('events');
var utils = require('../../utils/utils.js');
/**
* Cache Manager for Fortified Function Core
* Handles memoization and cache lifecycle management
*/
class CacheManager extends events.EventEmitter {
constructor(options, securityManager) {
super();
this.memoCache = new Map();
this.options = options;
this.securityManager = securityManager;
if (this.options.autoCleanup) {
this.setupAutoCleanup();
}
}
/**
* Check if result is cached and return it
*/
async getCachedResult(args, executionId) {
if (!this.options.memoize) {
return null;
}
const cacheKey = await this.securityManager.generateCacheKey(args);
const cached = this.memoCache.get(cacheKey);
if (cached) {
this.emit("cache_hit", { executionId, cacheKey });
return cached.result;
}
this.emit("cache_miss", { executionId, cacheKey });
return null;
}
/**
* Cache execution result
*/
async cacheResult(args, result, executionId) {
if (!this.options.memoize) {
return;
}
const cacheKey = await this.securityManager.generateCacheKey(args);
this.memoCache.set(cacheKey, {
result,
timestamp: Date.now(),
});
this.emit("result_cached", { executionId, cacheKey });
}
/**
* Clear all cached results
*/
clearCache() {
this.memoCache.clear();
this.emit("cache_cleared");
}
/**
* Get cache statistics
*/
getCacheStats() {
const entries = Array.from(this.memoCache.entries()).map(([key, entry]) => ({
key,
timestamp: entry.timestamp,
}));
return {
size: this.memoCache.size,
entries,
};
}
/**
* Remove expired cache entries
*/
cleanupExpiredEntries(maxAge = 300000) {
let removedCount = 0;
for (const [key, entry] of this.memoCache.entries()) {
if (utils.FortifiedUtils.isCacheEntryExpired(entry.timestamp, maxAge)) {
this.memoCache.delete(key);
removedCount++;
}
}
if (removedCount > 0) {
this.emit("cache_cleanup", { removedCount });
}
return removedCount;
}
/**
* Set up automatic cleanup of old cache entries
*/
setupAutoCleanup() {
this.cleanupInterval = setInterval(() => {
this.cleanupExpiredEntries(300000); // 5 minutes
}, 60000); // Check every minute
}
/**
* Clean up resources
*/
destroy() {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
}
this.clearCache();
this.removeAllListeners();
}
}
exports.CacheManager = CacheManager;
//# sourceMappingURL=cache-manager.js.map