File size: 8,713 Bytes
69b897d |
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 |
/**
* ็ผๅญ็ๆงๅ็ฎก็ๅทฅๅ
ท
* ๆไพ็ปไธ็็ผๅญ็ๆงใ็ป่ฎกๅๅฎๅ
จๆธ
็ๅ่ฝ
*/
const logger = require('./logger')
const crypto = require('crypto')
class CacheMonitor {
constructor() {
this.monitors = new Map() // ๅญๅจๆๆ่ขซ็ๆง็็ผๅญๅฎไพ
this.startTime = Date.now()
this.totalHits = 0
this.totalMisses = 0
this.totalEvictions = 0
// ๐ ๅฎๅ
จ้
็ฝฎ
this.securityConfig = {
maxCacheAge: 15 * 60 * 1000, // ๆๅคง็ผๅญๅนด้พ 15 ๅ้
forceCleanupInterval: 30 * 60 * 1000, // ๅผบๅถๆธ
็้ด้ 30 ๅ้
memoryThreshold: 100 * 1024 * 1024, // ๅ
ๅญ้ๅผ 100MB
sensitiveDataPatterns: [/password/i, /token/i, /secret/i, /key/i, /credential/i]
}
// ๐งน ๅฎๆๆง่กๅฎๅ
จๆธ
็
this.setupSecurityCleanup()
// ๐ ๅฎๆๆฅๅ็ป่ฎกไฟกๆฏ
this.setupPeriodicReporting()
}
/**
* ๆณจๅ็ผๅญๅฎไพ่ฟ่ก็ๆง
* @param {string} name - ็ผๅญๅ็งฐ
* @param {LRUCache} cache - ็ผๅญๅฎไพ
*/
registerCache(name, cache) {
if (this.monitors.has(name)) {
logger.warn(`โ ๏ธ Cache ${name} is already registered, updating reference`)
}
this.monitors.set(name, {
cache,
registeredAt: Date.now(),
lastCleanup: Date.now(),
totalCleanups: 0
})
logger.info(`๐ฆ Registered cache for monitoring: ${name}`)
}
/**
* ่ทๅๆๆ็ผๅญ็็ปผๅ็ป่ฎก
*/
getGlobalStats() {
const stats = {
uptime: Math.floor((Date.now() - this.startTime) / 1000), // ็ง
cacheCount: this.monitors.size,
totalSize: 0,
totalHits: 0,
totalMisses: 0,
totalEvictions: 0,
averageHitRate: 0,
caches: {}
}
for (const [name, monitor] of this.monitors) {
const cacheStats = monitor.cache.getStats()
stats.totalSize += cacheStats.size
stats.totalHits += cacheStats.hits
stats.totalMisses += cacheStats.misses
stats.totalEvictions += cacheStats.evictions
stats.caches[name] = {
...cacheStats,
lastCleanup: new Date(monitor.lastCleanup).toISOString(),
totalCleanups: monitor.totalCleanups,
age: Math.floor((Date.now() - monitor.registeredAt) / 1000) // ็ง
}
}
const totalRequests = stats.totalHits + stats.totalMisses
stats.averageHitRate =
totalRequests > 0 ? `${((stats.totalHits / totalRequests) * 100).toFixed(2)}%` : '0%'
return stats
}
/**
* ๐ ๆง่กๅฎๅ
จๆธ
็
* ๆธ
็่ฟๆๆฐๆฎๅๆฝๅจ็ๆๆไฟกๆฏ
*/
performSecurityCleanup() {
logger.info('๐ Starting security cleanup for all caches')
for (const [name, monitor] of this.monitors) {
try {
const { cache } = monitor
const beforeSize = cache.cache.size
// ๆง่กๅธธ่งๆธ
็
cache.cleanup()
// ๆฃๆฅ็ผๅญๅนด้พ๏ผๅฆๆๅคช่ๅๅฎๅ
จๆธ
็ฉบ
const cacheAge = Date.now() - monitor.registeredAt
if (cacheAge > this.securityConfig.maxCacheAge * 2) {
logger.warn(
`โ ๏ธ Cache ${name} is too old (${Math.floor(cacheAge / 60000)}min), performing full clear`
)
cache.clear()
}
monitor.lastCleanup = Date.now()
monitor.totalCleanups++
const afterSize = cache.cache.size
if (beforeSize !== afterSize) {
logger.info(`๐งน Cache ${name}: Cleaned ${beforeSize - afterSize} items`)
}
} catch (error) {
logger.error(`โ Error cleaning cache ${name}:`, error)
}
}
}
/**
* ๐ ็ๆ่ฏฆ็ปๆฅๅ
*/
generateReport() {
const stats = this.getGlobalStats()
logger.info('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ')
logger.info('๐ Cache System Performance Report')
logger.info('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ')
logger.info(`โฑ๏ธ Uptime: ${this.formatUptime(stats.uptime)}`)
logger.info(`๐ฆ Active Caches: ${stats.cacheCount}`)
logger.info(`๐ Total Cache Size: ${stats.totalSize} items`)
logger.info(`๐ฏ Global Hit Rate: ${stats.averageHitRate}`)
logger.info(`โ
Total Hits: ${stats.totalHits.toLocaleString()}`)
logger.info(`โ Total Misses: ${stats.totalMisses.toLocaleString()}`)
logger.info(`๐๏ธ Total Evictions: ${stats.totalEvictions.toLocaleString()}`)
logger.info('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ')
// ่ฏฆ็ป็ๆฏไธช็ผๅญ็ป่ฎก
for (const [name, cacheStats] of Object.entries(stats.caches)) {
logger.info(`\n๐ฆ ${name}:`)
logger.info(
` Size: ${cacheStats.size}/${cacheStats.maxSize} | Hit Rate: ${cacheStats.hitRate}`
)
logger.info(
` Hits: ${cacheStats.hits} | Misses: ${cacheStats.misses} | Evictions: ${cacheStats.evictions}`
)
logger.info(
` Age: ${this.formatUptime(cacheStats.age)} | Cleanups: ${cacheStats.totalCleanups}`
)
}
logger.info('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ')
}
/**
* ๐งน ่ฎพ็ฝฎๅฎๆๅฎๅ
จๆธ
็
*/
setupSecurityCleanup() {
// ๆฏ 10 ๅ้ๆง่กไธๆฌกๅฎๅ
จๆธ
็
setInterval(
() => {
this.performSecurityCleanup()
},
10 * 60 * 1000
)
// ๆฏ 30 ๅ้ๅผบๅถๅฎๆดๆธ
็
setInterval(() => {
logger.warn('โ ๏ธ Performing forced complete cleanup for security')
for (const [name, monitor] of this.monitors) {
monitor.cache.clear()
logger.info(`๐๏ธ Force cleared cache: ${name}`)
}
}, this.securityConfig.forceCleanupInterval)
}
/**
* ๐ ่ฎพ็ฝฎๅฎๆๆฅๅ
*/
setupPeriodicReporting() {
// ๆฏ 5 ๅ้็ๆไธๆฌก็ฎๅ็ป่ฎก
setInterval(
() => {
const stats = this.getGlobalStats()
logger.info(
`๐ Quick Stats - Caches: ${stats.cacheCount}, Size: ${stats.totalSize}, Hit Rate: ${stats.averageHitRate}`
)
},
5 * 60 * 1000
)
// ๆฏ 30 ๅ้็ๆไธๆฌก่ฏฆ็ปๆฅๅ
setInterval(
() => {
this.generateReport()
},
30 * 60 * 1000
)
}
/**
* ๆ ผๅผๅ่ฟ่กๆถ้ด
*/
formatUptime(seconds) {
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const secs = seconds % 60
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`
} else if (minutes > 0) {
return `${minutes}m ${secs}s`
} else {
return `${secs}s`
}
}
/**
* ๐ ็ๆๅฎๅ
จ็็ผๅญ้ฎ
* ไฝฟ็จ SHA-256 ๅๅธ้ฟๅ
ๆด้ฒๅๅงๆฐๆฎ
*/
static generateSecureCacheKey(data) {
return crypto.createHash('sha256').update(data).digest('hex')
}
/**
* ๐ก๏ธ ้ช่ฏ็ผๅญๆฐๆฎๅฎๅ
จๆง
* ๆฃๆฅๆฏๅฆๅ
ๅซๆๆไฟกๆฏ
*/
validateCacheSecurity(data) {
const dataStr = typeof data === 'string' ? data : JSON.stringify(data)
for (const pattern of this.securityConfig.sensitiveDataPatterns) {
if (pattern.test(dataStr)) {
logger.warn('โ ๏ธ Potential sensitive data detected in cache')
return false
}
}
return true
}
/**
* ๐พ ่ทๅๅ
ๅญไฝฟ็จไผฐ็ฎ
*/
estimateMemoryUsage() {
let totalBytes = 0
for (const [, monitor] of this.monitors) {
const { cache } = monitor.cache
for (const [key, item] of cache) {
// ็ฒ็ฅไผฐ็ฎ๏ผkey ้ฟๅบฆ + value ๅบๅๅ้ฟๅบฆ
totalBytes += key.length * 2 // UTF-16
totalBytes += JSON.stringify(item).length * 2
}
}
return {
bytes: totalBytes,
mb: (totalBytes / (1024 * 1024)).toFixed(2),
warning: totalBytes > this.securityConfig.memoryThreshold
}
}
/**
* ๐จ ็ดงๆฅๆธ
็
* ๅจๅ
ๅญๅๅๅคงๆถไฝฟ็จ
*/
emergencyCleanup() {
logger.error('๐จ EMERGENCY CLEANUP INITIATED')
for (const [name, monitor] of this.monitors) {
const { cache } = monitor
const beforeSize = cache.cache.size
// ๆธ
็ไธๅ็็ผๅญ้กน๏ผLRU ไผไฟ็ๆ่ฟไฝฟ็จ็๏ผ
const targetSize = Math.floor(cache.maxSize / 2)
while (cache.cache.size > targetSize) {
const firstKey = cache.cache.keys().next().value
cache.cache.delete(firstKey)
}
logger.warn(`๐จ Emergency cleaned ${name}: ${beforeSize} -> ${cache.cache.size} items`)
}
}
}
// ๅฏผๅบๅไพ
module.exports = new CacheMonitor()
|