Skip to content

Commit 76282b9

Browse files
authored
perf(vite): speed up inspect module list (#623)
1 parent 22f6cd0 commit 76282b9

5 files changed

Lines changed: 90 additions & 5 deletions

File tree

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,3 +1509,48 @@ describe('vite inspect batched writes', () => {
15091509
])
15101510
})
15111511
})
1512+
1513+
describe('vite inspect modules list', () => {
1514+
it('reuses the list until a recorded change and then rebuilds it', async () => {
1515+
const { ctx, envCtx, vite } = await createFixture()
1516+
const plugin = vite.config.plugins[1]
1517+
const record = (id: string) => {
1518+
envCtx.recordTransform(id, { name: 'plugin-a', result: `export const id = '${id}'`, start: 0, end: 1 }, `const id = '${id}'`, plugin)
1519+
}
1520+
1521+
record('/src/a.ts')
1522+
const first = await envCtx.getModulesList()
1523+
expect(first.map(module => module.id)).toEqual(['/src/a.ts'])
1524+
expect(await envCtx.getModulesList()).toBe(first)
1525+
1526+
// Finishing a transform request doesn't change the recorded modules.
1527+
ctx.store.clearPendingLoadMetrics(envCtx.scope, {})
1528+
expect(await envCtx.getModulesList()).toBe(first)
1529+
1530+
record('/src/b.ts')
1531+
const second = await envCtx.getModulesList()
1532+
expect(second.map(module => module.id)).toEqual(['/src/a.ts', '/src/b.ts'])
1533+
1534+
envCtx.invalidate('/src/a.ts')
1535+
expect((await envCtx.getModulesList()).map(module => module.id)).toEqual(['/src/b.ts'])
1536+
})
1537+
1538+
it('builds the full sorted list when it takes several slices', async () => {
1539+
const { envCtx, vite } = await createFixture()
1540+
const plugin = vite.config.plugins[1]
1541+
const ids = Array.from({ length: 3000 }, (_, index) => `/src/m${String(index).padStart(4, '0')}.ts`)
1542+
for (const id of ids)
1543+
envCtx.recordTransform(id, { name: 'plugin-a', result: 'export {}', start: 0, end: 1 }, 'const a = 1', plugin)
1544+
1545+
// Make every module take longer than a slice, so the build yields between modules.
1546+
const now = vi.spyOn(performance, 'now')
1547+
let clock = 0
1548+
now.mockImplementation(() => (clock += 10))
1549+
try {
1550+
expect((await envCtx.getModulesList()).map(module => module.id)).toEqual(ids)
1551+
}
1552+
finally {
1553+
now.mockRestore()
1554+
}
1555+
})
1556+
})

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,12 +181,14 @@ export class ViteInspectViteContext {
181181
}
182182

183183
// Ids can carry HMR timestamps, so cap the cache instead of letting it grow for the whole session.
184-
const MAX_PUBLIC_MODULE_ID_CACHE_SIZE = 10_000
184+
// Keep it well above the module count of large projects, or the cache keeps clearing and never hits.
185+
const MAX_PUBLIC_MODULE_ID_CACHE_SIZE = 100_000
185186

