Refactor DiskCache to use a synchronization queue and update cache key generation
| @@ -21,6 +21,7 @@ import { parse, write } from '../character-card-parser.js'; | ||
| 21 | 21 | import { readWorldInfoFile } from './worldinfo.js'; |
| 22 | 22 | import { invalidateThumbnail } from './thumbnails.js'; |
| 23 | 23 | import { importRisuSprites } from './sprites.js'; |
| 24 | +import { getUserDirectories } from '../users.js'; | |
| 24 | 25 | const defaultAvatarPath = './public/img/ai4.png'; |
| 25 | 26 | |
| 26 | 27 | // With 100 MB limit it would take roughly 3000 characters to reach this limit |
| @@ -34,28 +35,29 @@ const useDiskCache = !!getConfigValue('performance.useDiskCache', true, 'boolean | ||
| 34 | 35 | |
| 35 | 36 | class DiskCache { |
| 36 | 37 | /** |
| 37 | 38 | * @typedeftype {objectstring} CacheRemovalQueueItem |
| 38 | - * @property {string} item Path to the character file | |
| 39 | + * @readonly | |
| 39 | - * @property {number} timestamp Timestamp of the last access | |
| 40 | 40 | */ |
| 41 | - | |
| 42 | - /** @type {string} */ | |
| 43 | 41 | static DIRECTORY = 'characters'; |
| 44 | 42 | |
| 45 | - /** @type {number} */ | |
| 43 | + /** | |
| 46 | - static REMOVAL_INTERVAL = 5 * 60 * 1000; | |
| 44 | + * @type {number} | |
| 45 | + * @readonly | |
| 46 | + */ | |
| 47 | + static SYNC_INTERVAL = 5 * 60 * 1000; | |
| 47 | 48 | |
| 48 | 49 | /** @type {import('node-persist').LocalStorage} */ |
| 49 | 50 | #instance; |
| 50 | 51 | |
| 51 | 52 | /** @type {NodeJS.Timeout} */ |
| 52 | 53 | #removalIntervalsyncInterval; |
| 53 | 54 | |
| 54 | 55 | /** |
| 55 | 56 | * Queue forof removaluser ofhandles cacheto entriessync. |
| 56 | 57 | * @type {CacheRemovalQueueItem[]Set<string>} |
| 58 | + * @readonly | |
| 57 | 59 | */ |
| 58 | 60 | removalQueuesyncQueue = []new Set(); |
| 59 | 61 | |
| 60 | 62 | /** |
| 61 | 63 | * Path to the cache directory. |
| @@ -74,49 +76,21 @@ class DiskCache { | ||
| 74 | 76 | } |
| 75 | 77 | |
| 76 | 78 | /** |
| 77 | 79 | * Processes the removalsynchronization queue. |
| 78 | 80 | * @returns {Promise<void>} |
| 79 | 81 | */ |
| 80 | 82 | async #removeCacheEntriessyncCacheEntries() { |
| 81 | - // TODO: consider running this.verify() for a user instead as getting all cache keys | |
| 82 | - // is a heavy operation, since it requires to read all files in the disk cache. | |
| 83 | - | |
| 84 | 83 | try { |
| 85 | 84 | if (!useDiskCache || this.removalQueuesyncQueue.lengthsize === 0) { |
| 86 | 85 | return; |
| 87 | 86 | } |
| 88 | 87 | |
| 89 | - /** @type {Map<string, number>} */ | |
| 88 | + const directories = [...this.syncQueue].map(entry => getUserDirectories(entry)); | |
| 90 | - const latestTimestamps = new Map(); | |
| 89 | + this.syncQueue.clear(); | |
| 91 | - for (const { item, timestamp } of this.removalQueue) { | |
| 92 | - if (!latestTimestamps.has(item) || timestamp > (latestTimestamps.get(item) ?? 0)) { | |
| 93 | - latestTimestamps.set(item, timestamp); | |
| 94 | - } | |
| 95 | - } | |
| 96 | - this.removalQueue.length = 0; | |
| 97 | - | |
| 98 | - const cache = await this.instance(); | |
| 99 | - const keys = await cache.keys(); | |
| 100 | 90 | |
| 101 | - for (const [item, timestamp] of latestTimestamps.entries()) { | |
| 91 | + await this.verify(directories); | |
| 102 | - const itemKeys = keys.filter(k => k.startsWith(item)); | |
| 103 | - if (!itemKeys.length) { | |
| 104 | - continue; | |
| 105 | - } | |
| 106 | - for (const key of itemKeys) { | |
| 107 | - const datumPath = cache.getDatumPath(key); | |
| 108 | - if (!fs.existsSync(datumPath)) { | |
| 109 | - continue; | |
| 110 | - } | |
| 111 | - const stat = fs.statSync(datumPath); | |
| 112 | - if (stat.mtimeMs > timestamp) { | |
| 113 | - continue; | |
| 114 | - } | |
| 115 | - await cache.removeItem(key); | |
| 116 | - } | |
| 117 | - } | |
| 118 | 92 | } catch (error) { |
| 119 | 93 | console.error('Error while removingsynchronizing cache entries:', error); |
| 120 | 94 | } |
| 121 | 95 | } |
| 122 | 96 | |
| @@ -131,7 +105,7 @@ class DiskCache { | ||
| 131 | 105 | |
| 132 | 106 | this.#instance = storage.create({ dir: this.cachePath, ttl: false }); |
| 133 | 107 | await this.#instance.init(); |
| 134 | 108 | this.#removalIntervalsyncInterval = setInterval(this.#removeCacheEntriessyncCacheEntries.bind(this), DiskCache.REMOVAL_INTERVALSYNC_INTERVAL); |
| 135 | 109 | return this.#instance; |
| 136 | 110 | } |
| 137 | 111 | |
| @@ -151,8 +125,8 @@ class DiskCache { | ||
| 151 | 125 | const files = fs.readdirSync(dir.characters, { withFileTypes: true }); |
| 152 | 126 | for (const file of files.filter(f => f.isFile() && path.extname(f.name) === '.png')) { |
| 153 | 127 | const filePath = path.join(dir.characters, file.name); |
| 154 | 128 | const statcacheKey = fs.statSyncgetCacheKey(filePath); |
| 155 | 129 | validKeys.add(path.parse(cache.getDatumPath(`${filePath}-${stat.mtimeMs}`cacheKey)).base); |
| 156 | 130 | } |
| 157 | 131 | } |
| 158 | 132 | for (const key of this.hashedKeys) { |
| @@ -163,8 +137,8 @@ class DiskCache { | ||
| 163 | 137 | } |
| 164 | 138 | |
| 165 | 139 | dispose() { |
| 166 | 140 | if (this.#removalIntervalsyncInterval) { |
| 167 | 141 | clearInterval(this.#removalIntervalsyncInterval); |
| 168 | 142 | } |
| 169 | 143 | } |
| 170 | 144 | } |
| @@ -172,14 +146,27 @@ class DiskCache { | ||
| 172 | 146 | export const diskCache = new DiskCache(); |
| 173 | 147 | |
| 174 | 148 | /** |
| 149 | + * Gets the cache key for the specified image file. | |
| 150 | + * @param {string} inputFile - Path to the image file | |
| 151 | + * @returns {string} - Cache key | |
| 152 | + */ | |
| 153 | +function getCacheKey(inputFile) { | |
| 154 | + if (fs.existsSync(inputFile)) { | |
| 155 | + const stat = fs.statSync(inputFile); | |
| 156 | + return `${inputFile}-${stat.mtimeMs}`; | |
| 157 | + } | |
| 158 | + | |
| 159 | + return inputFile; | |
| 160 | +} | |
| 161 | + | |
| 162 | +/** | |
| 175 | 163 | * Reads the character card from the specified image file. |
| 176 | 164 | * @param {string} inputFile - Path to the image file |
| 177 | 165 | * @param {string} inputFormat - 'png' |
| 178 | 166 | * @returns {Promise<string | undefined>} - Character card data |
| 179 | 167 | */ |
| 180 | 168 | async function readCharacterData(inputFile, inputFormat = 'png') { |
| 181 | 169 | const statcacheKey = fs.statSyncgetCacheKey(inputFile); |
| 182 | - const cacheKey = `${inputFile}-${stat.mtimeMs}`; | |
| 183 | 170 | if (memoryCache.has(cacheKey)) { |
| 184 | 171 | return memoryCache.get(cacheKey); |
| 185 | 172 | } |
| @@ -220,7 +207,7 @@ async function writeCharacterData(inputFile, data, outputFile, request, crop = u | ||
| 220 | 207 | } |
| 221 | 208 | } |
| 222 | 209 | if (useDiskCache && !Buffer.isBuffer(inputFile)) { |
| 223 | - diskCache.removalQueue.push({ item: inputFile, timestamp: Date.now() }); | |
| 210 | + diskCache.syncQueue.add(request.user.profile.handle); | |
| 224 | 211 | } |
| 225 | 212 | /** |
| 226 | 213 | * Read the image, resize, and save it as a PNG into the buffer. |