forked from rtfeldman/node-test-runner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncGet.js
More file actions
53 lines (49 loc) · 1.59 KB
/
SyncGet.js
File metadata and controls
53 lines (49 loc) · 1.59 KB
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
// @flow
const path = require('path');
const {
Worker,
MessageChannel,
receiveMessageOnPort,
// $FlowFixMe[cannot-resolve-module]: Flow doesn’t seem to know about the `worker_threads` module yet.
} = require('worker_threads');
// Poor man’s type alias. We can’t use /*:: type SyncGetWorker = ... */ because of:
// https://github.com/prettier/prettier/issues/2597
const SyncGetWorker /*: {
get: (string) => string,
shutDown: () => void,
} */ = {
get: (string) => string,
shutDown: () => {},
};
// Start a worker thread and return a `syncGetWorker`
// capable of making sync requests until shut down.
function startWorker() /*: typeof SyncGetWorker */ {
const { port1: localPort, port2: workerPort } = new MessageChannel();
const sharedLock = new SharedArrayBuffer(4);
// $FlowFixMe[incompatible-call]: Flow is wrong and says `sharedLock` is not an accepted parameter here.
const sharedLockArray = new Int32Array(sharedLock);
const workerPath = path.resolve(__dirname, 'SyncGetWorker.js');
const worker = new Worker(workerPath, {
workerData: { sharedLock, requestPort: workerPort },
transferList: [workerPort],
});
function get(url) {
worker.postMessage(url);
Atomics.wait(sharedLockArray, 0, 0); // blocks until notified at index 0.
const response = receiveMessageOnPort(localPort);
if (response.message.error) {
throw response.message.error;
} else {
return response.message;
}
}
function shutDown() {
localPort.close();
worker.terminate();
}
return { get, shutDown };
}
module.exports = {
SyncGetWorker,
startWorker,
};