Skip to content

Commit 563442f

Browse files
fix(test): isolate cache db per vitest worker
Co-authored-by: me <me@kentcdodds.com>
1 parent 461793d commit 563442f

1 file changed

Lines changed: 30 additions & 4 deletions

File tree

app/utils/cache.server.ts

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import fs from 'node:fs'
2+
import os from 'node:os'
23
import path from 'node:path'
4+
import { threadId } from 'node:worker_threads'
35
import { DatabaseSync } from 'node:sqlite'
46
import {
57
cachified as baseCachified,
@@ -20,14 +22,27 @@ import { getInstanceInfo, getInstanceInfoSync } from './litefs.server.ts'
2022
import { cachifiedTimingReporter, type Timings } from './timing.server.ts'
2123

2224
const CACHE_DATABASE_PATH = process.env.CACHE_DATABASE_PATH
25+
const IS_TEST = process.env.NODE_ENV === 'test' || process.env.CI === 'true'
26+
const TEST_WORKER_ID = process.env.VITEST_WORKER_ID ?? String(threadId)
27+
const CACHE_DATABASE_PATH_FOR_TESTS = IS_TEST
28+
? path.join(
29+
os.tmpdir(),
30+
`epic-stack-cache-${process.pid}-${TEST_WORKER_ID}.db`,
31+
)
32+
: CACHE_DATABASE_PATH
2333

2434
const cacheDb = remember('cacheDb', createDatabase)
2535

2636
function createDatabase(tryAgain = true): DatabaseSync {
27-
const parentDir = path.dirname(CACHE_DATABASE_PATH)
37+
const databasePath = CACHE_DATABASE_PATH_FOR_TESTS
38+
if (!databasePath) {
39+
throw new Error('CACHE_DATABASE_PATH is not set')
40+
}
41+
42+
const parentDir = path.dirname(databasePath)
2843
fs.mkdirSync(parentDir, { recursive: true })
2944

30-
const db = new DatabaseSync(CACHE_DATABASE_PATH)
45+
const db = new DatabaseSync(databasePath)
3146
const { currentIsPrimary } = getInstanceInfoSync()
3247
if (!currentIsPrimary) return db
3348

@@ -41,10 +56,21 @@ function createDatabase(tryAgain = true): DatabaseSync {
4156
)
4257
`)
4358
} catch (error: unknown) {
44-
fs.unlinkSync(CACHE_DATABASE_PATH)
59+
try {
60+
fs.unlinkSync(databasePath)
61+
} catch (unlinkError) {
62+
if (
63+
typeof unlinkError !== 'object' ||
64+
unlinkError === null ||
65+
!('code' in unlinkError) ||
66+
unlinkError.code !== 'ENOENT'
67+
) {
68+
throw unlinkError
69+
}
70+
}
4571
if (tryAgain) {
4672
console.error(
47-
`Error creating cache database, deleting the file at "${CACHE_DATABASE_PATH}" and trying again...`,
73+
`Error creating cache database, deleting the file at "${databasePath}" and trying again...`,
4874
)
4975
return createDatabase(false)
5076
}

0 commit comments

Comments
 (0)