-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
327 lines (261 loc) · 9.03 KB
/
index.ts
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
317
318
319
320
321
322
323
324
325
326
import test from 'tape';
import Capnode, { capWrap } from '../index';
import { IAsyncApiObject, IAsyncApiValue, IRemoteFunction } from '../src/@types/index';
require ('../src/serializers/default.test');
require('./streaming');
require('./capWrap');
test('basic serialization and api reconstruction', async (t) => {
/**
* The API we want to make available over a serializable async boundary
* like a network, process, or other context:
*/
const api: IAsyncApiObject = {
foo: 'bar',
baz: async () => 'bam',
bork: undefined,
}
// A capnode is made a server by receiving an API as its index:
const cap = new Capnode({
index: api,
nickname: 'cap1',
});
// A client is created, perhaps in another process:
const cap2 = new Capnode({ nickname: 'cap2' });
// Each capnode creates a remote, representing its connection to the other:
const remote = cap.createRemote();
const remote2 = cap2.createRemote();
// Each remote is given a method to send messages to the other:
remote.addRemoteMessageListener((message) => remote2.receiveMessage(message));
remote2.addRemoteMessageListener((message) => remote.receiveMessage(message));
try {
// We can now request the index from cap1 on cap2:
const remoteApi: any = await cap2.requestIndex(remote2);
// Notice they are not the same objects:
t.notEqual(remoteApi, api, 'Api objects are not the same object.');
// They do, however, share the same properties and tyeps:
Object.keys(remoteApi).forEach((key) => {
t.ok(key in api, 'The original api has the key ' + key);
t.equal(typeof remoteApi[key], typeof api[key], 'The values are the same type');
// Other than functions, they are even the same value:
if (typeof remoteApi[key] !== 'function') {
t.equal(remoteApi[key], api[key]);
}
})
// We can even call the functions provided:
const result = await remoteApi.baz();
t.equal(result, 'bam');
} catch (err) {
t.error(err);
}
t.end();
})
test('creating an event emitter', async (t) => {
/**
* We want to support passing functions as arguments to remote functions.
*
* In this example, we subscribe to a method that will call our listener function
* after 100 ms.
*/
const api: IAsyncApiObject = {
subscribe: async (listener) => {
setTimeout(() => {
try {
if (listener && typeof listener === 'function') {
listener('foo');
} else {
t.fail('listener was no good:' + listener);
}
} catch (e) { t.error(e);}
}, 100)
return 'OKAY!';
}
}
const cap = new Capnode({
index: api,
nickname: 'cap1',
});
const cap2 = new Capnode({ nickname: 'cap2' });
const remote = cap.createRemote();
const remote2 = cap2.createRemote();
remote.addRemoteMessageListener((message) => remote2.receiveMessage(message));
remote2.addRemoteMessageListener((message) => remote.receiveMessage(message));
try {
const remoteApi: any = await cap2.requestIndex(remote2);
Object.keys(remoteApi).forEach((key) => {
t.ok(key in api, 'The original api has the key ' + key);
t.equal(typeof remoteApi[key], typeof api[key], 'The values are the same type');
if (typeof remoteApi[key] !== 'function') {
t.equal(remoteApi[key], api[key]);
}
})
// We can even call the functions provided:
const result = await remoteApi.subscribe(async (result: IAsyncApiValue) => {
t.equal(result, 'foo', 'The subscription was fired.');
t.end();
});
t.equal(result, 'OKAY!', 'the result was returned');
} catch (err) {
t.error(err);
}
})
test('passing event emitters around', async (t) => {
/**
* We want to support passing functions as arguments to remote functions.
*
* In this example, we subscribe to a method that will call our listener function
* after 100 ms.
*/
const api: IAsyncApiObject = {
subscribe: async (listener) => {
setTimeout(() => {
try {
if (typeof listener === 'function') {
listener('foo');
} else {
t.fail('listener was no good: ' + listener);
}
} catch (e) { t.error(e);}
}, 100)
return 'OKAY!';
}
}
const cap = new Capnode({
index: api,
nickname: 'cap1',
});
const cap2 = new Capnode({ nickname: 'cap2' });
const remote = cap.createRemote();
const remote2 = cap2.createRemote();
remote.addRemoteMessageListener((message) => remote2.receiveMessage(message));
remote2.addRemoteMessageListener((message) => remote.receiveMessage(message));
try {
const remoteApi: any = await cap2.requestIndex(remote2);
Object.keys(remoteApi).forEach((key) => {
t.ok(key in api, 'The original api has the key ' + key);
t.equal(typeof remoteApi[key], typeof api[key], 'The values are the same type');
if (typeof remoteApi[key] !== 'function') {
t.equal(remoteApi[key], api[key]);
}
})
// We can even call the functions provided:
const result = await remoteApi.subscribe(async (result: IAsyncApiValue) => {
t.equal(result, 'foo', 'The subscription was fired.');
t.end();
});
t.equal(result, 'OKAY!', 'the result was returned');
} catch (err) {
t.error(err);
}
})
test('passing functions back and forth', async (t) => {
/**
* There should be no limit to how many functions we can pass back and forth:
*/
const api: IAsyncApiObject = {
greet: async (greeting) => {
if (greeting === 'how do you do?') {
return {
value: 'very well, and you?',
reply: async (theirState: string) => {
t.equal(theirState, 'jolly well indeed.');
t.end();
}
}
}
},
}
const cap = new Capnode({
index: api,
nickname: 'cap1',
});
const cap2 = new Capnode({ nickname: 'cap2' });
const remote = cap.createRemote();
const remote2 = cap2.createRemote();
remote.addRemoteMessageListener((message) => remote2.receiveMessage(message));
remote2.addRemoteMessageListener((message) => remote.receiveMessage(message));
try {
const remoteApi: any = await cap2.requestIndex(remote2);
const reply = await remoteApi.greet('how do you do?');
t.ok(reply);
t.equal(reply.value, 'very well, and you?');
t.equal(typeof reply.reply, 'function');
reply.reply('jolly well indeed.');
} catch (err) {
t.error(err);
}
})
/**
* Since garbage collection only works on unreferenced local functions,
* we need to provide the `.dealloc()` method on all remote functions to allow consumers
* to deallocate remote function references.
*
* This will not be necessary after WeakRef is merged into the JS standard.
*/
test('remote deallocation', async (t) => {
const api: IAsyncApiObject = {
receiveEvents: async (emitter) => {
if (!emitter || typeof emitter !== 'object' || !('on' in emitter) || typeof emitter.on !== 'function') {
t.fail('emitter is no good ' + emitter);
return t.end();
}
// The emitter side is going to tell this side to deallocate:
emitter.on('data', (data: string) => {
t.equal(data, 'foo', 'event is fired correctly.');
});
}
}
const cap = new Capnode({
index: api,
nickname: 'cap1',
});
const cap2 = new Capnode({ nickname: 'cap2' });
const remote = cap.createRemote();
const remote2 = cap2.createRemote();
remote.addRemoteMessageListener((message) => remote2.receiveMessage(message));
remote2.addRemoteMessageListener((message) => remote.receiveMessage(message));
try {
const remoteApi: any = await cap2.requestIndex(remote2);
const listeners: IRemoteFunction[] = [];
const emitter = {
on: async (eventName:string, listener:IRemoteFunction) => {
t.equal(eventName, 'data');
listeners.push(listener);
// Emit our event:
await listener('foo');
const initialCount = cap.registeredMethodCount;
// Now we test the dealloc method:
await listeners[0].dealloc();
const subsequentCount = cap.registeredMethodCount;
t.equal(subsequentCount, initialCount - 1, 'The method was deallocated');
}
};
await remoteApi.receiveEvents(emitter);
} catch (err) {
t.error(err);
}
t.end();
})
test('proxy unwrapping', async (t) => {
const specialObject = {};
const api: IAsyncApiObject = {
specialObject,
isSpecialObject: async (obj: any) => {
return obj === specialObject;
},
}
try {
// We can now request the index from cap1 on cap2:
const remoteApi: IAsyncApiValue = await capWrap(api);
if (!remoteApi || typeof remoteApi !== 'object' || !('isSpecialObject' in remoteApi)
|| typeof remoteApi.isSpecialObject !== 'function'
|| !('specialObject' in remoteApi)) {
return t.fail('API not properly reconstructed.')
}
const specialProxy: IAsyncApiValue = remoteApi.specialObject;
const result = await remoteApi.isSpecialObject(specialProxy);
t.equal(result, true, 'Proxy should be special');
} catch (err) {
t.error(err);
}
t.end();
})