Debian Codegraph @

pkg/base1/test-channel.ts

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import QUnit from "qunit-tests";
3
4 import { transport_globals } from 'cockpit/_internal/transport';
5 import { Channel, ChannelControlMessage, ChannelOptions, ChannelPayload } from 'cockpit/channel';
6
7 // simple function to 'use' values (to avoid 'unused' warnings)
8 function use(..._args: unknown[]) {
9 }
10
11 // Many of the functions in this file are not designed to run, but to be
12 // typechecked. Here's some assertions for the types we'll check.
13 function is_str(_x: string): void {
14 }
15
16 function is_bytes(_x: Uint8Array): void {
17 }
18
19 // verify that type assertions are fundamentally working the way we think
20 function verify_type_assertions() {
21 const bytes = new Uint8Array();
22 const str = "";
23
24 // These are positive assertions
25 is_str(str);
26 is_bytes(bytes);
27
28 // These are typing fails. tsc will verify that they fail.
29 // @ts-expect-error Cannot pass bytes to is_str()
30 is_str(bytes);
31
32 // @ts-expect-error Cannot pass string to is_bytes()
33 is_bytes(str);
34 }
35
36 function is_str_channel(x: Channel<string>): void {
37 x.on('data', msg => is_str(msg));
38
39 // @ts-expect-error: of course string channels don't get binary data...
40 x.on('data', msg => is_bytes(msg));
41 }
42
43 function is_bytes_channel(x: Channel<Uint8Array>): void {
44 x.on('data', msg => is_bytes(msg));
45
46 // @ts-expect-error: of course binary channels don't get string data...
47 x.on('data', msg => is_str(msg));
48 }
49
50 // tsc seems to have inconsistent treatment of `void` argument types when
51 // things get complicated. If this ever gets fixed, search for 'VOID BUG'
52 // and adjust each test
53
54 // https://github.com/microsoft/TypeScript/issues/29131
55
56 // This is equivalent to 'void', but tsc treats it weirdly
57 type AlwaysVoid<P> = P extends string ? void : void;
58 function simple_void(_x: void): void { }
59 function weird_void<P>(_x: AlwaysVoid<P>): void { }
60 class VoidCtor<P> { constructor(x: AlwaysVoid<P>) { use(x) } }
61 class VoidCtorSubclass extends VoidCtor<unknown> { }
62 function test_void_weirdness() {
63 const v = (() => {})(); // get a value of type 'void'
64
65 // This works just fine
66 simple_void();
67 // @ts-expect-error But this doesn't work
68 weird_void();
69 weird_void(v); // but we can demonstrate that `void` is indeed accepted here
70
71 // @ts-expect-error This doesn't work
72 use(new VoidCtor<unknown>());
73 use(new VoidCtor<unknown>(v)); // ... even though 'void' is the argument type
74
75 // ...but for some reason this works, even though it's the very same function
76 use(new VoidCtorSubclass());
77 }
78
79 function test_channel_api_types() {
80 // @ts-expect-error: It's not valid to create a channel with no args
81 const no_args_channel = new Channel();
82 use(no_args_channel);
83
84 // @ts-expect-error: It's not valid to create a channel with no payload
85 const no_payload_channel = new Channel({});
86 use(no_payload_channel);
87
88 // @ts-expect-error: It's not valid to create a channel with no payload
89 const text_no_payload_channel = new Channel({ binary: false });
90 use(text_no_payload_channel);
91
92 // @ts-expect-error: It's not valid to create a channel with no payload
93 const bytes_no_payload_channel = new Channel({ binary: true });
94 use(bytes_no_payload_channel);
95
96 // This how to create a valid text channel
97 const text_channel = new Channel({ payload: 'echo' });
98 is_str_channel(text_channel);
99
100 // This is also fine, if you like to be explicit
101 const explicit_type_text_channel = new Channel<string>({ payload: 'echo' });
102 is_str_channel(explicit_type_text_channel);
103
104 // ...another way to be explicit
105 const explicit_opt_text_channel = new Channel({ payload: 'echo', binary: false });
106 is_str_channel(explicit_opt_text_channel);
107
108 // Or why not both at once?
109 const very_explicit_text_channel = new Channel<string>({ payload: 'echo', binary: false });
110 is_str_channel(very_explicit_text_channel);
111
112 // Binary channels need to specify both the type and the flag
113 const binary_channel = new Channel<Uint8Array>({ payload: 'echo', binary: true });
114 is_bytes_channel(binary_channel);
115
116 // Unfortunately we can't detect Channel<Uint8Array> based on `binary: true`
117 // without engaging a seriously advanced level of typing gymnastics (which
118 // would introduce other drawbacks).
119 // @ts-expect-error It would be nice if this were possible...
120 const autodetect_binary_channel = new Channel({ payload: 'echo', binary: true });
121 use(autodetect_binary_channel);
122
123 // But, directly using the new channel in a typed context should hint the
124 // correct type without explicitly specifying it, which will be the usual case.
125 is_str_channel(new Channel({ payload: 'echo' }));
126 is_str_channel(new Channel({ payload: 'echo', binary: false }));
127 is_bytes_channel(new Channel({ payload: 'echo', binary: true }));
128
129 // The opposite should all be impossible
130 // @ts-expect-error should not be able to convince a text channel that it's binary
131 is_bytes_channel(new Channel({ payload: 'echo' }));
132 // @ts-expect-error should not be able to convince a text channel that it's binary
133 is_bytes_channel(new Channel({ payload: 'echo', binary: false }));
134 // @ts-expect-error should not be able to convince a binary channel that it's text
135 is_str_channel(new Channel({ payload: 'echo', binary: true }));
136
137 // Explicitly giving the wrong type parameter should also be forbidden
138 // @ts-expect-error should not be able to convince a text channel that it's binary
139 const not_text_channel = new Channel<Uint8Array>({ payload: 'echo' });
140 use(not_text_channel);
141
142 // @ts-expect-error should not be able to convince a text channel that it's binary
143 const not_explicit_text_channel = new Channel<Uint8Array>({ payload: 'echo', binary: false });
144 use(not_explicit_text_channel);
145
146 // @ts-expect-error should not be able to convince a binary channel that it's text
147 const not_binary_channel = new Channel<string>({ payload: 'echo', binary: true });
148 use(not_binary_channel);
149 }
150
151 // This is how it looks to create a wrapper API that can open a channel in
152 // either text or binary mode.
153 function open_echo<P extends ChannelPayload = string>(options: ChannelOptions<P>): Channel<P> {
154 return new Channel({ ...options, payload: 'echo' });
155 }
156
157 // And this is how you use that API:
158 function test_open_echo_types() {
159 const string_echo = open_echo({});
160 is_str_channel(string_echo);
161
162 // @ts-expect-error This should be possible because `void` is valid for
163 // options but it oddly doesn't work (VOID BUG)
164 const string_echo_void = open_echo();
165 is_str_channel(string_echo_void);
166
167 const binary_echo = open_echo<Uint8Array>({ binary: true });
168 is_bytes_channel(binary_echo);
169 }
170
171 // Demonstrate how to properly do typing on a derived channel type which can be
172 // opened in either text or binary mode
173 class EchoChannel<P extends ChannelPayload = string> extends Channel<P> {
174 constructor(options: ChannelOptions<P>) {
175 super({ ...options, payload: 'echo' });
176 }
177 }
178
179 function test_echo_channel_types() {
180 const text_echo_channel = new EchoChannel({});
181 is_str_channel(text_echo_channel);
182
183 // @ts-expect-error This should also be possible because options can be void
184 // but is currently not working (VOID BUG)
185 const void_text_echo_channel = new EchoChannel();
186 is_str_channel(void_text_echo_channel);
187
188 const binary_echo_channel = new EchoChannel<Uint8Array>({ binary: true });
189 is_bytes_channel(binary_echo_channel);
190 }
191
192 // Various subclasses that further derive from EchoChannel to add a specific mode
193 export class TextEchoChannel extends EchoChannel<string> {
194 constructor() {
195 super({ binary: false });
196 }
197 }
198
199 export class TextEchoChannelDefaultArg extends EchoChannel<string> {
200 constructor() {
201 super({ });
202 }
203 }
204
205 export class TextEchoChannelTrivial extends EchoChannel<string> {
206 // eslint-disable-next-line no-useless-constructor
207 constructor() {
208 super();
209 }
210 }
211
212 export class TextEchoChannelNoConstructor extends EchoChannel<string> {
213 // this is fine, will be checked at instantiation
214 }
215
216 export class BinaryEchoChannel extends EchoChannel<Uint8Array> {
217 constructor() {
218 super({ binary: true });
219 }
220 }
221
222 export class BinaryEchoChannelNoConstructor extends EchoChannel<Uint8Array> {
223 // this is fine, but users will be required to pass `{ binary: true } for themselves
224 }
225
226 function test_fixed_type_echo_channels_types() {
227 const text_echo_channel = new TextEchoChannel();
228 is_str_channel(text_echo_channel);
229
230 const text_echo_channel_default_arg = new TextEchoChannelDefaultArg();
231 is_str_channel(text_echo_channel_default_arg);
232
233 const text_echo_channel_trivial = new TextEchoChannelTrivial();
234 is_str_channel(text_echo_channel_trivial);
235
236 // This is really the same as the other cases of passing no arguments (and
237 // indeed, we're directly calling the constructor on EchoChannel, but this
238 // time it works for some reason. VOID BUG doesn't affect this case?
239 const text_echo_channel_no_constructor = new TextEchoChannelNoConstructor();
240 is_str_channel(text_echo_channel_no_constructor);
241
242 // @ts-expect-error Of course this is invalid...
243 const text_binary_channel = new TextEchoChannelNoConstructor({ binary: true });
244 is_str_channel(text_binary_channel);
245
246 const binary_echo_channel = new BinaryEchoChannel();
247 is_bytes_channel(binary_echo_channel);
248
249 // We need to pass the `binary: true` flag ourselves since there's no
250 // constructor in this class to provide it for us.
251 const binary_echo_no_ctor = new BinaryEchoChannelNoConstructor({ binary: true });
252 is_bytes_channel(binary_echo_no_ctor);
253
254 // @ts-expect-error If we forget to pass the flag, it's an error
255 const binary_echo_no_arg = new BinaryEchoChannelNoConstructor();
256 is_bytes_channel(binary_echo_no_arg);
257
258 // @ts-expect-error If we pass the wrong flag, it's an error
259 const binary_echo_wrong_arg = new BinaryEchoChannelNoConstructor({ binary: false });
260 is_bytes_channel(binary_echo_wrong_arg);
261 }
262
263 // These three subclasses are incorrectly implemented and will trigger errors
264 export class BrokenTextEchoChannelWrongConstructor extends EchoChannel<string> {
265 constructor() {
266 // @ts-expect-error must specify binary: false for string channel
267 super({ binary: true });
268 }
269 }
270
271 export class BrokenBinaryEchoChannelWrongConstructor extends EchoChannel<Uint8Array> {
272 constructor() {
273 // @ts-expect-error must specify binary: true for Uint8Array channel
274 super({ binary: false });
275 }
276 }
277
278 export class BrokenBinaryEchoChannelTrivialConstructor extends EchoChannel<Uint8Array> {
279 // eslint-disable-next-line no-useless-constructor
280 constructor() {
281 // @ts-expect-error must specify binary: true for Uint8Array channel
282 super();
283 }
284 }
285
286 // Demonstrate typing on a function that can open a channel in either mode
287 function open_echo_subclass<P extends ChannelPayload = string>(options: ChannelOptions<P>): EchoChannel<P> {
288 return new EchoChannel(options);
289 }
290
291 function is_echo_channel<P extends ChannelPayload>(_channel: EchoChannel<P>) {
292 }
293
294 function test_open_echo_subclass_type() {
295 // @ts-expect-error VOID BUG is back again in this case...
296 const no_arg = open_echo_subclass();
297 is_echo_channel<string>(no_arg);
298
299 // legit calls
300 const empty_arg = open_echo_subclass({});
301 is_echo_channel<string>(empty_arg);
302
303 const false_arg = open_echo_subclass({ binary: false });
304 is_echo_channel<string>(false_arg);
305
306 const true_arg = open_echo_subclass<Uint8Array>({ binary: true });
307 is_echo_channel<Uint8Array>(true_arg);
308
309 // inferred type from context
310 is_echo_channel<string>(open_echo_subclass({}));
311 is_echo_channel<string>(open_echo_subclass({ binary: false }));
312 is_echo_channel<Uint8Array>(open_echo_subclass({ binary: true }));
313
314 // and the 'wrong' versions
315 // @ts-expect-error Can't have a binary channel with no args
316 is_echo_channel<Uint8Array>(open_echo_subclass({}));
317 // @ts-expect-error Can't have a binary channel with binary: false
318 is_echo_channel<Uint8Array>(open_echo_subclass({ binary: false }));
319 // @ts-expect-error Can't have a text channel with binary: true
320 is_echo_channel<string>(open_echo_subclass({ binary: true }));
321 }
322
323 // Demonstrate usage of above classes and functions
324 function test_payload_types() {
325 const text_channel = new Channel({ payload: 'echo' });
326 text_channel.on('data', msg => {
327 is_str(msg);
328
329 // @ts-expect-error This should be a string
330 is_bytes(msg);
331 });
332 text_channel.send_data('');
333 // @ts-expect-error Can't send binary data on text channels
334 text_channel.send_data(new Uint8Array());
335
336 const binary_channel = new Channel<Uint8Array>({ payload: 'echo', binary: true });
337 binary_channel.on('data', msg => {
338 is_bytes(msg);
339
340 // @ts-expect-error This should be a Uint8Array
341 is_str(msg);
342 });
343 binary_channel.send_data(new Uint8Array());
344 // @ts-expect-error Can't send text data on binary channels
345 binary_channel.send_data('');
346 }
347
348 export function test_unknown_payload(binary: boolean) {
349 // The type of a channel with unknown payload is Channel<ChannelPayload>
350 const unknown0 = new Channel<ChannelPayload>({ payload: 'echo', binary });
351
352 // Upcasting to the unknown type is always valid
353 const unknown1: Channel<ChannelPayload> =
354 new Channel<string>({ payload: 'echo' });
355 use(unknown1);
356 const unknown2: Channel<ChannelPayload> =
357 new Channel<Uint8Array>({ payload: 'echo', binary: true });
358 use(unknown2);
359
360 // @ts-expect-error Downcasting is not valid
361 const known1: Channel<string> = unknown0;
362 use(known1);
363 // @ts-expect-error Downcasting is not valid
364 const known2: Channel<string> = unknown0;
365 use(known2);
366
367 // It's possible to directly construct the unknown type with any binary flag
368 const unknown3 = new Channel<ChannelPayload>({ payload: 'echo' });
369 use(unknown3);
370 const unknown4 = new Channel<ChannelPayload>({ payload: 'echo', binary: true });
371 use(unknown4);
372 const unknown5 = new Channel<ChannelPayload>({ payload: 'echo', binary: false });
373 use(unknown5);
374
375 unknown0.on('data', msg => {
376 // @ts-expect-error msg on unknown payload channel is not str
377 is_str(msg);
378 // @ts-expect-error msg on unknown payload channel is not bytes
379 is_bytes(msg);
380 });
381
382 // Unfortunately, because of how the types work, either of these works.
383 // Fortunately, it's unproblematic at the protocol implementation level.
384 unknown0.send_data(new Uint8Array());
385 unknown0.send_data('');
386 }
387
388 // This is all just to verify various properties of the static typing
389 // Nothing will run this, so we export it to avoid an 'unused' warning
390 export function test_typing() {
391 verify_type_assertions();
392 test_void_weirdness();
393 test_channel_api_types();
394 test_open_echo_types();
395 test_echo_channel_types();
396 test_fixed_type_echo_channels_types();
397 test_open_echo_subclass_type();
398 test_payload_types();
399 }
400
401 // Actual dynamic tests start here
402 // This test must be the first test — it tests global transport startup
403 QUnit.test("test startup queue", async assert => {
404 assert.equal(transport_globals.default_transport, null, 'no transport yet');
405
406 const echo = new Channel({ payload: 'echo' });
407 // queue up a bunch of data before our first `await`
408 echo.send_data('a');
409 echo.send_control({ command: 'x' });
410 echo.send_data('b');
411 echo.send_control({ command: 'y' });
412 echo.send_data('c');
413 echo.send_control({ command: 'z' });
414 echo.done();
415
416 const incoming_messages: (string | ChannelControlMessage)[] = [];
417 echo.on('data', msg => incoming_messages.push(msg));
418 echo.on('control', msg => incoming_messages.push(msg));
419 echo.on('done', msg => incoming_messages.push(msg));
420 echo.on('close', msg => incoming_messages.push(msg));
421
422 // now we await. the Transport will come online here and our outgoing
423 // queue will drain then we'll receive our results.
424 assert.false(transport_globals.default_transport?.ready, 'transport not ready');
425 assert.true(echo.toString().includes('waiting for transport'), 'waiting for transport');
426 assert.equal(echo.id, null, 'null ID');
427
428 await echo.wait();
429
430 assert.true(transport_globals.default_transport?.ready, 'transport now ready');
431 assert.false(echo.toString().includes('waiting'), 'no longer waiting for anything');
432 assert.notEqual(echo.id, null, 'non-null ID');
433
434 // echo channel echos only data, not control
435 // but we will get done/close anyway
436 const expected_incoming_messages = [
437 'a',
438 'b',
439 'c',
440 { command: 'done', channel: echo.id },
441 { command: 'close', channel: echo.id },
442 ];
443
444 // wait until we have all of our expected messages, up to 1s
445 for (let i = 0; i < 100; i++) {
446 if (incoming_messages.length === expected_incoming_messages.length)
447 break;
448 await new Promise(resolve => window.setTimeout(resolve, 10));
449 }
450
451 assert.deepEqual(incoming_messages, expected_incoming_messages, 'received echoed messages');
452 assert.true(echo.toString().includes('closed'), 'channel closed');
453 });
454
455 QUnit.test("simple channel api", async assert => {
456 const binary_foo = new TextEncoder().encode('foo');
457
458 const echo = new Channel({ payload: 'echo' });
459 assert.true(echo.toString().includes('waiting for open'), 'waiting for open');
460 await echo.wait();
461 assert.true(echo.toString().includes('opened'), 'opened');
462 echo.send_data('foo');
463 const unknown_echo: Channel<ChannelPayload> = echo;
464 unknown_echo.send_data(binary_foo);
465 // make sure it comes back as a string
466 assert.equal(await new Promise(resolve => echo.on('data', resolve)), 'foo');
467 echo.done();
468 await new Promise(resolve => echo.on('done', resolve));
469 await new Promise(resolve => echo.on('close', resolve));
470 assert.true(echo.toString().includes('closed'), 'opened');
471
472 const binary_echo = new Channel<Uint8Array>({ payload: 'echo', binary: true });
473 await echo.wait();
474 const unknown_binary_echo: Channel<ChannelPayload> = binary_echo;
475 unknown_binary_echo.send_data('foo'); // send a string on a binary channel
476 // make sure it comes back as binary
477 assert.deepEqual(await new Promise(resolve => binary_echo.on('data', resolve)), binary_foo);
478 binary_echo.done();
479 await new Promise(resolve => binary_echo.on('done', resolve));
480 await new Promise(resolve => binary_echo.on('close', resolve));
481 });
482
483 QUnit.test("unsupported channel", async assert => {
484 const not_supported = new Channel({ payload: 'nonesuch' });
485 let err = null;
486 try {
487 await not_supported.wait();
488 } catch (exc) {
489 err = exc as ChannelControlMessage; // yaya
490 }
491 assert.equal(err?.problem, 'not-supported');
492 assert.true(not_supported.toString().includes('error not-supported'), 'got error');
493 });
494
495 QUnit.test("close with error", async assert => {
496 const channel = new Channel({ payload: 'nonesuch' });
497
498 let closed = null;
499 channel.on('close', msg => { closed = msg });
500 channel.close('xyz', { extra: 55 });
501 assert.deepEqual(closed, { command: 'close', problem: 'xyz', extra: 55 });
502
503 let err = null;
504 try {
505 await channel.wait();
506 } catch (exc) {
507 err = exc as ChannelControlMessage; // yaya;
508 }
509 assert.equal(err?.problem, 'xyz');
510 });
511
512 QUnit.test("no signals after manual close", async assert => {
513 let saw_data = false;
514
515 const channel = new Channel({ payload: 'echo' });
516 channel.on('data', () => { saw_data = true });
517 channel.send_data('a');
518 channel.send_data('b');
519 channel.send_data('c');
520 channel.close();
521
522 let err = null;
523 try {
524 await channel.wait();
525 } catch (exc) {
526 err = exc;
527 }
528 assert.deepEqual(err, { command: 'close' });
529
530 // wait for any extra signals
531 await new Promise(resolve => window.setTimeout(resolve, 100));
532 assert.false(saw_data, 'no data callbacks after close');
533 });
534
535 QUnit.start();