-
-
Notifications
You must be signed in to change notification settings - Fork 156
/
TaskRunner.js
80 lines (62 loc) · 1.85 KB
/
TaskRunner.js
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
72
73
74
75
76
77
78
79
80
import os from 'os';
import Worker from 'jest-worker';
import serialize from 'serialize-javascript';
import minify from './minify';
const workerPath = require.resolve('./worker');
export default class TaskRunner {
constructor(options = {}) {
this.cache = options.cache;
this.numberWorkers = TaskRunner.getNumberWorkers(options.parallel);
}
static getNumberWorkers(parallel) {
// In some cases cpus() returns undefined
// https://github.com/nodejs/node/issues/19022
const cpus = os.cpus() || { length: 1 };
return parallel === true
? cpus.length - 1
: Math.min(Number(parallel) || 0, cpus.length - 1);
}
async runTask(task) {
if (this.worker) {
return this.worker.transform(serialize(task));
}
return minify(task);
}
async run(tasks) {
if (this.numberWorkers > 1) {
this.worker = new Worker(workerPath, { numWorkers: this.numberWorkers });
// show syntax error from jest-worker
// https://github.com/facebook/jest/issues/8872#issuecomment-524822081
if (this.worker.getStderr()) this.worker.getStderr().pipe(process.stderr);
}
return Promise.all(
tasks.map((task) => {
const enqueue = async () => {
let result;
try {
result = await this.runTask(task);
} catch (error) {
result = { error };
}
if (this.cache.isEnabled() && !result.error) {
return this.cache.store(task, result).then(
() => result,
() => result
);
}
return result;
};
if (this.cache.isEnabled()) {
return this.cache.get(task).then((data) => data, enqueue);
}
return enqueue();
})
);
}
async exit() {
if (!this.worker) {
return Promise.resolve();
}
return this.worker.end();
}
}