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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
|
import { gc } from "bun";
import { describe, test, expect, mock, beforeEach } from "bun:test";
import { channel, Channel, hasSubscribers, subscribe, unsubscribe } from "node:diagnostics_channel";
import { AsyncLocalStorage } from "node:async_hooks";
describe("Channel", () => {
// test-diagnostics-channel-has-subscribers.js
test("can have subscribers", () => {
const name = "channel1";
const dc = channel(name);
expect(hasSubscribers(name)).toBeFalse();
dc.subscribe(() => {});
expect(hasSubscribers(name)).toBeTrue();
checkCalls();
});
// test-diagnostics-channel-symbol-named.js
test("can have symbol as name", () => {
const input = {
foo: "bar",
};
const symbol = Symbol("channel2");
// Individual channel objects can be created to avoid future lookups
const dc = channel(symbol);
// Expect two successful publishes later
dc.subscribe(
mustCall((message, name) => {
expect(name).toBe(symbol);
expect(message).toStrictEqual(input);
}),
);
dc.publish(input);
expect(() => {
// @ts-expect-error
channel(null);
}).toThrow(/channel argument must be of type/);
checkCalls();
});
// test-diagnostics-channel-sync-unsubscribe.js
test("does not throw when unsubscribed", () => {
const name = "channel3";
const data = "some message";
const onMessageHandler: any = mustCall(() => unsubscribe(name, onMessageHandler));
subscribe(name, onMessageHandler);
// This must not throw.
channel(name).publish(data);
checkCalls();
});
// test-diagnostics-channel-pub-sub.js
test("can publish and subscribe", () => {
const name = "channel4";
const input = {
foo: "bar",
};
// Individual channel objects can be created to avoid future lookups
const dc = channel(name);
expect(dc).toBeInstanceOf(Channel);
// No subscribers yet, should not publish
expect(dc.hasSubscribers).toBeFalse();
const subscriber = mustCall((message, name) => {
expect(name).toBe(dc.name);
expect(message).toStrictEqual(input);
});
// Now there's a subscriber, should publish
subscribe(name, subscriber);
expect(dc.hasSubscribers).toBeTrue();
// The ActiveChannel prototype swap should not fail instanceof
expect(dc).toBeInstanceOf(Channel);
// Should trigger the subscriber once
dc.publish(input);
// Should not publish after subscriber is unsubscribed
expect(unsubscribe(name, subscriber)).toBeTrue();
expect(dc.hasSubscribers).toBeFalse();
// unsubscribe() should return false when subscriber is not found
expect(unsubscribe(name, subscriber)).toBeFalse();
expect(() => {
// @ts-expect-error
subscribe(name, null);
}).toThrow(/subscription argument must be of type/);
// Reaching zero subscribers should not delete from the channels map as there
// will be no more weakref to incRef if another subscribe happens while the
// channel object itself exists.
dc.subscribe(subscriber);
dc.unsubscribe(subscriber);
dc.subscribe(subscriber);
checkCalls();
});
// test-diagnostics-channel-object-channel-pub-sub.js
test("can publish and subscribe using object", () => {
const name = "channel5";
const input = {
foo: "bar",
};
// Should not have named channel
expect(hasSubscribers(name)).toBeFalse();
// Individual channel objects can be created to avoid future lookups
const dc = channel(name);
expect(dc).toBeInstanceOf(Channel);
expect(channel(name)).toBe(dc); // intentional object equality check
// No subscribers yet, should not publish
expect(dc.hasSubscribers).toBeFalse();
const subscriber = mustCall((message, name) => {
expect(name).toBe(dc.name);
expect(message).toStrictEqual(input);
});
// Now there's a subscriber, should publish
dc.subscribe(subscriber);
expect(dc.hasSubscribers).toBeTrue();
// The ActiveChannel prototype swap should not fail instanceof
expect(dc).toBeInstanceOf(Channel);
// Should trigger the subscriber once
dc.publish(input);
// Should not publish after subscriber is unsubscribed
expect(dc.unsubscribe(subscriber)).toBeTrue();
expect(dc.hasSubscribers).toBeFalse();
// unsubscribe() should return false when subscriber is not found
expect(dc.unsubscribe(subscriber)).toBeFalse();
expect(() => {
// @ts-expect-error
subscribe(null);
}).toThrow(/channel argument must be of type/);
checkCalls();
});
// test-diagnostics-channel-safe-subscriber-errors.js
// TODO: Needs support for 'uncaughtException' event
test.todo("can handle subscriber errors", () => {
const input = {
foo: "bar",
};
const dc = channel("channel6");
const error = new Error("This error should have been caught!");
process.on(
"uncaughtException",
mustCall(err => {
expect(err).toStrictEqual(error);
}),
);
dc.subscribe(
mustCall(() => {
throw error;
}),
);
// The failing subscriber should not stop subsequent subscribers from running
dc.subscribe(mustCall(() => {}));
// Publish should continue without throwing
const fn = mustCall(() => {});
dc.publish(input);
fn();
checkCalls();
});
// test-diagnostics-channel-bind-store.js
// TODO: Needs support for 'uncaughtException' event
test.todo("can use bind store", () => {
let n = 0;
const name = "channel7";
const thisArg = new Date();
const inputs = [{ foo: "bar" }, { baz: "buz" }];
const dc = channel(name);
// Bind a storage directly to published data
const store1 = new AsyncLocalStorage();
dc.bindStore(store1);
let store1bound = true;
// Bind a store with transformation of published data
const store2 = new AsyncLocalStorage();
dc.bindStore(
store2,
mustCall(data => {
expect(data).toStrictEqual(inputs[n]);
return { data };
}, 4),
);
// Regular subscribers should see publishes from runStores calls
dc.subscribe(
mustCall(data => {
if (store1bound) {
expect(data).toStrictEqual(store1.getStore());
}
expect({ data }).toStrictEqual(store2.getStore());
expect(data).toStrictEqual(inputs[n]);
}, 4),
);
// Verify stores are empty before run
expect(store1.getStore()).toBeUndefined();
expect(store2.getStore()).toBeUndefined();
dc.runStores(
inputs[n],
mustCall(function (a, b) {
// Verify this and argument forwarding
expect(this).toBe(thisArg);
expect(a).toBe(1);
expect(b).toBe(2);
// Verify store 1 state matches input
expect(store1.getStore()).toStrictEqual(inputs[n]);
// Verify store 2 state has expected transformation
expect(store2.getStore()).toStrictEqual({ data: inputs[n] });
// Should support nested contexts
n++;
dc.runStores(
inputs[n],
mustCall(function () {
// Verify this and argument forwarding
expect(this).toBeUndefined();
// Verify store 1 state matches input
expect(store1.getStore()).toStrictEqual(inputs[n]);
// Verify store 2 state has expected transformation
expect(store2.getStore()).toStrictEqual({ data: inputs[n] });
}),
);
n--;
// Verify store 1 state matches input
expect(store1.getStore()).toStrictEqual(inputs[n]);
// Verify store 2 state has expected transformation
expect(store2.getStore()).toStrictEqual({ data: inputs[n] });
}),
thisArg,
1,
2,
);
// Verify stores are empty after run
expect(store1.getStore()).toBeUndefined();
expect(store2.getStore()).toBeUndefined();
// Verify unbinding works
expect(dc.unbindStore(store1)).toBeTrue();
store1bound = false;
// Verify unbinding a store that is not bound returns false
expect(dc.unbindStore(store1)).toBeFalse();
n++;
dc.runStores(
inputs[n],
mustCall(() => {
// Verify after unbinding store 1 will remain undefined
expect(store1.getStore()).toBeUndefined();
// Verify still bound store 2 receives expected data
expect(store2.getStore()).toStrictEqual({ data: inputs[n] });
}),
);
// Contain transformer errors and emit on next tick
const fail = new Error("fail");
dc.bindStore(store1, () => {
throw fail;
});
let calledRunStores = false;
process.once(
"uncaughtException",
mustCall(err => {
expect(calledRunStores).toBeTrue();
expect(err).toStrictEqual(fail);
}),
);
dc.runStores(
inputs[n],
mustCall(() => {}),
);
calledRunStores = true;
checkCalls();
});
// test-diagnostics-channel-memory-leak.js
test("references are not leaked", () => {
function noop() {}
const heapUsedBefore = process.memoryUsage().heapUsed;
for (let i = 0; i < 1000; i++) {
const name = `channel7-${i}`;
subscribe(name, noop);
unsubscribe(name, noop);
}
gc(true);
const heapUsedAfter = process.memoryUsage().heapUsed;
expect(heapUsedBefore).toBeGreaterThanOrEqual(heapUsedAfter);
});
});
describe("TracingChannel", () => {
// Port tests from:
// https://github.com/search?q=repo%3Anodejs%2Fnode+test-diagnostics-channel+AND+%2Ftracing%2F&type=code
test.todo("TODO");
});
const mocks = new Map();
function mustCall<T>(fn: (...args: any[]) => T, expected?: number) {
const instance = mock(fn);
mocks.set(instance, expected ?? 1);
return instance;
}
function mustNotCall<T>(fn: (...args: any[]) => T) {
return mustCall(fn, 0);
}
// FIXME: remove this and use `afterEach` instead
// Currently, `bun test` disallows `expect()` in `afterEach`
function checkCalls() {
for (const [mock, expected] of mocks.entries()) {
expect(mock).toHaveBeenCalledTimes(expected);
}
mocks.clear();
}
beforeEach(() => {
mocks.clear();
});
|