Skip to content

Commit 2026460

Browse files
authored
fix(vite): open inspect archives on first write (#655)
1 parent ade88a5 commit 2026460

6 files changed

Lines changed: 89 additions & 90 deletions

File tree

‎packages/vite/src/node/__tests__/inspect-context.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,19 @@ describe('vite inspect context', () => {
612612
expect(await envCtx.getModulesList()).toHaveLength(5)
613613
})
614614

615+
it('rejects flush when opening the archives fails with another batch queued', async () => {
616+
const error = new Error('Cannot open the inspect archives')
617+
const ctx = ViteInspectContext.create({
618+
filename: () => { throw error },
619+
maxBatchItems: 1,
620+
})
621+
for (const id of ['/a.ts', '/b.ts'])
622+
ctx.store.recordLoad('client', id, id, { name: 'plugin-a', start: 0, end: 1 })
623+
624+
await expect(ctx.store.flush()).rejects.toBe(error)
625+
await expect(ctx.close()).rejects.toBe(error)
626+
})
627+
615628
it('does not delay concurrent plugin hooks while writes are queued', async () => {
616629
const { ctx, env, envCtx, vite } = await createFixture({
617630
store: {

‎packages/vite/src/node/__tests__/inspect-plugin.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import type { Plugin, ResolvedConfig } from 'vite'
2+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
3+
import { tmpdir } from 'node:os'
4+
import { join } from 'node:path'
5+
import { resolveConfig } from 'vite'
26
import { describe, expect, it } from 'vitest'
37
import { createDevToolsContext } from '../../../../core/src/node/context'
48
import { DevToolsViteInspect } from '../inspect/plugin'
@@ -24,6 +28,26 @@ async function createContext(command: 'serve' | 'build') {
2428
}
2529

2630
describe('devToolsViteInspect', () => {
31+
it('leaves inspect archives untouched when only resolving Vite config', async ({ onTestFinished }) => {
32+
const cacheDir = mkdtempSync(join(tmpdir(), 'vite-inspect-config-'))
33+
onTestFinished(() => rmSync(cacheDir, { recursive: true, force: true }))
34+
const archives = join(cacheDir, 'devtools', 'inspect')
35+
const payloads = join(archives, 'payloads.bin')
36+
mkdirSync(archives, { recursive: true })
37+
writeFileSync(payloads, 'existing data')
38+
39+
await resolveConfig({
40+
root: cacheDir,
41+
cacheDir,
42+
configFile: false,
43+
devtools: false,
44+
plugins: [DevToolsViteInspect()],
45+
}, 'serve')
46+
47+
expect(readFileSync(payloads, 'utf8')).toBe('existing data')
48+
expect(existsSync(join(archives, 'plugin-calls.bin'))).toBe(false)
49+
})
50+
2751
it('registers inspect RPC in dev mode', async () => {
2852
const ctx = await createContext('serve')
2953

‎packages/vite/src/node/inspect/context.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ export class ViteInspectContext {
6060
readonly configToInstances = new Map<ResolvedConfig, ViteInspectViteContext>()
6161
readonly idToInstances = new Map<string, ViteInspectViteContext>()
6262

63-
static async create(options: ViteInspectStoreOptions = {}): Promise<ViteInspectContext> {
64-
return new ViteInspectContext(await createViteInspectStore(options))
63+
static create(options: ViteInspectStoreOptions = {}): ViteInspectContext {
64+
return new ViteInspectContext(createViteInspectStore(options))
6565
}
6666

6767
constructor(readonly store: ViteInspectStore) {}

‎packages/vite/src/node/inspect/plugin.ts‎

Lines changed: 14 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -21,65 +21,13 @@ import {
2121

2222
export function DevToolsViteInspect(): PluginWithDevTools {
2323
let inspectContext: ViteInspectContext | undefined
24-
let inspectContextPromise: Promise<ViteInspectContext> | undefined
25-
let closingInspectContext: Promise<void> | undefined
26-
let inspectStorageDir: string | undefined
2724
let inspectModuleUpdatedState: ViteInspectModuleUpdatedSharedState | undefined
2825

2926
function notifyInspectModuleUpdated(ids: string[] | null = null) {
3027
if (inspectModuleUpdatedState)
3128
notifyViteInspectModuleUpdated(inspectModuleUpdatedState, ids)
3229
}
3330

34-
async function createInspectContext(config: ResolvedConfig): Promise<ViteInspectContext> {
35-
const cacheDir = config.cacheDir || join(config.root, 'node_modules/.vite')
36-
const storageDir = join(cacheDir, 'devtools', 'inspect')
37-
inspectStorageDir = storageDir
38-
removeInspectStorage()
39-
40-
try {
41-
const ctx = await ViteInspectContext.create({
42-
filename: join(storageDir, 'payloads.bin'),
43-
})
44-
inspectContext = ctx
45-
return ctx
46-
}
47-
catch (error) {
48-
removeInspectStorage()
49-
throw error
50-
}
51-
}
52-
53-
function ensureInspectContext(config: ResolvedConfig): Promise<ViteInspectContext | undefined> {
54-
if (config.command !== 'serve')
55-
return Promise.resolve(undefined)
56-
57-
inspectContextPromise ??= createInspectContext(config)
58-
return inspectContextPromise
59-
}
60-
61-
async function closeInspectContext(): Promise<void> {
62-
const ctx = inspectContext ?? await inspectContextPromise
63-
if (!ctx)
64-
return
65-
66-
closingInspectContext ??= (async () => {
67-
await ctx.close()
68-
})()
69-
await closingInspectContext
70-
}
71-
72-
function removeInspectStorage(): void {
73-
if (inspectStorageDir)
74-
rmSync(inspectStorageDir, { recursive: true, force: true })
75-
}
76-
77-
async function resolveInspectContext(): Promise<ViteInspectContext | undefined> {
78-
if (inspectContext)
79-
return inspectContext
80-
return inspectContextPromise
81-
}
82-
8331
return {
8432
name: 'vite:devtools:vite-inspect',
8533
enforce: 'pre',
@@ -91,10 +39,8 @@ export function DevToolsViteInspect(): PluginWithDevTools {
9139
for (const fn of viteRpcFunctions)
9240
ctx.rpc.register(fn as any)
9341

94-
const currentInspectContext = await resolveInspectContext()
95-
96-
if (currentInspectContext) {
97-
setViteInspectContext(ctx, currentInspectContext)
42+
if (inspectContext) {
43+
setViteInspectContext(ctx, inspectContext)
9844
for (const fn of inspectRpcFunctions)
9945
ctx.rpc.register(fn as any)
10046

@@ -115,11 +61,19 @@ export function DevToolsViteInspect(): PluginWithDevTools {
11561
},
11662
},
11763

118-
async configResolved(config) {
119-
const ctx = await ensureInspectContext(config)
120-
if (!ctx)
64+
configResolved(config) {
65+
if (config.command !== 'serve')
12166
return
12267

68+
const cacheDir = config.cacheDir || join(config.root, 'node_modules/.vite')
69+
const storageDir = join(cacheDir, 'devtools', 'inspect')
70+
const ctx = inspectContext ??= ViteInspectContext.create({
71+
filename: () => {
72+
rmSync(storageDir, { recursive: true, force: true })
73+
return join(storageDir, 'payloads.bin')
74+
},
75+
})
76+
12377
const vite = ctx.getViteContext(config)
12478
vite.registerEnvironmentNames(Object.keys(config.environments))
12579

@@ -165,7 +119,7 @@ export function DevToolsViteInspect(): PluginWithDevTools {
165119
await closeServer()
166120
}
167121
finally {
168-
await closeInspectContext()
122+
await ctx.close()
169123
}
170124
}
171125

‎packages/vite/src/node/inspect/store/index.ts‎

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,12 @@ export type {
6969
ViteInspectTransformListItem,
7070
} from './types'
7171

72-
export async function createViteInspectStore(options: ViteInspectStoreOptions = {}): Promise<ViteInspectStore> {
73-
const filename = options.filename === ':memory:' ? undefined : options.filename
72+
interface InspectArchives {
73+
payloads: InspectPayloadStore
74+
pluginCalls: InspectPluginCallStore
75+
}
76+
77+
async function openArchives(filename?: string): Promise<InspectArchives> {
7478
if (filename)
7579
mkdirSync(dirname(filename), { recursive: true })
7680

@@ -80,7 +84,7 @@ export async function createViteInspectStore(options: ViteInspectStoreOptions =
8084
const pluginCalls = await createInspectPluginCallStore(
8185
filename ? join(dirname(filename), 'plugin-calls.bin') : undefined,
8286
)
83-
return new PayloadViteInspectStore(payloads, pluginCalls, options)
87+
return { payloads, pluginCalls }
8488
}
8589
catch (error) {
8690
await payloads?.close().catch(() => {})
@@ -89,11 +93,14 @@ export async function createViteInspectStore(options: ViteInspectStoreOptions =
8993
}
9094
}
9195

96+
export function createViteInspectStore(options: ViteInspectStoreOptions = {}): ViteInspectStore {
97+
return new PayloadViteInspectStore(options)
98+
}
99+
92100
class PayloadViteInspectStore implements ViteInspectStore {
93101
private readonly maxBatchItems: number
94102
private readonly maxBatchBytes: number
95-
private readonly payloads: InspectPayloadStore
96-
private readonly pluginCalls: InspectPluginCallStore
103+
private archives?: InspectArchives
97104
private readonly scopes = new Map<string, ScopeData>()
98105

99106
private queue: Array<PendingWrite | undefined> = []
@@ -116,13 +123,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
116123
private activeReaders = 0
117124
private readerWaiters: Array<() => void> = []
118125

119-
constructor(
120-
payloads: InspectPayloadStore,
121-
pluginCalls: InspectPluginCallStore,
122-
options: ViteInspectStoreOptions,
123-
) {
124-
this.payloads = payloads
125-
this.pluginCalls = pluginCalls
126+
constructor(private readonly options: ViteInspectStoreOptions) {
126127
this.maxBatchItems = positiveInteger(options.maxBatchItems, DEFAULT_MAX_BATCH_ITEMS)
127128
this.maxBatchBytes = positiveInteger(options.maxBatchBytes, DEFAULT_MAX_BATCH_BYTES)
128129
}
@@ -279,7 +280,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
279280
}
280281

281282
async getPluginCalls(scope: string, pluginId: number): Promise<ViteInspectPluginCallInfo[]> {
282-
return this.readSnapshot(() => this.pluginCalls.read(scope, pluginId))
283+
return this.readSnapshot(() => this.archives?.pluginCalls.read(scope, pluginId) ?? Promise.resolve([]))
283284
}
284285

285286
async getFirstResolveResult(scope: string, sourceId: string): Promise<string | undefined> {
@@ -346,8 +347,9 @@ class PayloadViteInspectStore implements ViteInspectStore {
346347
this.startPump()
347348
if (this.pumpPromise)
348349
await this.pumpPromise
350+
this.throwWriteError()
349351
}
350-
await this.pluginCalls.flush()
352+
await this.archives?.pluginCalls.flush()
351353
this.throwWriteError()
352354
}
353355

@@ -468,6 +470,12 @@ class PayloadViteInspectStore implements ViteInspectStore {
468470
private async writeDataBatch(
469471
writes: Array<Exclude<QueuedWrite, { operation: 'invalidate' | 'clearScope' | 'clearPendingLoadMetrics' }>>,
470472
): Promise<void> {
473+
// The write queue has a single consumer. Config-only callers never open the archives.
474+
if (!this.archives) {
475+
const filename = typeof this.options.filename === 'function' ? this.options.filename() : this.options.filename
476+
this.archives = await openArchives(filename === ':memory:' ? undefined : filename)
477+
}
478+
const { payloads, pluginCalls } = this.archives
471479
const values: Array<string | null | undefined> = []
472480
const prepared: PreparedWrite[] = []
473481
const pluginCallWrites: InspectPluginCallWrite[] = []
@@ -536,8 +544,8 @@ class PayloadViteInspectStore implements ViteInspectStore {
536544
}
537545

538546
const [ranges] = await Promise.all([
539-
values.length > 0 ? this.payloads.write(values) : Promise.resolve([]),
540-
this.pluginCalls.write(pluginCallWrites),
547+
values.length > 0 ? payloads.write(values) : Promise.resolve([]),
548+
pluginCalls.write(pluginCallWrites),
541549
])
542550
for (const item of prepared)
543551
this.applyPreparedWrite(item, ranges)
@@ -601,7 +609,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
601609
// Replace the previous snapshot even when it contains a load error result.
602610
if (!transforms || (write.transformRequest && transforms.transformRequest !== write.transformRequest)) {
603611
if (transforms)
604-
this.payloads.reclaim(collectPayloadRanges(transforms.items))
612+
this.archives?.payloads.reclaim(collectPayloadRanges(transforms.items))
605613
transforms = {
606614
transformRequest: write.transformRequest,
607615
publicModuleId: write.publicModuleId,
@@ -635,7 +643,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
635643
this.commitDeclinedLoadMetrics(data, write.publicModuleId, write.transformRequest)
636644
const existing = data.transforms.get(write.moduleId)
637645
if (existing)
638-
this.payloads.reclaim(collectPayloadRanges(existing.items))
646+
this.archives?.payloads.reclaim(collectPayloadRanges(existing.items))
639647
setTransforms(data, write.moduleId, {
640648
transformRequest: write.transformRequest,
641649
publicModuleId: write.publicModuleId,
@@ -660,7 +668,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
660668
private invalidateNow(scope: string, moduleId: string, publicModuleId: string): void {
661669
const data = this.scopes.get(scope)
662670
if (!data) {
663-
this.pluginCalls.invalidate(scope, new Set([publicModuleId]))
671+
this.archives?.pluginCalls.invalidate(scope, new Set([publicModuleId]))
664672
return
665673
}
666674

@@ -714,7 +722,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
714722
reclaimed.push(...collectPayloadRanges(transforms.items))
715723
deleteTransforms(data, id)
716724
}
717-
this.payloads.reclaim(reclaimed)
725+
this.archives?.payloads.reclaim(reclaimed)
718726

719727
deleteResolveIds(data, linkedResolveIds)
720728

@@ -727,25 +735,25 @@ class PayloadViteInspectStore implements ViteInspectStore {
727735
}
728736
}
729737

730-
this.pluginCalls.invalidate(scope, invalidPublicIds)
738+
this.archives?.pluginCalls.invalidate(scope, invalidPublicIds)
731739
}
732740

733741
private clearScopeNow(scope: string): void {
734742
const data = this.scopes.get(scope)
735743
if (!data) {
736-
this.pluginCalls.clearScope(scope)
744+
this.archives?.pluginCalls.clearScope(scope)
737745
return
738746
}
739747
const ranges: ViteInspectPayloadRange[] = []
740748
for (const transforms of data.transforms.values())
741749
ranges.push(...collectPayloadRanges(transforms.items))
742-
this.payloads.reclaim(ranges)
743-
this.pluginCalls.clearScope(scope)
750+
this.archives?.payloads.reclaim(ranges)
751+
this.archives?.pluginCalls.clearScope(scope)
744752
this.scopes.delete(scope)
745753
}
746754

747755
private async restoreTransformInfo(info: StoredViteInspectTransformInfo): Promise<ViteInspectTransformInfo> {
748-
const result = info.result ? await this.payloads.read(info.result) : undefined
756+
const result = info.result ? await this.archives!.payloads.read(info.result) : undefined
749757
return {
750758
name: info.name,
751759
plugin_id: info.pluginId,
@@ -812,14 +820,14 @@ class PayloadViteInspectStore implements ViteInspectStore {
812820
this.scheduledPump = undefined
813821
}
814822
try {
815-
await this.payloads.close()
823+
await this.archives?.payloads.close()
816824
}
817825
catch (error) {
818826
thrownError ??= error
819827
reportStorageError('closing the payload archive', error)
820828
}
821829
try {
822-
await this.pluginCalls.close()
830+
await this.archives?.pluginCalls.close()
823831
}
824832
catch (error) {
825833
thrownError ??= error

‎packages/vite/src/node/inspect/store/types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
} from '../types'
77

88
export interface ViteInspectStoreOptions {
9-
filename?: string
9+
filename?: string | (() => string)
1010
maxBatchItems?: number
1111
maxBatchBytes?: number
1212
}

0 commit comments

Comments
 (0)