-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathe.js
316 lines (310 loc) · 9.15 KB
/
e.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Add RPC capability to WebSocket command channel.
*
* Suppose you want to run `new Foo(1, 2).on('event', localListener)` on a remote worker,
* use the following steps:
*
* 0. Create RPC helper on each side of the channel:
*
* const rpcLocal = getRpcHelper(localChannel); // at local side
* const rpcRemote = getRpcHelper(remoteChannel); // at remote side
*
* 1. Register the class at remote:
*
* rpcRemote.registerClass('Foo', Foo);
*
* 2. Construct an object at local:
*
* const obj = await rpcLocal.construct('Foo', [ 1, 2 ]);
*
* 3. Call the method at local:
*
* const result = await rpcLocal.call(obj, 'on', [ 'event' ], [ listener ]);
*
* RPC methods can only have parameters of JSON and function types,
* and all callbacks must appear after JSON parameters.
*
* This utility has limited support for exceptions.
* If the remote method throws an Error, `rpc.call()` will throw an Error as well.
* The local error message contains `inspect(remoteError)` and should be sufficient for debugging purpose.
* However, those two errors are totally different objects so don't try to write concrete error handlers.
*
* Underlying, it uses a protocal similar to JSON-RPC:
*
* -> { type: 'rpc_constructor', id: 1, className: 'Foo', parameters: [ 1, 2 ] }
* <- { type: 'rpc_response', id: 1 }
*
* -> { type: 'rpc_method', id: 2, objectId: 1, methodName: 'bar', parameters: [ 'event' ], callbackIds: [ 3 ] }
* <- { type: 'rpc_response', id: 2, result: 'result' }
*
* <- { type: 'rpc_callback', id: 4, callbackId: 3, parameters: [ 'baz' ] }
**/
const rpcHelpers = new Map();
export class DefaultMap extends Map {
constructor(defaultFactory) {
super();
this.defaultFactory = defaultFactory;
}
get(key) {
const value = super.get(key);
if (value !== undefined) {
return value;
}
const defaultValue = this.defaultFactory();
this.set(key, defaultValue);
return defaultValue;
}
}
export class Deferred {
constructor() {
this.resolveCallbacks = [];
this.rejectCallbacks = [];
this.isResolved = false;
this.isRejected = false;
this.resolve = (value) => {
if (!this.isResolved && !this.isRejected) {
this.isResolved = true;
this.resolvedValue = value;
for (const callback of this.resolveCallbacks) {
callback(value);
}
} else if (this.isResolved && this.resolvedValue === value) {
console.debug("Double resolve:", value);
} else {
const msg = this.errorMessage("trying to resolve with value: " + value);
throw new Error("Conflict Deferred result. " + msg);
}
};
this.reject = (reason) => {
if (!this.isResolved && !this.isRejected) {
this.isRejected = true;
this.rejectedReason = reason;
for (const callback of this.rejectCallbacks) {
callback(reason);
}
} else if (this.isRejected) {
console.warning("Double reject:", this.rejectedReason, reason);
} else {
const msg = this.errorMessage(
"trying to reject with reason: " + reason
);
throw new Error("Conflict Deferred result. " + msg);
}
};
}
get promise() {
if (this.isResolved) {
return Promise.resolve(this.resolvedValue);
}
if (this.isRejected) {
return Promise.reject(this.rejectedReason);
}
return new Promise((resolutionFunc, rejectionFunc) => {
this.resolveCallbacks.push(resolutionFunc);
this.rejectCallbacks.push(rejectionFunc);
});
}
get settled() {
return this.isResolved || this.isRejected;
}
errorMessage(curStat) {
let prevStat = "";
if (this.isResolved) {
prevStat = "Already resolved with value: " + this.resolvedValue;
}
if (this.isRejected) {
prevStat = "Already rejected with reason: " + this.rejectedReason;
}
return prevStat + " ; " + curStat;
}
}
export function getRpcHelper(channel) {
if (!rpcHelpers.has(channel)) {
rpcHelpers.set(channel, new RpcHelper(channel));
}
return rpcHelpers.get(channel);
}
export class RpcHelper {
/**
* NOTE: Don't use this constructor directly. Use `getRpcHelper()`.
**/
constructor(channel) {
this.lastId = 0;
this.localCtors = new Map();
this.localObjs = new Map();
this.localCbs = new Map();
this.responses = new DefaultMap(() => new Deferred());
this.channel = channel;
this.channel.onCommand("rpc_constructor", (command) => {
this.invokeLocalConstructor(
command.id,
command.className,
command.parameters
);
});
this.channel.onCommand("rpc_method", (command) => {
this.invokeLocalMethod(
command.id,
command.objectId,
command.methodName,
command.parameters,
command.callbackIds
);
});
this.channel.onCommand("rpc_callback", (command) => {
this.invokeLocalCallback(
command.id,
command.callbackId,
command.parameters
);
});
this.channel.onCommand("rpc_response", (command) => {
this.responses.get(command.id).resolve(command);
});
}
/**
* Register a class for RPC use.
*
* This method must be called at remote side before calling `construct()` at local side.
* To ensure this, the client can call `getRpcHelper().registerClass()` before calling `connect()`.
**/
registerClass(className, constructor) {
this.localCtors.set(className, constructor);
}
/**
* Construct a class object remotely.
*
* Must be called after `registerClass()` at remote side, or an error will be raised.
**/
construct(className, parameters) {
return this.invokeRemoteConstructor(className, parameters ?? []);
}
/**
* Call a method on a remote object.
*
* The `objectId` is the return value of `construct()`.
*
* If the method returns a promise, `call()` will wait for it to resolve.
**/
call(objectId, methodName, parameters, callbacks) {
return this.invokeRemoteMethod(
objectId,
methodName,
parameters ?? [],
callbacks ?? []
);
}
async invokeRemoteConstructor(className, parameters) {
const id = this.generateId();
this.channel.send({ type: "rpc_constructor", id, className, parameters });
await this.waitResponse(id);
return id;
}
invokeLocalConstructor(id, className, parameters) {
const ctor = this.localCtors.get(className);
if (!ctor) {
this.sendRpcError(id, `Unknown class name ${className}`);
return;
}
let obj;
try {
obj = new ctor(...parameters);
} catch (error) {
this.sendError(id, error);
return;
}
this.localObjs.set(id, obj);
this.sendResult(id, undefined);
}
async invokeRemoteMethod(objectId, methodName, parameters, callbacks) {
const id = this.generateId();
const callbackIds = this.generateCallbackIds(callbacks);
this.channel.send({
type: "rpc_method",
id,
objectId,
methodName,
parameters,
callbackIds,
});
return await this.waitResponse(id);
}
async invokeLocalMethod(id, objectId, methodName, parameters, callbackIds) {
const obj = this.localObjs.get(objectId);
if (!obj) {
this.sendRpcError(id, `Non-exist object ${objectId}`);
return;
}
const callbacks = this.createCallbacks(callbackIds);
let result;
try {
result = obj[methodName](...parameters, ...callbacks);
if (typeof result === "object" && result.then) {
result = await result;
}
} catch (error) {
this.sendError(id, error);
return;
}
this.sendResult(id, result);
}
invokeRemoteCallback(callbackId, parameters) {
const id = this.generateId(); // for debug purpose
this.channel.send({ type: "rpc_callback", id, callbackId, parameters });
}
invokeLocalCallback(_id, callbackId, parameters) {
const cb = this.localCbs.get(callbackId);
if (cb) {
cb(...parameters);
} else {
}
}
generateId() {
this.lastId += 1;
return this.lastId;
}
generateCallbackIds(callbacks) {
const ids = [];
for (const cb of callbacks) {
const id = this.generateId();
ids.push(id);
this.localCbs.set(id, cb);
}
return ids;
}
createCallbacks(callbackIds) {
return callbackIds.map((id) => (...args) => {
this.invokeRemoteCallback(id, args);
});
}
sendResult(id, result) {
try {
JSON.stringify(result);
} catch {
this.sendRpcError(id, "method returns non-JSON value ");
return;
}
this.channel.send({ type: "rpc_response", id, result });
}
sendError(id, error) {
const msg = String(error.stack);
this.channel.send({ type: "rpc_response", id, error: msg });
}
sendRpcError(id, message) {
this.channel.send({
type: "rpc_response",
id,
error: `RPC framework error: ${message}`,
});
}
async waitResponse(id) {
const deferred = this.responses.get(id);
const res = await deferred.promise;
if (res.error) {
throw new Error(`RPC remote error:\n${res.error}`);
}
return res.result;
}
}