chahuadev-framework-en / modules /cache-manager.js
chahuadev
Update README
857cdcf
/**
* Cache Manager - ระบบจัดการ Cache
* Chahua Development Thailand
* CEO: Saharath C.
*
* Purpose: จัดการการ cache ข้อมูลเพื่อประสิทธิภาพ
*/
const fs = require('fs');
const path = require('path');
class CacheManager {
constructor(options = {}) {
this.config = {
defaultTTL: options.defaultTTL || 300, // 5 minutes
maxSize: options.maxSize || 1000, // Max 1000 items
persistPath: options.persistPath || './logs/cache',
enablePersistence: options.enablePersistence || false,
cleanupInterval: options.cleanupInterval || 60000, // 1 minute
compressionEnabled: options.compressionEnabled || false
};
this.cache = new Map();
this.accessTimes = new Map();
this.stats = {
hits: 0,
misses: 0,
sets: 0,
deletes: 0,
cleanups: 0
};
this.setupCleanupTimer();
if (this.config.enablePersistence) {
this.loadFromDisk();
}
console.log('Cache Manager initialized');
}
async set(key, value, options = {}) {
try {
const ttl = options.ttl || this.config.defaultTTL;
const expiry = Date.now() + (ttl * 1000);
const cacheItem = {
key,
value,
expiry,
size: this.calculateSize(value),
created: Date.now(),
accessed: Date.now(),
hits: 0
};
// Check if we need to make space
if (this.cache.size >= this.config.maxSize) {
this.evictLRU();
}
this.cache.set(key, cacheItem);
this.accessTimes.set(key, Date.now());
this.stats.sets++;
if (this.config.enablePersistence) {
await this.persistToDisk();
}
console.log(`Cache SET: ${key} (TTL: ${ttl}s)`);
return true;
} catch (error) {
console.error('Cache set error:', error.message);
return false;
}
}
async get(key) {
try {
const item = this.cache.get(key);
if (!item) {
this.stats.misses++;
console.log(`Cache MISS: ${key}`);
return null;
}
// Check if expired
if (Date.now() > item.expiry) {
this.cache.delete(key);
this.accessTimes.delete(key);
this.stats.misses++;
console.log(`Cache EXPIRED: ${key}`);
return null;
}
// Update access info
item.accessed = Date.now();
item.hits++;
this.accessTimes.set(key, Date.now());
this.stats.hits++;
console.log(`Cache HIT: ${key}`);
return item.value;
} catch (error) {
console.error('Cache get error:', error.message);
this.stats.misses++;
return null;
}
}
async delete(key) {
try {
const deleted = this.cache.delete(key);
this.accessTimes.delete(key);
if (deleted) {
this.stats.deletes++;
console.log(`Cache DELETE: ${key}`);
if (this.config.enablePersistence) {
await this.persistToDisk();
}
}
return deleted;
} catch (error) {
console.error('Cache delete error:', error.message);
return false;
}
}
async clear() {
try {
const size = this.cache.size;
this.cache.clear();
this.accessTimes.clear();
if (this.config.enablePersistence) {
await this.persistToDisk();
}
console.log(`Cache CLEARED: ${size} items removed`);
return true;
} catch (error) {
console.error('Cache clear error:', error.message);
return false;
}
}
has(key) {
const item = this.cache.get(key);
if (!item) return false;
// Check if expired
if (Date.now() > item.expiry) {
this.cache.delete(key);
this.accessTimes.delete(key);
return false;
}
return true;
}
keys() {
const validKeys = [];
const now = Date.now();
for (const [key, item] of this.cache.entries()) {
if (now <= item.expiry) {
validKeys.push(key);
}
}
return validKeys;
}
size() {
this.cleanup(); // Clean expired items first
return this.cache.size;
}
evictLRU() {
// Find least recently used item
let oldestKey = null;
let oldestTime = Date.now();
for (const [key, time] of this.accessTimes.entries()) {
if (time < oldestTime) {
oldestTime = time;
oldestKey = key;
}
}
if (oldestKey) {
this.cache.delete(oldestKey);
this.accessTimes.delete(oldestKey);
console.log(`Cache LRU EVICTED: ${oldestKey}`);
}
}
cleanup() {
const now = Date.now();
let cleanedCount = 0;
for (const [key, item] of this.cache.entries()) {
if (now > item.expiry) {
this.cache.delete(key);
this.accessTimes.delete(key);
cleanedCount++;
}
}
if (cleanedCount > 0) {
this.stats.cleanups++;
console.log(`Cache CLEANUP: ${cleanedCount} expired items removed`);
}
return cleanedCount;
}
setupCleanupTimer() {
this.cleanupTimer = setInterval(() => {
this.cleanup();
}, this.config.cleanupInterval);
}
stopCleanupTimer() {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = null;
}
}
calculateSize(value) {
try {
return JSON.stringify(value).length;
} catch (error) {
return 0;
}
}
async persistToDisk() {
try {
const cacheDir = path.dirname(this.config.persistPath);
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
const cacheData = {
timestamp: Date.now(),
cache: Array.from(this.cache.entries()),
accessTimes: Array.from(this.accessTimes.entries()),
stats: this.stats
};
fs.writeFileSync(this.config.persistPath, JSON.stringify(cacheData));
} catch (error) {
console.error('Cache persist error:', error.message);
}
}
loadFromDisk() {
try {
if (!fs.existsSync(this.config.persistPath)) {
return;
}
const data = JSON.parse(fs.readFileSync(this.config.persistPath, 'utf8'));
// Restore cache
this.cache = new Map(data.cache || []);
this.accessTimes = new Map(data.accessTimes || []);
this.stats = { ...this.stats, ...data.stats };
// Clean expired items
this.cleanup();
console.log('Cache loaded from disk');
} catch (error) {
console.error('Cache load error:', error.message);
}
}
getStats() {
const totalRequests = this.stats.hits + this.stats.misses;
const hitRate = totalRequests > 0 ? Math.round((this.stats.hits / totalRequests) * 100) : 0;
return {
size: this.cache.size,
hitRate: `${hitRate}%`,
totalHits: this.stats.hits,
totalMisses: this.stats.misses,
totalSets: this.stats.sets,
totalDeletes: this.stats.deletes,
totalCleanups: this.stats.cleanups,
totalRequests
};
}
getDetailedStats() {
const stats = this.getStats();
const items = [];
for (const [key, item] of this.cache.entries()) {
items.push({
key,
size: item.size,
hits: item.hits,
created: new Date(item.created).toISOString(),
accessed: new Date(item.accessed).toISOString(),
expiresIn: Math.max(0, Math.round((item.expiry - Date.now()) / 1000))
});
}
// Sort by most accessed
items.sort((a, b) => b.hits - a.hits);
return {
...stats,
items: items.slice(0, 10) // Top 10 most accessed
};
}
exportCache() {
const exportData = {
exportTime: new Date().toISOString(),
config: this.config,
stats: this.getStats(),
items: Array.from(this.cache.entries()).map(([key, item]) => ({
key,
value: item.value,
created: new Date(item.created).toISOString(),
accessed: new Date(item.accessed).toISOString(),
hits: item.hits,
size: item.size
}))
};
return exportData;
}
}
module.exports = CacheManager;