-
Notifications
You must be signed in to change notification settings - Fork 507
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
perf: limit open files in generateFSTree (#2458)
Co-authored-by: Pooya Parsa <pooya@pi0.io>
- Loading branch information
1 parent
69b05a5
commit da42b05
Showing
4 changed files
with
58 additions
and
49 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
export async function runParallel<T>( | ||
inputs: Set<T>, | ||
cb: (input: T) => unknown | Promise<unknown>, | ||
opts: { concurrency: number; interval?: number } | ||
) { | ||
const tasks = new Set<Promise<unknown>>(); | ||
|
||
function queueNext(): undefined | Promise<unknown> { | ||
const route = inputs.values().next().value; | ||
if (!route) { | ||
return; | ||
} | ||
|
||
inputs.delete(route); | ||
const task = ( | ||
opts.interval | ||
? new Promise((resolve) => setTimeout(resolve, opts.interval)) | ||
: Promise.resolve() | ||
) | ||
.then(() => cb(route)) | ||
.catch((error) => { | ||
console.error(error); | ||
}); | ||
|
||
tasks.add(task); | ||
return task.then(() => { | ||
tasks.delete(task); | ||
if (inputs.size > 0) { | ||
return refillQueue(); | ||
} | ||
}); | ||
} | ||
|
||
function refillQueue(): Promise<unknown> { | ||
const workers = Math.min(opts.concurrency - tasks.size, inputs.size); | ||
return Promise.all(Array.from({ length: workers }, () => queueNext())); | ||
} | ||
|
||
await refillQueue(); | ||
} |