-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.js
94 lines (81 loc) · 2.1 KB
/
rpc.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// tags: #rpc #design-mode
// 宿主环境提供线程通信 postMessage(message) 和 addListener((message)=>{}) 方法,封装他们进行 rpc 通讯
// 调用方式 const res = await rpc('method', ...params);
function initRPC(postMessage, addListener) {
let id = 0;
const channelMap = new Map();
function genId() {
return id++;
}
function rpc(method, ...params) {
const curId = genId();
postMessage(
JSON.stringify({
id: curId,
method,
params,
})
);
return new Promise((resolve, reject) => {
channelMap.set(curId, {
resolve,
reject,
});
});
}
addListener((message) => {
const { id, method, params, res } = JSON.parse(message);
if (res) {
const { resolve, reject } = channelMap.get(id);
if (res.data) {
resolve(res.data);
} else {
reject(res.error);
}
channelMap.delete(id);
} else {
try {
const data = globalThis[method](...params);
postMessage(
JSON.stringify({
id,
res: {
data,
},
})
);
} catch (e) {
postMessage(
JSON.stringify({
id,
res: {
error: e.message,
},
})
);
}
}
});
return rpc;
}
/* test code */
async function testRunner(fn) {
const { Worker, isMainThread, parentPort } = require("node:worker_threads");
if (isMainThread) {
const worker = new Worker(__filename);
globalThis.add = (a, b) => a + b;
const rpc = fn(worker.postMessage.bind(worker), (cb) =>
worker.on("message", cb)
);
console.log("parent thread(10-1):", await rpc("sub", 10, 1));
console.log("parent thread(1-10):", await rpc("sub", 1, 10));
} else {
globalThis.sub = (a, b) => a - b;
const rpc = fn(parentPort.postMessage.bind(parentPort), (cb) =>
parentPort.on("message", cb)
);
console.log("child thread(1+2):", await rpc("add", 1, 2));
console.log("child thread(2+3):", await rpc("add", 2, 3));
}
}
testRunner(initRPC);