File size: 9,975 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * 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;