-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmqtt-test.mjs
More file actions
1056 lines (1007 loc) · 29.3 KB
/
Copy pathmqtt-test.mjs
File metadata and controls
1056 lines (1007 loc) · 29.3 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/** @typedef {import("mqtt/build").MqttClient} MqttClient */
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { decode } from 'cbor-x';
import { callOperation } from './utility.js';
import { setupTestApp } from './setupTestApp.mjs';
import environmentManager from '#src/utility/environment/environmentManager';
const { get: env_get, setProperty } = environmentManager;
import { connect, connectAsync } from 'mqtt';
import { readFileSync } from 'fs';
import { handleApplication as handleMQTTApplication } from '#src/server/mqtt';
// Adapter: creates a minimal scope and delegates to the new plugin API,
// capturing socket/ws server instances so callers can call .listen() on them.
function startMQTT(config) {
const serverInstances = [];
const mockServer = {
get mqtt() {
return global.server.mqtt;
},
set mqtt(value) {
global.server.mqtt = value;
},
socket(listener, options) {
const instance = global.server.socket(listener, options);
serverInstances.push(instance);
return instance;
},
ws(listener, options) {
const result = global.server.ws(listener, options);
serverInstances.push(...(Array.isArray(result) ? result : [result]));
return result;
},
};
handleMQTTApplication({
options: { getAll: () => config },
server: mockServer,
});
return serverInstances;
}
import axios from 'axios';
async function subscribeAllowingSubackError(client, topic, options) {
try {
return await client.subscribeAsync(topic, options);
} catch (error) {
if (error.packet?.cmd === 'suback') {
return error.packet.granted.map((qos) => ({ topic, qos }));
}
throw error;
}
}
async function connectWithMessageListener(brokerUrl, options, listener) {
const client = connect(brokerUrl, options);
client.on('message', listener);
await once(client, 'connect');
return client;
}
describe('test MQTT connections and commands', function () {
this.timeout(10000);
let available_records;
/** @type {MqttClient} */
let clientV4;
/** @type {MqttClient} */
let clientV5;
beforeEach(async () => {
available_records = await setupTestApp();
clientV4 = await connectAsync('ws://localhost:9926', {
protocolVersion: 4,
wsOptions: {
headers: {
Accept: 'application/cbor',
},
},
});
clientV5 = await connectAsync('mqtts://localhost:8883', {
protocolVersion: 5,
rejectUnauthorized: false,
});
});
it('subscribe to retained/persisted record', async function () {
let path = 'VariedProps/' + available_records[1];
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
clientV4.off('message', onMessage);
reject(new Error('Timeout waiting for retained message'));
}, 1000);
const onMessage = (topic, payload) => {
clearTimeout(timeout);
try {
assert.equal(topic, path);
const data = decode(payload);
assert.ok(data, 'Should have received a valid payload');
resolve();
} catch (e) {
reject(e);
}
};
clientV4.once('message', onMessage);
clientV4.subscribeAsync(path).catch(reject);
});
});
it('subscribe to retained/persisted record but with retain handling disabling retain messages', async function () {
let path = 'VariedProps/' + available_records[1];
await clientV5.subscribeAsync(path, { rh: 2 });
await new Promise((resolve, reject) => {
const onMessage = (topic, payload) => {
decode(payload);
reject(new Error('Should not receive any retained messages'));
};
clientV5.once('message', onMessage);
setTimeout(() => {
clientV5.off('message', onMessage);
resolve();
}, 50);
});
});
it('subscribe to top level without wildcard should not match record', async function () {
await clientV5.subscribeAsync('VariedProps/');
await new Promise((resolve, reject) => {
const onMessage = () => {
reject(new Error('Should not receive any top-level messages'));
};
clientV5.once('message', onMessage);
setTimeout(() => {
clientV5.off('message', onMessage);
resolve();
}, 50);
});
});
it('can repeatedly publish', async () => {
const vus = 5;
const tableName = 'SimpleRecord';
let intervals = [];
let clients = [];
let received = [];
let subscriptions = [];
for (let x = 1; x < vus + 1; x++) {
const topic = `${tableName}/1`;
/** @type {MqttClient} */
const client = await connectAsync({
clientId: `vu${x}`,
host: 'localhost',
clean: true,
connectTimeout: 2000,
protocol: 'mqtt',
protocolVersion: 4,
});
clients.push(client);
subscriptions.push(
(async () => {
await client.subscribeAsync(topic);
intervals.push(
setInterval(() => {
client.publish(topic, JSON.stringify({ name: 'radbot 9000', pub_time: Date.now() }), {
qos: 1,
retain: false,
});
}, 1)
);
})()
);
client.on('message', function (topic, message) {
// message is Buffer
let obj = JSON.parse(message.toString());
received.push(obj);
});
client.on('error', function (error) {
// message is Buffer
console.error(error);
});
}
await Promise.all(subscriptions);
await new Promise((resolve) => setTimeout(resolve, 200));
for (let interval of intervals) clearInterval(interval);
await new Promise((resolve) => setTimeout(resolve, 20));
for (let client of clients) client.end();
assert(received.length > 10);
assert.equal(received[0].name, 'radbot 9000');
});
it('last will should be published on connection loss', async () => {
const topic = `SimpleRecord/52`;
/** @type {MqttClient} */
const client_to_die = await connectAsync({
host: 'localhost',
clean: true,
protocolVersion: 4,
will: {
topic,
payload: JSON.stringify({ name: 'last will and testimony' }),
qos: 1,
retain: false,
},
});
await clientV4.subscribeAsync(topic);
await new Promise((resolve, reject) => {
clientV4.once('message', function (topic, message) {
try {
let data = decode(message);
// message is Buffer
assert.deepEqual(data, { name: 'last will and testimony' });
resolve();
} catch (error) {
reject(error);
}
});
client_to_die.end(true); // this closes the connection without a disconnect packet
});
});
it('last will should not be published on explicit disconnect', async () => {
const topic = `SimpleRecord/53`;
const client_to_die = await connectAsync({
host: 'localhost',
clean: true,
protocolVersion: 4,
will: {
topic,
payload: JSON.stringify({ name: 'last will and testimony' }),
qos: 1,
retain: false,
},
});
let onMessage;
await clientV4.subscribeAsync(topic);
await new Promise((resolve, reject) => {
onMessage = function (topic) {
try {
reject('Should not get a message on topic ' + topic);
} catch (error) {
reject(error);
}
};
clientV4.once('message', onMessage);
setTimeout(resolve, 50);
client_to_die.end(); // this closes the connection with a disconnect packet
});
clientV4.off('message', onMessage);
});
it('can publish non-JSON', async () => {
const topic = `SimpleRecord/51`;
const client = await connectAsync({
host: 'localhost',
clean: true,
connectTimeout: 2000,
protocol: 'mqtt',
protocolVersion: 4,
});
await client.subscribeAsync(topic);
await new Promise((resolve) => {
client.publish(topic, Buffer.from([1, 2, 3, 4, 5]), {
qos: 1,
retain: false,
});
client.on('message', function (topic, message) {
// message is Buffer
assert.deepEqual(Array.from(message), [1, 2, 3, 4, 5]);
resolve();
});
client.on('error', function (error) {
// message is Buffer
console.error(error);
});
});
});
it('publish and subscribe are restricted', async () => {
const topic = `SimpleRecord/51`;
const client_authorized = await connectAsync({
host: 'localhost',
clean: true,
connectTimeout: 2000,
protocol: 'mqtt',
protocolVersion: 4,
});
const client = await connectAsync({
host: 'localhost',
clean: true,
connectTimeout: 2000,
protocol: 'mqtt',
protocolVersion: 4,
username: 'restricted',
password: 'restricted',
will: {
topic,
payload: JSON.stringify({ name: 'last will and testimony that should not be published' }),
qos: 1,
},
});
let published_messages = [];
const granted = await subscribeAllowingSubackError(client, topic);
assert.equal(granted[0].qos, 128);
await client_authorized.subscribeAsync(topic);
await new Promise((resolve) => {
client.publish(topic, JSON.stringify({ name: 'should not be published ' }), {
qos: 1,
retain: false,
});
client_authorized.on('message', function (topic) {
published_messages.push(topic);
});
client.on('error', function (error) {
// message is Buffer
console.error('Error connecting to restricted client', error);
});
setTimeout(resolve, 50);
});
client.end(true); // force close to trigger the will message
await delay(50);
assert.equal(published_messages.length, 0);
});
it('can not subscribe to resource with mqtt export disabled', async () => {
const client = await connectAsync({
host: 'localhost',
clean: true,
connectTimeout: 2000,
protocolVersion: 4,
});
const granted = await subscribeAllowingSubackError(client, 'Related/#');
assert.equal(granted[0].qos, 128);
});
it('subscribe to retained record with upsert operation', async function () {
let path = 'SimpleRecord/77';
let client = await connectAsync('mqtt://localhost:1883', {
protocolVersion: 4,
});
await new Promise((resolve, reject) => {
client.subscribeAsync(path).catch(reject);
client.once('message', (topic, payload) => {
JSON.parse(payload);
resolve();
});
callOperation({
operation: 'upsert',
schema: 'data',
table: 'SimpleRecord',
records: [
{
id: '77',
name: 'test record from operation',
},
],
}).then(
(response) => {
response.json().then((data) => {
console.log(data);
});
},
(error) => {
reject(error);
}
);
});
client.end();
});
it('subscribe to retained record with patch operations', async function () {
let path = 'SimpleRecord/78';
let client = await connectAsync('mqtt://localhost:1883', {
clean: false,
clientId: 'with-patches',
protocolVersion: 4,
});
let headers = {
'Content-Type': 'application/json',
};
await new Promise(async (resolve) => {
let messages = [];
const onMessage = (topic, payload) => {
let record = JSON.parse(payload);
messages.push(record);
if (messages.length === 2) {
assert.equal(messages[0].name, 'a starting point');
assert.equal(messages[0].count, 2);
assert.equal(messages[1].count, 3);
assert.equal(messages[1].name, 'an updated name');
assert.equal(messages[1].newProperty, 'new value');
resolve();
client.off('message', onMessage);
}
};
client.on('message', onMessage);
await client.subscribeAsync(path, { qos: 1 });
await axios.put('http://localhost:9926/SimpleRecord/78', { name: 'a starting point', count: 2 }, { headers });
// Small delay so the PUT notification is delivered before the PATCH; without this the
// two messages can arrive out of order on a loaded CI runner.
await delay(20);
await axios.patch(
'http://localhost:9926/SimpleRecord/78',
{ name: 'an updated name', newProperty: 'new value', count: { __op__: 'add', value: 1 } },
{ headers }
);
});
await client.endAsync();
// Give the broker time to fully process the disconnect before we make more patches,
// so those patches are queued for the offline client rather than delivered live.
await delay(50);
await axios.patch(
'http://localhost:9926/SimpleRecord/78',
{ name: 'update 2', newProperty: 'newer value', count: { __op__: 'add', value: 1 } },
{ headers }
);
await axios.patch(
'http://localhost:9926/SimpleRecord/78',
{ name: 'update 3', count: { __op__: 'add', value: 1 } },
{ headers }
);
await new Promise(async (resolve, reject) => {
let messages = [];
client = await connectWithMessageListener(
'mqtt://localhost:1883',
{
clean: false,
clientId: 'with-patches',
protocolVersion: 4,
},
(topic, payload, _packet) => {
let record = JSON.parse(payload);
messages.push(record);
if (messages.length == 3) {
assert.equal(messages[0].name, 'update 2');
assert.equal(messages[0].count, 4);
assert.equal(messages[1].newProperty, 'newer value');
assert.equal(messages[1].name, 'update 3');
assert.equal(messages[1].count, 5);
assert.equal(messages[2].name, 'update 4');
assert.equal(messages[2].count, 6);
resolve();
}
}
);
client.on('error', reject);
await axios.patch(
'http://localhost:9926/SimpleRecord/78',
{ name: 'update 4', count: { __op__: 'add', value: 1 } },
{ headers }
);
});
client.end();
});
it('subscribe twice', async function () {
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client-sub2',
protocolVersion: 4,
});
await client.subscribeAsync('SimpleRecord/22', { qos: 1 });
await client.subscribeAsync('SimpleRecord/22', { qos: 1 });
await new Promise((resolve) => {
client.once('message', (topic, payload) => {
JSON.parse(payload);
resolve();
});
client.publish(
'SimpleRecord/22',
JSON.stringify({
name: 'This is a test again',
}),
{
retain: false,
qos: 1,
}
);
});
await client.endAsync();
});
it('received binary/string messages', async function () {
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client-sub2',
protocolVersion: 4,
});
await client.subscribeAsync('SimpleRecord/22', { qos: 0 });
await new Promise((resolve) => {
client.on('message', (topic, payload) => {
assert.equal(payload.toString(), 'This is a test of a plain string');
resolve();
});
client.publish('SimpleRecord/22', 'This is a test of a plain string', {
retain: true,
qos: 1,
});
});
await client.endAsync();
client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client-sub2',
protocolVersion: 4,
});
await new Promise((resolve, reject) => {
client.on('message', (topic, payload) => {
assert.equal(payload.toString(), 'This is a test of a plain string');
resolve();
});
client.subscribeAsync('SimpleRecord/22', { qos: 0 }).catch(reject);
});
await client.endAsync();
});
it('subscribe and unsubscribe with mTLS', async function () {
let server;
await new Promise((resolve, reject) => {
server = startMQTT({
server: global.server,
network: { securePort: 8884, mtls: { user: 'HDB_ADMIN', required: true } },
})[0].listen(8884, resolve);
server.on('error', reject);
});
let bad_client = await connectAsync('mqtts://localhost:8884', {
clientId: 'test-bad-mtls',
protocolVersion: 4,
reconnectPeriod: 0,
}).catch(() => null);
const private_key_path = env_get('tls_privateKey');
let cert, ca;
for await (const certificate of databases.system.hdb_certificate.search([])) {
if (certificate.is_authority) ca = certificate.certificate;
else if (certificate.name === 'localhost') cert = certificate.certificate;
}
let client = await connectAsync('mqtts://localhost:8884', {
key: readFileSync(private_key_path),
cert,
ca,
// Self-signed CA in test environment; mTLS is server-side (server rejects clients without
// a cert), so we skip client-side server-cert verification to avoid intermittent
// "self-signed certificate in certificate chain" failures on loaded runners.
rejectUnauthorized: false,
clean: true,
clientId: 'test-client-mtls',
protocolVersion: 4,
});
if (bad_client && bad_client.connected) {
throw new Error('Client should not be able to connect to mTLS without a certificate');
}
await client.subscribeAsync('SimpleRecord/23', { qos: 1 });
await client.unsubscribeAsync('SimpleRecord/23');
await new Promise((resolve, reject) => {
client.on('message', (topic, payload) => {
JSON.parse(payload);
reject('Should not receive a message that we are unsubscribed to');
});
client.publish(
'SimpleRecord/23',
JSON.stringify({
name: 'This is a test again',
}),
{
retain: false,
qos: 1,
}
);
setTimeout(resolve, 50);
});
client.end();
});
it('subscribe and unsubscribe with WSS mTLS', async function () {
let server;
try {
await new Promise((resolve, reject) => {
setProperty('http_mtls', { user: 'HDB_ADMIN', required: true });
server = startMQTT({
server: global.server,
webSocket: {
securePort: 8885,
network: { mtls: { user: 'HDB_ADMIN', required: true } },
},
})[0].listen(8885, resolve);
server.on('error', reject);
});
const private_key_path = env_get('tls_privateKey');
let cert, ca;
for await (const certificate of databases.system.hdb_certificate.search([])) {
if (certificate.is_authority) ca = certificate.certificate;
else if (certificate.name === 'localhost') cert = certificate.certificate;
}
let bad_client = await connectAsync('wss://localhost:8885', {
reconnectPeriod: 0,
clientId: 'test-bad-mtls',
protocolVersion: 4,
}).catch(() => null);
let client = await connectAsync('wss://localhost:8885', {
key: readFileSync(private_key_path),
cert,
ca,
// Same rationale as the TCP mTLS test: skip client-side server-cert check.
rejectUnauthorized: false,
clean: true,
reconnectPeriod: 0,
clientId: 'test-client-mtls',
protocolVersion: 4,
});
if (bad_client && bad_client.connected) {
throw new Error('Client should not be able to connect to mTLS without a certificate');
}
await subscribeAllowingSubackError(client, 'SimpleRecord/23', { qos: 1 });
await client.unsubscribeAsync('SimpleRecord/23');
await new Promise((resolve, reject) => {
client.on('message', (topic, payload) => {
JSON.parse(payload);
reject('Should not receive a message that we are unsubscribed to');
});
client.publish(
'SimpleRecord/23',
JSON.stringify({
name: 'This is a test again',
}),
{
retain: false,
qos: 1,
}
);
setTimeout(resolve, 50);
});
client.end();
} finally {
setProperty('http_mtls', false);
}
});
it('subscribe to bad topic', async function () {
const granted = await subscribeAllowingSubackError(clientV5, 'DoesNotExist/+');
assert.equal(granted[0].qos, 0x8f);
});
it('Invalid packet', async function () {
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client1',
protocolVersion: 4,
});
// directly send an invalid packet, which should cause the connection to close
client.stream.write(Buffer.from([67, 255]));
await new Promise((resolve) => {
client.on('close', resolve);
});
});
const wildcardsTests = () =>
async function () {
const topic_expectations = {
//'SimpleRecord/+': ['SimpleRecord/', 'SimpleRecord/44', 'SimpleRecord/47'],
'SimpleRecord/+/33': ['SimpleRecord/sub/33'],
'SimpleRecord/sub/+': ['SimpleRecord/sub/33'],
'SimpleRecord/sub/+/33': ['SimpleRecord/sub/sub2/33'],
'SimpleRecord/+/+/+': ['SimpleRecord/sub/sub2/33'],
'SimpleRecord/+/sub2/+': ['SimpleRecord/sub/sub2/33'],
'SimpleRecord/+/+': ['SimpleRecord/sub/33'],
'SimpleRecord/sub/#': ['SimpleRecord/sub/33', 'SimpleRecord/sub/sub2/33'],
'SimpleRecord/+/sub2/#': ['SimpleRecord/sub/sub2/33'],
};
for (const subscription_topic in topic_expectations) {
let expected_topics = topic_expectations[subscription_topic];
await clientV5.subscribeAsync(subscription_topic);
let message_count = 0;
let message_listener;
await new Promise((resolve) => {
clientV5.on(
'message',
(message_listener = (topic, payload) => {
assert(expected_topics.includes(topic));
let record = JSON.parse(payload);
assert(record.name);
if (++message_count == expected_topics.length) resolve();
})
);
clientV5.publish(
'SimpleRecord/44',
JSON.stringify({
name: 'This is a test 1',
}),
{
retain: false,
qos: 1,
}
);
clientV5.publish(
'SimpleRecord/sub/33',
JSON.stringify({
name: 'This is a test to a sub-topic',
}),
{
retain: false,
qos: 1,
}
);
clientV5.publish(
'SimpleRecord/sub/sub2/33',
JSON.stringify({
name: 'This is a test to a deeper sub-topic',
}),
{
retain: false,
qos: 1,
}
);
clientV4.publish(
'SimpleRecord/47',
JSON.stringify({
name: 'This is a test 2',
}),
{
retain: true,
qos: 1,
}
);
clientV4.publish(
'SimpleRecord/',
JSON.stringify({
name: 'This is a test to the generic table topic',
}),
{
qos: 1,
}
);
});
clientV5.off('message', message_listener);
await clientV5.unsubscribeAsync(subscription_topic);
}
};
it('subscribe to single-level wildcard/full table', wildcardsTests());
it('subscribe to multi-level wildcard/full table', async function () {
await clientV5.subscribeAsync('SimpleRecord/#');
let message_count = 0;
let message_listener;
await new Promise((resolve) => {
clientV5.on(
'message',
(message_listener = (topic, payload) => {
let record = JSON.parse(payload);
assert(record.name);
if (++message_count == 4) resolve();
})
);
clientV5.publish(
'SimpleRecord/44',
JSON.stringify({
name: 'This is a test 1',
}),
{
retain: false,
qos: 1,
}
);
clientV5.publish(
'SimpleRecord/sub/33',
JSON.stringify({
name: 'This is a test to a sub-topic', // should go to multi-level wildcard
}),
{
retain: false,
qos: 1,
}
);
clientV4.publish(
'SimpleRecord/47',
JSON.stringify({
name: 'This is a test 2',
}),
{
retain: true,
qos: 1,
}
);
clientV4.publish(
'SimpleRecord/',
JSON.stringify({
name: 'This is a test to the generic table topic',
}),
{
qos: 1,
}
);
});
clientV5.off('message', message_listener);
await clientV5.unsubscribeAsync('SimpleRecord/#');
});
it('subscribe to wildcards we do not support', async function () {
await assert.rejects(clientV5.subscribeAsync('SimpleRecord/+test'), /Invalid topic/);
const granted = await subscribeAllowingSubackError(clientV5, '+/SimpleRecord/test');
assert.equal(granted[0].qos, 0x8f); // assert that the subscription was rejected
});
it('subscribe with QoS=1 and reconnect with non-clean session', async function () {
this.timeout(20000); // needs more than the suite-level 10 s on loaded runners
// this first connection is a tear down to remove any previous durable session with this id
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client1',
protocolVersion: 4,
});
await client.endAsync();
await delay(10);
client = await connectAsync('mqtt://localhost:1883', {
clean: false,
clientId: 'test-client1',
protocolVersion: 4,
});
await client.subscribeAsync(['SimpleRecord/41', 'SimpleRecord/42'], { qos: 1 });
await client.endAsync();
await delay(10);
client = await connectAsync('mqtt://localhost:1883', {
clean: false,
clientId: 'test-client1',
protocolVersion: 4,
});
await new Promise((resolve) => {
client.on('message', (topic, payload) => {
JSON.parse(payload);
resolve();
});
client.publish(
'SimpleRecord/41',
JSON.stringify({
name: 'This is a test of durable session with subscriptions restarting',
}),
{
qos: 1,
}
);
});
await delay(10);
await client.endAsync();
await delay(50);
clientV5.publish(
'SimpleRecord/41',
JSON.stringify({
name: 'This is a test of publishing to a disconnected durable session',
}),
{
qos: 1,
}
);
await clientV5.publishAsync(
'SimpleRecord/42',
JSON.stringify({
name: 'This is a test of publishing to a disconnected durable session 2',
}),
{
qos: 1,
}
);
await clientV5.publishAsync(
'SimpleRecord/42',
JSON.stringify({
name: 'This is a test of publishing to a disconnected durable session 3',
}),
{
qos: 1,
}
);
await delay(10);
let messages = [];
client = await connectWithMessageListener(
'mqtt://localhost:1883',
{
clean: false,
clientId: 'test-client1',
protocolVersion: 5,
properties: {
sessionExpiryInterval: 3600,
},
},
(topic, message) => {
messages.push(message.toString());
}
);
await new Promise((resolve, reject) => {
const interval = setInterval(() => {
if (messages.length === 3) {
clearInterval(interval);
resolve();
}
}, 1);
setTimeout(() => {
clearInterval(interval);
reject(
new Error(`Expected 3 queued messages to be delivered to reconnected durable session, got ${messages.length}`)
);
}, 15000);
});
await delay(50);
await client.endAsync();
if (messages.length !== 3) console.error('Incorrect messages', { messages });
assert(messages.length === 3);
});
it('subscribe with QoS=2', async function () {
// this first connection is a tear down to remove any previous durable session with this id
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client1',
protocolVersion: 4,
});
await client.end();
await delay(10);
client = await connectAsync('mqtt://localhost:1883', {
clean: false,
clientId: 'test-client1',
protocolVersion: 4,
});
await client.subscribeAsync('SimpleRecord/41', { qos: 2 });
await new Promise((resolve) => {
client.on('message', (topic, payload) => {
JSON.parse(payload);
resolve();
});
client.publish(
'SimpleRecord/41',
JSON.stringify({
name: 'This is a test of a message with qos 2',
}),
{
qos: 2,
}
);
});
client.end();
});
it('connection events', async function () {
let events_received = [];
server.mqtt.events.on('connection', (_a1, _a2) => {
events_received.push('connection');
});
server.mqtt.events.on('connected', (_a1, _a2) => {
events_received.push('connected');
});
server.mqtt.events.on('disconnected', (_a1, _a2) => {
events_received.push('disconnected');
});
server.mqtt.events.on('error', (_a1, _a2) => {
events_received.push('error');
});
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client1',
protocolVersion: 4,
});
await subscribeAllowingSubackError(client, 'this does not exist', { qos: 1 });
client.end();
await new Promise((resolve) => {
setTimeout(resolve, 20);
});
assert(events_received.includes('connection'));
assert(events_received.includes('connected'));
assert(events_received.includes('disconnected'));
assert(events_received.includes('error'));
});
it('subscribe root with history', async function () {
// this first connection is a tear down to remove any previous durable session with this id
let client = await connectAsync('mqtt://localhost:1883', {
clean: true,
clientId: 'test-client1',
protocolVersion: 4,
});
let messages = [];
client.on('message', (topic, payload) => {
messages.push(topic, payload.length > 0 ? JSON.parse(payload) : 'deleted');
});
await client.subscribeAsync('FourPropWithHistory/#', { qos: 1 });
await delay(300);
const { FourPropWithHistory } = await import('../testApp/resources.js');
assert.equal(messages.length, 20);
assert.equal(FourPropWithHistory.acknowledgements, 10);