Skip to content

Commit

Permalink
perf(optimizer): bulk optimizer delay (#12609)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Mar 27, 2023
1 parent 420782c commit c881971
Showing 1 changed file with 44 additions and 28 deletions.
72 changes: 44 additions & 28 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,14 +675,14 @@ async function createDepsOptimizer(
let registeredIds: { id: string; done: () => Promise<any> }[] = []
let seenIds = new Set<string>()
let workersSources = new Set<string>()
let waitingOn: string | undefined
const waitingOn = new Set<string>()
let firstRunEnsured = false

function resetRegisteredIds() {
registeredIds = []
seenIds = new Set<string>()
workersSources = new Set<string>()
waitingOn = undefined
waitingOn.clear()
firstRunEnsured = false
}

Expand All @@ -705,8 +705,8 @@ async function createDepsOptimizer(
// Avoid waiting for this id, as it may be blocked by the rollup
// bundling process of the worker that also depends on the optimizer
registeredIds = registeredIds.filter((registered) => registered.id !== id)
if (waitingOn === id) {
waitingOn = undefined
if (waitingOn.has(id)) {
waitingOn.delete(id)
runOptimizerWhenIdle()
}
}
Expand All @@ -719,32 +719,48 @@ async function createDepsOptimizer(
}
}

function runOptimizerWhenIdle() {
if (!waitingOn) {
const next = registeredIds.pop()
if (next) {
waitingOn = next.id
const afterLoad = () => {
waitingOn = undefined
if (!closed && !workersSources.has(next.id)) {
if (registeredIds.length > 0) {
runOptimizerWhenIdle()
} else {
onCrawlEnd()
}
}
}
next
.done()
.then(() => {
setTimeout(
afterLoad,
registeredIds.length > 0 ? 0 : runOptimizerIfIdleAfterMs,
)
})
.catch(afterLoad)
async function runOptimizerWhenIdle() {
if (waitingOn.size > 0) return

const processingRegisteredIds = registeredIds
registeredIds = []

const donePromises = processingRegisteredIds.map(async (registeredId) => {
waitingOn.add(registeredId.id)
try {
await registeredId.done()
} finally {
waitingOn.delete(registeredId.id)
}
})

const afterLoad = () => {
if (closed) return
if (
registeredIds.length > 0 &&
registeredIds.every((registeredId) =>
workersSources.has(registeredId.id),
)
) {
return
}

if (registeredIds.length > 0) {
runOptimizerWhenIdle()
} else {
onCrawlEnd()
}
}

const results = await Promise.allSettled(donePromises)
if (
registeredIds.length > 0 ||
results.some((result) => result.status === 'rejected')
) {
afterLoad()
} else {
setTimeout(afterLoad, runOptimizerIfIdleAfterMs)
}
}
}

Expand Down

0 comments on commit c881971

Please sign in to comment.