Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add node worker-thread support to jest-worker #7408

Merged
merged 38 commits into from
Dec 5, 2018
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
418c6f9
Restructure workers (create a base class and inherit from it)
Jul 9, 2018
100c49f
Move child.js to workers folder
Jul 9, 2018
f786cb6
Restructure base classes and make a working POC
Jul 9, 2018
2a1ac0e
Remove BaseWorker
Jul 9, 2018
59ebd73
Remove MessageChannel and cleanup super() calls
Jul 9, 2018
9b1f19b
Use worker threads implementation if possible
Jul 9, 2018
bea945f
Restructure queues
Jul 10, 2018
3e9ce02
Support experimental modules in jest-resolver
Jul 11, 2018
02dedef
Rename child.js to processChild.js
Jul 11, 2018
5e8347b
Remove private properties from WorkerPoolInterface
Jul 11, 2018
e60bc1f
Move common line outside of if-else
Jul 11, 2018
b7470d6
Unify interface (use workerId) and remove recursion
Jul 11, 2018
092d700
Remove opt-out option for worker_threads in node 10.5+
Jul 11, 2018
3947fcb
Alphabetical import sorting
Jul 11, 2018
c715f00
Unlock worker after onEnd
Jul 11, 2018
4614e54
Cache queue head in the getNextJob loop
Jul 11, 2018
e0bfb83
Elegant while loop
Jul 11, 2018
9958587
Remove redundand .binds
Jul 11, 2018
29e04d2
Clean up interfaces and responsibilites
Jul 12, 2018
5b5323d
Merge
rickhanlonii Nov 19, 2018
d0041a9
Update jest-worker
rickhanlonii Nov 25, 2018
8d6a0e8
Add changelog and update jest-worker readme
rickhanlonii Nov 25, 2018
6c64753
Fix lint lol
rickhanlonii Nov 25, 2018
6677028
Merge remote-tracking branch 'origin/master' into rh-jest-worker-threads
rickhanlonii Dec 3, 2018
9f3b4aa
Fixes from review
rickhanlonii Dec 3, 2018
0d6ca7a
Merge remote-tracking branch 'upstream/master' into rh-jest-worker-th…
rickhanlonii Dec 3, 2018
e46802d
Update Changelog
rickhanlonii Dec 3, 2018
33beafb
rm function
rickhanlonii Dec 3, 2018
3282aef
rm []
rickhanlonii Dec 3, 2018
936a4b3
Make imports alphabetical 🤮
rickhanlonii Dec 3, 2018
0f6d46e
Go back to any
rickhanlonii Dec 3, 2018
aa734ec
Fix lint
rickhanlonii Dec 3, 2018
03e21f6
\n
rickhanlonii Dec 4, 2018
b55efe3
Fix formatting
rickhanlonii Dec 4, 2018
c22536c
Add docs
rickhanlonii Dec 4, 2018
880c16d
Revert canUseWorkerThreads
rickhanlonii Dec 4, 2018
b3e2967
Fix lint
rickhanlonii Dec 4, 2018
aec3368
Fix pathing on windows
rickhanlonii Dec 5, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea
.DS_STORE
.eslintcache
*.swp
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- `[jest-haste-map]` Accept a `getCacheKey` method in `hasteImplModulePath` modules to reset the cache when the logic changes ([#7350](https://github.com/facebook/jest/pull/7350))
- `[jest-config]` Add `haste.computeSha1` option to compute the sha-1 of the files in the haste map ([#7345](https://github.com/facebook/jest/pull/7345))
- `[expect]` `expect(Infinity).toBeCloseTo(Infinity)` Treats `Infinity` as equal in toBeCloseTo matcher ([#7405](https://github.com/facebook/jest/pull/7405))
- `[jest-worker]` Add node worker-thread support to jest-worker ([#7408](https://github.com/facebook/jest/pull/7408))

### Fixes

Expand Down
Empty file added jest-worker
Empty file.
10 changes: 6 additions & 4 deletions packages/jest-resolve/src/isBuiltinModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ declare var process: {
binding(type: string): {},
};

const EXPERIMENTAL_MODULES = ['worker_threads'];

const BUILTIN_MODULES =
builtinModules ||
Object.keys(process.binding('natives')).filter(
(module: string) => !/^internal\//.test(module),
);
builtinModules.concat(EXPERIMENTAL_MODULES) ||
Object.keys(process.binding('natives'))
.filter((module: string) => !/^internal\//.test(module))
.concat(EXPERIMENTAL_MODULES);

export default function isBuiltinModule(module: string): boolean {
return BUILTIN_MODULES.indexOf(module) !== -1;
Expand Down
6 changes: 6 additions & 0 deletions packages/jest-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ export function hello(param) {
}
```

## Experimental worker

Node 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a "threading API" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.

We will use worker threads where available. To enable in Node 10+, run the Node process with the `--experimental-worker` flag.
rickhanlonii marked this conversation as resolved.
Show resolved Hide resolved

## API

The only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.
Expand Down
159 changes: 159 additions & 0 deletions packages/jest-worker/src/Farm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/**
mjesun marked this conversation as resolved.
Show resolved Hide resolved
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

'use strict';

import type {
ChildMessage,
QueueChildMessage,
WorkerInterface,
OnStart,
OnEnd,
} from './types';
import {CHILD_MESSAGE_CALL} from './types';
export default class Farm {
rickhanlonii marked this conversation as resolved.
Show resolved Hide resolved
_computeWorkerKey: (string, ...Array<any>) => ?string;
_cacheKeys: {[string]: WorkerInterface, __proto__: null};
_callback: Function;
_last: Array<QueueChildMessage>;
_locks: Array<boolean>;
_numOfWorkers: number;
_offset: number;
_queue: Array<?QueueChildMessage>;

constructor(
numOfWorkers: number,
callback: Function,
computeWorkerKey?: (string, ...Array<any>) => ?string,
) {
this._callback = callback;
this._numOfWorkers = numOfWorkers;
this._cacheKeys = Object.create(null);
this._queue = [];
this._last = [];
this._locks = [];
this._offset = 0;
if (computeWorkerKey) {
this._computeWorkerKey = computeWorkerKey;
}
}

doWork(method: string, ...args: Array<any>): Promise<mixed> {
mjesun marked this conversation as resolved.
Show resolved Hide resolved
return new Promise((resolve, reject) => {
const computeWorkerKey = this._computeWorkerKey;
const request: ChildMessage = [CHILD_MESSAGE_CALL, false, method, args];

let worker: ?WorkerInterface = null;
let hash: ?string = null;

if (computeWorkerKey) {
hash = computeWorkerKey.apply(this, [method].concat(args));
worker = hash == null ? null : this._cacheKeys[hash];
}

const onStart: OnStart = (worker: WorkerInterface) => {
if (hash != null) {
this._cacheKeys[hash] = worker;
}
};

const onEnd: OnEnd = (error: ?Error, result: ?mixed) => {
if (error) {
reject(error);
} else {
resolve(result);
}
};

const task = {onEnd, onStart, request};
if (worker) {
this._enqueue(task, worker.getWorkerId());
} else {
this._push(task);
}
});
}

_getNextJob(workerId: number): ?QueueChildMessage {
let queueHead = this._queue[workerId];

while (queueHead && queueHead.request[1]) {
queueHead = queueHead.next;
}

this._queue[workerId] = queueHead;

return queueHead;
}

_process(workerId: number): Farm {
if (this.isLocked(workerId)) {
return this;
}

const job = this._getNextJob(workerId);

if (!job) {
return this;
}

const onEnd = (error: ?Error, result: mixed) => {
job.onEnd(error, result);
this.unlock(workerId);
this._process(workerId);
};

this.lock(workerId);

this._callback(workerId, job.request, job.onStart, onEnd);

job.request[1] = true;

return this;
}

_enqueue(task: QueueChildMessage, workerId: number): Farm {
if (task.request[1]) {
return this;
}

if (this._queue[workerId]) {
this._last[workerId].next = task;
} else {
this._queue[workerId] = task;
}

this._last[workerId] = task;
this._process(workerId);

return this;
}

_push(task: QueueChildMessage): Farm {
for (let i = 0; i < this._numOfWorkers; i++) {
const workerIdx = (this._offset + i) % this._numOfWorkers;
this._enqueue(task, workerIdx);
}
this._offset++;

return this;
}

lock(workerId: number): void {
this._locks[workerId] = true;
}

unlock(workerId: number): void {
this._locks[workerId] = false;
}

isLocked(workerId: number): boolean {
return this._locks[workerId];
}
}
52 changes: 52 additions & 0 deletions packages/jest-worker/src/WorkerPool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

'use strict';

import BaseWorkerPool from './base/BaseWorkerPool';

import type {
ChildMessage,
WorkerOptions,
OnStart,
OnEnd,
WorkerPoolInterface,
WorkerInterface,
} from './types';

let workerThreadsAreSupported = false;
try {
// $FlowFixMe: Flow doesn't know about experimental APIs
require('worker_threads');
workerThreadsAreSupported = true;
} catch (_) {}

class WorkerPool extends BaseWorkerPool implements WorkerPoolInterface {
send(
workerId: number,
request: ChildMessage,
onStart: OnStart,
onEnd: OnEnd,
): void {
this.getWorkerById(workerId).send(request, onStart, onEnd);
}

createWorker(workerOptions: WorkerOptions): WorkerInterface {
let Worker;
if (workerThreadsAreSupported) {
Worker = require('./workers/NodeThreadsWorker').default;
} else {
Worker = require('./workers/ChildProcessWorker').default;
}

return new Worker(workerOptions);
}
}

export default WorkerPool;
7 changes: 6 additions & 1 deletion packages/jest-worker/src/__performance_tests__/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
/**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
/**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

Expand Down
7 changes: 6 additions & 1 deletion packages/jest-worker/src/__performance_tests__/workers/pi.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
/**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
/**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

Expand Down
Loading