Skip to content

Commit 67e059b

Browse files
authored
fix(file): delete cache file if corrupted (#97)
1 parent dbd214e commit 67e059b

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

.changeset/kind-needles-sing.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'bentocache': patch
3+
---
4+
5+
Delete cache file if corrupted. See #93

packages/bentocache/src/drivers/file/cleaner.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,16 @@ async function deleteFileIfExpired({ filePath, onError }) {
1919

2020
if (expiry < Date.now()) await unlink(filePath)
2121
} catch (error) {
22+
/**
23+
* If the file is empty or contains invalid JSON, we should delete it
24+
* as its a corrupted cache file that wont be readable anyway
25+
*/
26+
if (error instanceof SyntaxError) {
27+
if (onError) onError({ filePath, error })
28+
await unlink(filePath).catch(() => {})
29+
return
30+
}
31+
2232
if (onError) onError({ filePath, error })
2333
}
2434
}

packages/bentocache/tests/drivers/file.spec.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ test.group('File Driver | Prune', () => {
4141
assert.isTrue(await fs.exists('foo4'))
4242
})
4343

44-
test('continue if invalid file is inside the cache directory', async ({
44+
test('delete corrupted cache files (invalid JSON) during prune', async ({
4545
assert,
4646
fs,
4747
cleanup,
@@ -59,11 +59,28 @@ test.group('File Driver | Prune', () => {
5959

6060
await sleep(1000)
6161

62-
assert.isTrue(await fs.exists('foo'))
62+
assert.isFalse(await fs.exists('foo'))
6363
assert.isFalse(await fs.exists('foo2'))
6464
assert.isFalse(await fs.exists('foo3/1'))
6565
})
6666

67+
test('delete empty cache files during prune', async ({ assert, fs, cleanup }) => {
68+
const driver = new FileDriver({
69+
pruneInterval: 500,
70+
directory: fileURLToPath(BASE_URL),
71+
})
72+
73+
cleanup(() => driver.disconnect())
74+
75+
await fs.create('emptyFile', '')
76+
await driver.set('validKey', 'bar', 300)
77+
78+
await sleep(1000)
79+
80+
assert.isFalse(await fs.exists('emptyFile'))
81+
assert.isFalse(await fs.exists('validKey'))
82+
})
83+
6784
test('use configured logger', async ({ assert, fs, cleanup }) => {
6885
const logger = testLogger()
6986
const driver = new FileDriver({

0 commit comments

Comments
 (0)