-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathaction-executor.ts
71 lines (59 loc) · 1.87 KB
/
action-executor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import Piscina from 'piscina';
import { InlineOptions } from './bundle-inline-options';
import { maxWorkers } from './environment-options';
import { I18nOptions } from './i18n-options';
const workerFile = require.resolve('./process-bundle');
export class BundleActionExecutor {
private workerPool?: Piscina;
constructor(private workerOptions: { i18n: I18nOptions }) {}
private ensureWorkerPool(): Piscina {
if (this.workerPool) {
return this.workerPool;
}
this.workerPool = new Piscina({
filename: workerFile,
name: 'inlineLocales',
workerData: this.workerOptions,
maxThreads: maxWorkers,
});
return this.workerPool;
}
async inline(
action: InlineOptions,
): Promise<{ file: string; diagnostics: { type: string; message: string }[]; count: number }> {
return this.ensureWorkerPool().run(action, { name: 'inlineLocales' });
}
inlineAll(actions: Iterable<InlineOptions>) {
return BundleActionExecutor.executeAll(actions, (action) => this.inline(action));
}
private static async *executeAll<I, O>(
actions: Iterable<I>,
executor: (action: I) => Promise<O>,
): AsyncIterable<O> {
const executions = new Map<Promise<O>, Promise<[Promise<O>, O]>>();
for (const action of actions) {
const execution = executor(action);
executions.set(
execution,
execution.then((result) => [execution, result]),
);
}
while (executions.size > 0) {
const [execution, result] = await Promise.race(executions.values());
executions.delete(execution);
yield result;
}
}
stop(): void {
if (this.workerPool) {
void this.workerPool.destroy();
}
}
}