Skip to content

Commit

Permalink
fix: move cache state to ctx.cache
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 9, 2022
1 parent f714833 commit 695a7a2
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 34 deletions.
2 changes: 2 additions & 0 deletions packages/ui/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { builtinModules } from 'module'
import esbuild from 'rollup-plugin-esbuild'
import dts from 'rollup-plugin-dts'
import resolve from '@rollup/plugin-node-resolve'
Expand All @@ -11,6 +12,7 @@ const entry = [
]

const external = [
...builtinModules,
...Object.keys(pkg.dependencies),
...Object.keys(pkg.peerDependencies || {}),
'worker_threads',
Expand Down
2 changes: 2 additions & 0 deletions packages/vite-node/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { builtinModules } from 'module'
import esbuild from 'rollup-plugin-esbuild'
import dts from 'rollup-plugin-dts'
import resolve from '@rollup/plugin-node-resolve'
Expand All @@ -18,6 +19,7 @@ const entries = {
}

const external = [
...builtinModules,
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
'pathe',
Expand Down
2 changes: 2 additions & 0 deletions packages/vitest/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from 'fs'
import { builtinModules } from 'module'
import { dirname, join, relative, resolve } from 'pathe'
import esbuild from 'rollup-plugin-esbuild'
import dts from 'rollup-plugin-dts'
Expand Down Expand Up @@ -29,6 +30,7 @@ const dtsEntries = [
]

const external = [
...builtinModules,
...Object.keys(pkg.dependencies),
...Object.keys(pkg.peerDependencies),
'worker_threads',
Expand Down
1 change: 0 additions & 1 deletion packages/vitest/src/node/cache/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export class FilesStatsCache {
public async updateStats(fsPath: string) {
if (!fs.existsSync(fsPath))
return

const stats = await fs.promises.stat(fsPath)
this.cache.set(fsPath, { size: stats.size })
}
Expand Down
13 changes: 13 additions & 0 deletions packages/vitest/src/node/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,21 @@ import { loadConfigFromFile } from 'vite'
import { configFiles } from '../../constants'
import type { CliOptions } from '../cli-api'
import { slash } from '../../utils'
import { FilesStatsCache } from './files'
import { ResultsCache } from './results'

export class VitestCache {
results = new ResultsCache()
stats = new FilesStatsCache()

getFileTestResults(id: string) {
return this.results.getResults(id)
}

getFileStats(id: string) {
return this.stats.getStats(id)
}

static resolveCacheDir(root: string, dir: string | undefined) {
return resolve(root, slash(dir || 'node_modules/.vitest'))
}
Expand Down
21 changes: 12 additions & 9 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { StateManager } from './state'
import { resolveConfig } from './config'
import { printError } from './error'
import { VitestGit } from './git'
import { VitestCache } from './cache'

const WATCHER_DEBOUNCE = 100
const CLOSE_TIMEOUT = 1_000
Expand All @@ -29,6 +30,7 @@ export class Vitest {
server: ViteDevServer = undefined!
state: StateManager = undefined!
snapshot: SnapshotManager = undefined!
cache: VitestCache = undefined!
reporters: Reporter[] = undefined!
console: Console
pool: WorkerPool | undefined
Expand Down Expand Up @@ -65,6 +67,7 @@ export class Vitest {
this.server = server
this.config = resolved
this.state = new StateManager()
this.cache = new VitestCache()
this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions })

if (this.config.watch)
Expand Down Expand Up @@ -92,12 +95,12 @@ export class Vitest {
if (resolved.coverage.enabled)
await cleanCoverage(resolved.coverage, resolved.coverage.clean)

this.state.results.setConfig(resolved.root, resolved.cache)
this.cache.results.setConfig(resolved.root, resolved.cache)
try {
await this.state.results.readFromCache()
await this.cache.results.readFromCache()
}
catch (err) {
this.error(`[vitest] Error, while trying to parse cache in ${this.state.results.getCachePath()}:`, err)
this.error(`[vitest] Error, while trying to parse cache in ${this.cache.results.getCachePath()}:`, err)
}
}

Expand Down Expand Up @@ -148,7 +151,7 @@ export class Vitest {
}

// populate once, update cache on watch
await Promise.all(files.map(file => this.state.stats.updateStats(file)))
await Promise.all(files.map(file => this.cache.stats.updateStats(file)))

await this.runFiles(files)

Expand Down Expand Up @@ -253,8 +256,8 @@ export class Vitest {

await this.report('onFinished', files, this.state.getUnhandledErrors())

this.state.results.updateResults(files)
await this.state.results.writeToCache()
this.cache.results.updateResults(files)
await this.cache.results.writeToCache()
})()
.finally(() => {
this.runningPromise = undefined
Expand Down Expand Up @@ -380,8 +383,8 @@ export class Vitest {

if (this.state.filesMap.has(id)) {
this.state.filesMap.delete(id)
this.state.results.removeFromCache(id)
this.state.stats.removeStats(id)
this.cache.results.removeFromCache(id)
this.cache.stats.removeStats(id)
this.changedTests.delete(id)
this.report('onTestRemoved', id)
}
Expand All @@ -390,7 +393,7 @@ export class Vitest {
id = slash(id)
if (await this.isTargetFile(id)) {
this.changedTests.add(id)
await this.state.stats.updateStats(id)
await this.cache.stats.updateStats(id)
this.scheduleRerun(id)
}
}
Expand Down
10 changes: 5 additions & 5 deletions packages/vitest/src/node/sequencers/BaseSequencer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ export class BaseSequencer implements TestSequencer {

// async so it can be extended by other sequelizers
public async sort(files: string[]): Promise<string[]> {
const { state } = this.ctx
const cache = this.ctx.cache
return [...files].sort((a, b) => {
const aState = state.getFileTestResults(a)
const bState = state.getFileTestResults(b)
const aState = cache.getFileTestResults(a)
const bState = cache.getFileTestResults(b)

if (!aState || !bState) {
const statsA = state.getFileStats(a)
const statsB = state.getFileStats(b)
const statsA = cache.getFileStats(a)
const statsB = cache.getFileStats(b)

// run unknown first
if (!statsA || !statsB)
Expand Down
13 changes: 1 addition & 12 deletions packages/vitest/src/node/state.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
import type { ErrorWithDiff, File, Task, TaskResultPack, UserConsoleLog } from '../types'
import { FilesStatsCache } from './cache/files'
import { ResultsCache } from './cache/results'

// Note this file is shared for both node and browser, be aware to avoid node specific logic
export class StateManager {
filesMap = new Map<string, File>()
idMap = new Map<string, Task>()
taskFileMap = new WeakMap<Task, File>()
errorsSet = new Set<unknown>()
results = new ResultsCache()
stats = new FilesStatsCache()

getFileTestResults(id: string) {
return this.results.getResults(id)
}

getFileStats(id: string) {
return this.stats.getStats(id)
}

catchError(err: unknown, type: string) {
(err as ErrorWithDiff).type = type
Expand Down
14 changes: 7 additions & 7 deletions test/core/test/sequencers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const buildCtx = () => {
config: {
sequence: {},
},
state: {
cache: {
getFileTestResults: vi.fn(),
getFileStats: vi.fn(),
},
Expand All @@ -23,9 +23,9 @@ describe('base sequencer', () => {
expect(sorted).toStrictEqual(files)
})

test('prioritaze unknown files', async () => {
test('prioritize unknown files', async () => {
const ctx = buildCtx()
vi.spyOn(ctx.state, 'getFileStats').mockImplementation((file) => {
vi.spyOn(ctx.cache, 'getFileStats').mockImplementation((file) => {
if (file === 'b')
return { size: 2 }
})
Expand All @@ -37,7 +37,7 @@ describe('base sequencer', () => {

test('sort by size, larger first', async () => {
const ctx = buildCtx()
vi.spyOn(ctx.state, 'getFileStats').mockImplementation((file) => {
vi.spyOn(ctx.cache, 'getFileStats').mockImplementation((file) => {
if (file === 'a')
return { size: 1 }
if (file === 'b')
Expand All @@ -53,7 +53,7 @@ describe('base sequencer', () => {

test('sort by results, failed first', async () => {
const ctx = buildCtx()
vi.spyOn(ctx.state, 'getFileTestResults').mockImplementation((file) => {
vi.spyOn(ctx.cache, 'getFileTestResults').mockImplementation((file) => {
if (file === 'a')
return { failed: false, duration: 1 }
if (file === 'b')
Expand All @@ -69,7 +69,7 @@ describe('base sequencer', () => {

test('sort by results, long first', async () => {
const ctx = buildCtx()
vi.spyOn(ctx.state, 'getFileTestResults').mockImplementation((file) => {
vi.spyOn(ctx.cache, 'getFileTestResults').mockImplementation((file) => {
if (file === 'a')
return { failed: true, duration: 1 }
if (file === 'b')
Expand All @@ -85,7 +85,7 @@ describe('base sequencer', () => {

test('sort by results, long and failed first', async () => {
const ctx = buildCtx()
vi.spyOn(ctx.state, 'getFileTestResults').mockImplementation((file) => {
vi.spyOn(ctx.cache, 'getFileTestResults').mockImplementation((file) => {
if (file === 'a')
return { failed: false, duration: 1 }
if (file === 'b')
Expand Down

0 comments on commit 695a7a2

Please sign in to comment.