-
Notifications
You must be signed in to change notification settings - Fork 28.3k
/
public_loader_proxy.js
51 lines (45 loc) Β· 1.94 KB
/
public_loader_proxy.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
const { Worker } = require('internal/worker');
const { deserialize, serialize } = require('v8');
/**
* The communication vehicle constituting all memory shared between the main and the worker
*/
const commsChannel = new SharedArrayBuffer(2048);
/**
* The lock/unlock segment of the shared memory. Atomics require this to be a Int32Array. This
* segment is used to tell the main to sleep when the worker is worker, and vice verse (for the
* worker to sleep whilst the main is working).
* 0 β main sleeps
* 1 β worker sleeps
*/
const lock = new Int32Array(commsChannel, 0, 4);
/**
* The request & response segment of the shared memory. TextEncoder/Decoder (needed to convert
* requests & responses into a format supported by the comms channel) reads and writes with
* Uint8Array.
*/
const requestResponseData = new Uint8Array(commsChannel, 4, 2044);
const worker = new Worker('./worker.js', {
workerData: { commsChannel },
});
worker.unref(); // ! Allows the process to eventually exit when worker is in its final sleep.
Atomics.wait(lock, 0, 0); // ! Block this module until the worker is ready.
function makeRequest(type, data) {
requestResponseData.fill(0); // Erase any previous request/response (it's already been handled)
const request = serialize({ data, type });
requestResponseData.set(request);
Atomics.store(lock, 0, 0); // Send request to worker
Atomics.notify(lock, 0); // Notify worker of new request
Atomics.wait(lock, 0, 0); // Sleep until worker responds
return deserialize(requestResponseData);
}
module.exports = {
addCustomLoaders: (data) => makeRequest('addCustomLoaders', data),
cjsCache: {
delete: (data) => makeRequest('cjsCache.delete', data),
get: (data) => makeRequest('cjsCache.get', data),
has: (data) => makeRequest('cjsCache.has', data),
set: (data) => makeRequest('cjsCache.set', data),
},
import: (data) => makeRequest('import', data),
resolve: (data) => makeRequest('resolve', data),
};