186187
export class ViteInspectEnvironmentContext {
187188
readonly scope: string
188189
private pluginCallCount = 0
189190
private graphModuleIdResolver?: ReturnType<typeof createGraphModuleIdResolver>
191+
private modulesList?: { version: number, modules: ViteInspectModuleInfo[] }
190192
// Every hook call records its module id, so the same id is normalized once per plugin per request.
191193
private readonly publicModuleIds = new Map<string, string>()
192194
private publicModuleIdsRoot?: string
@@ -405,12 +407,27 @@ export class ViteInspectEnvironmentContext {
405407
}
406408

407409
async getModulesList(pluginCtx?: ModuleInfoProvider): Promise<ViteInspectModuleInfo[]> {
410+
// The panel refetches the list after every edit, often twice; reuse it until something is recorded.
411+
const store = this.inspectContext.store
412+
await store.flush()
413+
const version = store.getChangeVersion()
414+
if (!pluginCtx && this.modulesList?.version === version) {
415+
this.graphModuleIdResolver ??= this.createGraphModuleIdResolver(this.modulesList.modules)
416+
return this.modulesList.modules
417+
}
418+
408419
const modules = await getEnvironmentModulesList(this, pluginCtx)
409-
this.graphModuleIdResolver = createGraphModuleIdResolver(
420+
this.graphModuleIdResolver = this.createGraphModuleIdResolver(modules)
421+
if (!pluginCtx)
422+
this.modulesList = { version, modules }
423+
return modules
424+
}
425+
426+
private createGraphModuleIdResolver(modules: ViteInspectModuleInfo[]): ReturnType<typeof createGraphModuleIdResolver> {
427+
return createGraphModuleIdResolver(
410428
modules.map(module => module.id),
411429
this.env.getTopLevelConfig().resolve?.extensions ?? [],
412430
)
413-
return modules
414431
}
415432

416433
async getGraphModuleIdResolver(): Promise<ReturnType<typeof createGraphModuleIdResolver>> {

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import type {
66
} from './types'
77
import { DUMMY_LOAD_PLUGIN_NAME } from './utils'
88

9+
const MODULES_LIST_SLICE_MS = 4
10+
911
export interface ModuleInfoProvider {
1012
getModuleInfo: (id: string) => {
1113
importedIds?: readonly string[]
@@ -53,7 +55,7 @@ export async function getModulesList(
5355

5456
const ids = new Set(Object.keys(transformsById).concat(Object.keys(transformedIdMap)))
5557

56-
return Array.from(ids).sort().map((id) => {
58+
const toModuleInfo = (id: string): ViteInspectModuleInfo => {
5759
let totalTime = 0
5860
const transforms = transformsById[id] || []
5961
const transformPlugins: ViteInspectModulePluginMetric[] = transforms.map((transform) => {
@@ -85,7 +87,19 @@ export async function getModulesList(
8587
sourceSize: firstTransform?.hasResult ? firstTransform.resultSize : 0,
8688
distSize: lastTransform?.hasResult ? lastTransform.resultSize : 0,
8789
}
88-
})
90+
}
91+
92+
// Large projects take tens of milliseconds here; yield so Vite can keep serving requests meanwhile.
93+
const modules: ViteInspectModuleInfo[] = []
94+
let sliceStart = performance.now()
95+
for (const id of Array.from(ids).sort()) {
96+
modules.push(toModuleInfo(id))
97+
if (performance.now() - sliceStart > MODULES_LIST_SLICE_MS) {
98+
await new Promise(resolve => setImmediate(resolve))
99+
sliceStart = performance.now()
100+
}
101+
}
102+
return modules
89103
}
90104

91105
export async function getPublicGraphModuleIds(ctx: ViteInspectEnvironmentContext): Promise<string[]> {

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ class PayloadViteInspectStore implements ViteInspectStore {
112112
private peakQueuedBytes = 0
113113
private writeBatches = 0
114114

115+
private changeVersion = 0
115116
private activeReaders = 0
116117
private readerWaiters: Array<() => void> = []
117118

@@ -318,6 +319,10 @@ class PayloadViteInspectStore implements ViteInspectStore {
318319
return Array.from(moduleIds)
319320
}
320321

322+
getChangeVersion(): number {
323+
return this.changeVersion
324+
}
325+
321326
getStats(): ViteInspectStoreStats {
322327
return {
323328
maxBatchItems: this.maxBatchItems,
@@ -354,6 +359,8 @@ class PayloadViteInspectStore implements ViteInspectStore {
354359
private enqueue(write: QueuedWrite): void {
355360
if (this.closing || this.closed || this.lastWriteError)
356361
return
362+
if (write.operation !== 'clearPendingLoadMetrics')
363+
this.changeVersion += 1
357364

358365
const estimatedBytes = estimateWriteBytes(write)
359366
this.queue.push({ write, estimatedBytes })

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ export interface ViteInspectStore {
117117
getFirstResolveResult: (scope: string, sourceId: string) => Promise<string | undefined>
118118
findModuleId: (scope: string, publicModuleId: string) => Promise<string | undefined>
119119
getModuleIds: (scope: string) => Promise<string[]>
120+
/** Increases whenever a queued write can change recorded modules, so callers can reuse derived data until it changes. */
121+
getChangeVersion: () => number
120122
getStats: () => ViteInspectStoreStats
121123
flush: () => Promise<void>
122124
close: () => Promise<void>

0 commit comments

Comments
 (0)