Optimize cache verification

b625319f0cca5f25da1550362e57d8185d635df2

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +25 -11Ignore whitespace
src/endpoints/characters.js+25 -11
@@ -43,7 +43,7 @@ class DiskCache {
4343 static DIRECTORY = 'characters';
4444
4545 /** @type {number} */
4646 static REMOVAL_INTERVAL = 6000060 * 1000;
4747
4848 /** @type {import('node-persist').LocalStorage} */
4949 #instance;
@@ -58,6 +58,22 @@ class DiskCache {
5858 removalQueue = [];
5959
6060 /**
61+ * Path to the cache directory.
62+ * @returns {string}
63+ */
64+ get cachePath() {
65+ return path.join(globalThis.DATA_ROOT, '_cache', DiskCache.DIRECTORY);
66+ }
67+
68+ /**
69+ * Returns the list of hashed keys in the cache.
70+ * @returns {string[]}
71+ */
72+ get hashedKeys() {
73+ return fs.readdirSync(this.cachePath);
74+ }
75+
76+ /**
6177 * Processes the removal queue.
6278 * @returns {Promise<void>}
6379 */
@@ -110,8 +126,7 @@ class DiskCache {
110126 return this.#instance;
111127 }
112128
113- const cacheDir = path.join(globalThis.DATA_ROOT, '_cache', DiskCache.DIRECTORY);
129+ this.#instance = storage.create({ dir: this.cachePath, ttl: false });
114- this.#instance = storage.create({ dir: cacheDir, ttl: false });
115130 await this.#instance.init();
116131 this.#removalInterval = setInterval(this.#removeCacheEntries.bind(this), DiskCache.REMOVAL_INTERVAL);
117132 return this.#instance;
@@ -128,18 +143,17 @@ class DiskCache {
128143 }
129144
130145 const cache = await this.instance();
131146 const validKeys = []new Set();
132147 for (const dir of directoriesList) {
133148 const files = fs.readdirSync(dir.characters, { withFileTypes: true });
134- for (const file of files) {
149+ for (const file of files.filter(f => f.isFile() && path.extname(f.name) === '.png')) {
135150 const filePath = path.join(dir.characters, file.name);
136151 const stat = fs.statSync(filePath);
137152 validKeys.pushadd(path.parse(cache.getDatumPath(`${filePath}-${stat.mtimeMs}`)).base);
138153 }
139154 }
140- const cacheKeys = await cache.keys();
155+ for (const key of this.hashedKeys) {
141- for (const key of cacheKeys) {
156+ if (!validKeys.has(key)) {
142- if (!validKeys.includes(key)) {
143157 await cache.removeItem(key);
144158 }
145159 }