aboutsummaryrefslogtreecommitdiff
path: root/src/services
diff options
context:
space:
mode:
authorMax Isom <[email protected]>2021-12-03 11:06:56 -0500
committerMax Isom <[email protected]>2021-12-03 11:06:56 -0500
commit7ff54b9495545cd23fa87ac13bd654a78c29aa1d (patch)
tree8f89003848d643f3f5e40035c84521b07d2cab57 /src/services
parent4ffd679ddb227ea6e6ac911de382e4d5bec0926d (diff)
downloadmuse-7ff54b9495545cd23fa87ac13bd654a78c29aa1d.tar.xz
muse-7ff54b9495545cd23fa87ac13bd654a78c29aa1d.zip
Use loop instead of recursion
Diffstat (limited to 'src/services')
-rw-r--r--src/services/file-cache.ts35
1 files changed, 27 insertions, 8 deletions
diff --git a/src/services/file-cache.ts b/src/services/file-cache.ts
index 7e7aa6d..ac8c815 100644
--- a/src/services/file-cache.ts
+++ b/src/services/file-cache.ts
@@ -94,13 +94,12 @@ export default class FileCacheProvider {
private async evictOldest() {
debug('Evicting oldest files...');
- const [{dataValues: {totalSizeBytes}}] = await FileCache.findAll({
- attributes: [
- [sequelize.fn('sum', sequelize.col('bytes')), 'totalSizeBytes'],
- ],
- }) as unknown as [{dataValues: {totalSizeBytes: number}}];
- if (totalSizeBytes > this.config.CACHE_LIMIT_IN_BYTES) {
+ let totalSizeBytes = await this.getDiskUsageInBytes();
+ let numOfEvictedFiles = 0;
+ // Continue to evict until we're under the limit
+ /* eslint-disable no-await-in-loop */
+ while (totalSizeBytes > this.config.CACHE_LIMIT_IN_BYTES) {
const oldest = await FileCache.findOne({
order: [
['accessedAt', 'ASC'],
@@ -111,10 +110,15 @@ export default class FileCacheProvider {
await oldest.destroy();
await fs.unlink(path.join(this.config.CACHE_DIR, oldest.hash));
debug(`${oldest.hash} has been evicted`);
+ numOfEvictedFiles++;
}
- // Continue to evict until we're under the limit
- void this.evictionQueue.add(this.evictOldest.bind(this));
+ totalSizeBytes = await this.getDiskUsageInBytes();
+ }
+ /* eslint-enable no-await-in-loop */
+
+ if (numOfEvictedFiles > 0) {
+ debug(`${numOfEvictedFiles} files have been evicted`);
} else {
debug(`No files needed to be evicted. Total size of the cache is currently ${totalSizeBytes} bytes, and the cache limit is ${this.config.CACHE_LIMIT_IN_BYTES} bytes.`);
}
@@ -131,4 +135,19 @@ export default class FileCacheProvider {
}
}
}
+
+ /**
+ * Pulls from the database rather than the filesystem,
+ * so may be slightly inaccurate.
+ * @returns the total size of the cache in bytes
+ */
+ private async getDiskUsageInBytes() {
+ const [{dataValues: {totalSizeBytes}}] = await FileCache.findAll({
+ attributes: [
+ [sequelize.fn('sum', sequelize.col('bytes')), 'totalSizeBytes'],
+ ],
+ }) as unknown as [{dataValues: {totalSizeBytes: number}}];
+
+ return totalSizeBytes;
+ }
}