37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
// SPEC: PJ2026-0106050514 Workbench实时运行面 draft-2026-06-30-p0-1297-spec-first.
|
|
// Responsibility: Async queue and bounded worker pool. Mechanically migrated from OpenCode opencode/src/util/queue.ts.
|
|
|
|
export class AsyncQueue<T> implements AsyncIterable<T> {
|
|
private queue: T[] = [];
|
|
private resolvers: Array<(value: T) => void> = [];
|
|
|
|
push(item: T): void {
|
|
const resolve = this.resolvers.shift();
|
|
if (resolve) resolve(item);
|
|
else this.queue.push(item);
|
|
}
|
|
|
|
async next(): Promise<T> {
|
|
if (this.queue.length > 0) return this.queue.shift() as T;
|
|
return new Promise((resolve) => this.resolvers.push(resolve));
|
|
}
|
|
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
while (true) yield await this.next();
|
|
}
|
|
}
|
|
|
|
export async function work<T>(concurrency: number, items: T[], fn: (item: T) => Promise<void>): Promise<void> {
|
|
const pending = [...items];
|
|
await Promise.all(
|
|
Array.from({ length: concurrency }, async () => {
|
|
while (true) {
|
|
const item = pending.pop();
|
|
if (item === undefined) return;
|
|
await fn(item);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
|