amqplib 0.10.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.claude/commands/lint-disable.md +9 -0
  2. package/.claude/commands/lint-enable.md +12 -0
  3. package/.claude/settings.local.json +16 -0
  4. package/.github/workflows/publish.yml +1 -1
  5. package/.github/workflows/test.yml +1 -1
  6. package/CHANGELOG.md +34 -0
  7. package/CLAUDE.md +12 -0
  8. package/Makefile +5 -12
  9. package/bin/generate-defs.js +382 -369
  10. package/biome.json +51 -0
  11. package/callback_api.js +12 -8
  12. package/channel_api.js +5 -10
  13. package/examples/direct_reply_to_client.js +9 -5
  14. package/examples/direct_reply_to_server.js +8 -6
  15. package/examples/headers.js +13 -10
  16. package/examples/receive_generator.js +13 -20
  17. package/examples/send_generators.js +2 -9
  18. package/examples/ssl.js +2 -3
  19. package/examples/stream_queues/receive_stream.js +39 -36
  20. package/examples/stream_queues/send_stream.js +26 -29
  21. package/examples/tutorials/callback_api/emit_log.js +4 -3
  22. package/examples/tutorials/callback_api/emit_log_direct.js +5 -4
  23. package/examples/tutorials/callback_api/emit_log_topic.js +5 -4
  24. package/examples/tutorials/callback_api/new_task.js +5 -4
  25. package/examples/tutorials/callback_api/receive.js +16 -10
  26. package/examples/tutorials/callback_api/receive_logs.js +17 -11
  27. package/examples/tutorials/callback_api/receive_logs_direct.js +19 -13
  28. package/examples/tutorials/callback_api/receive_logs_topic.js +19 -14
  29. package/examples/tutorials/callback_api/rpc_client.js +20 -16
  30. package/examples/tutorials/callback_api/rpc_server.js +27 -21
  31. package/examples/tutorials/callback_api/send.js +4 -3
  32. package/examples/tutorials/callback_api/worker.js +18 -13
  33. package/examples/tutorials/emit_log.js +4 -6
  34. package/examples/tutorials/emit_log_direct.js +5 -7
  35. package/examples/tutorials/emit_log_topic.js +5 -7
  36. package/examples/tutorials/new_task.js +4 -6
  37. package/examples/tutorials/receive.js +8 -4
  38. package/examples/tutorials/receive_logs.js +10 -6
  39. package/examples/tutorials/receive_logs_direct.js +16 -10
  40. package/examples/tutorials/receive_logs_topic.js +16 -11
  41. package/examples/tutorials/rpc_client.js +17 -15
  42. package/examples/tutorials/rpc_server.js +9 -8
  43. package/examples/tutorials/send.js +4 -6
  44. package/examples/tutorials/worker.js +17 -14
  45. package/examples/waitForConfirms.js +2 -2
  46. package/lefthook.yml +14 -0
  47. package/lib/api_args.js +124 -149
  48. package/lib/bitset.js +28 -18
  49. package/lib/callback_model.js +134 -190
  50. package/lib/channel.js +175 -213
  51. package/lib/channel_model.js +41 -85
  52. package/lib/codec.js +257 -228
  53. package/lib/connect.js +74 -82
  54. package/lib/connection.js +204 -240
  55. package/lib/credentials.js +21 -29
  56. package/lib/defs.js +2559 -1927
  57. package/lib/error.js +5 -6
  58. package/lib/format.js +15 -33
  59. package/lib/frame.js +66 -66
  60. package/lib/heartbeat.js +17 -24
  61. package/lib/mux.js +32 -41
  62. package/package.json +8 -5
  63. package/test/bitset.test.js +65 -0
  64. package/test/callback_api.test.js +438 -0
  65. package/test/channel.test.js +592 -0
  66. package/test/channel_api.test.js +537 -0
  67. package/test/codec.test.js +172 -0
  68. package/test/connect.test.js +196 -0
  69. package/test/connection.test.js +330 -0
  70. package/test/data.test.js +33 -0
  71. package/test/frame.test.js +180 -0
  72. package/test/lib/data.js +249 -0
  73. package/test/lib/util.js +223 -0
  74. package/test/mux.test.js +215 -0
  75. package/test/bitset.js +0 -69
  76. package/test/callback_api.js +0 -379
  77. package/test/channel.js +0 -621
  78. package/test/channel_api.js +0 -606
  79. package/test/codec.js +0 -237
  80. package/test/connect.js +0 -197
  81. package/test/connection.js +0 -390
  82. package/test/data.js +0 -269
  83. package/test/frame.js +0 -191
  84. package/test/mux.js +0 -203
  85. package/test/util.js +0 -217
@@ -0,0 +1,172 @@
1
+ const { describe, it } = require('node:test');
2
+ const assert = require('node:assert');
3
+ const ints = require('buffer-more-ints');
4
+ const { forAll } = require('claire');
5
+ const codec = require('../lib/codec');
6
+ const defs = require('../lib/defs');
7
+ const amqp = require('./lib/data');
8
+ const { removeExplicitTypes, assertEqualModuloDefaults } = require('./lib/util');
9
+
10
+ // These just test known encodings; to generate the answers I used RabbitMQ's binary generator module.
11
+ const testCases = [
12
+ // integers
13
+ ['byte', { byte: 112 }, [4, 98, 121, 116, 101, 98, 112]],
14
+ ['byte max value', { byte: 127 }, [4, 98, 121, 116, 101, 98, 127]],
15
+ ['byte min value', { byte: -128 }, [4, 98, 121, 116, 101, 98, 128]],
16
+ ['< -128 promoted to signed short', { short: -129 }, [5, 115, 104, 111, 114, 116, 115, 255, 127]],
17
+ ['> 127 promoted to short', { short: 128 }, [5, 115, 104, 111, 114, 116, 115, 0, 128]],
18
+ ['< 2^15 still a short', { short: 0x7fff }, [5, 115, 104, 111, 114, 116, 115, 127, 255]],
19
+ ['-2^15 still a short', { short: -0x8000 }, [5, 115, 104, 111, 114, 116, 115, 128, 0]],
20
+ ['>= 2^15 promoted to int', { int: 0x8000 }, [3, 105, 110, 116, 73, 0, 0, 128, 0]],
21
+ ['< -2^15 promoted to int', { int: -0x8001 }, [3, 105, 110, 116, 73, 255, 255, 127, 255]],
22
+ ['< 2^31 still an int', { int: 0x7fffffff }, [3, 105, 110, 116, 73, 127, 255, 255, 255]],
23
+ ['>= -2^31 still an int', { int: -0x80000000 }, [3, 105, 110, 116, 73, 128, 0, 0, 0]],
24
+ ['>= 2^31 promoted to long', { long: 0x80000000 }, [4, 108, 111, 110, 103, 108, 0, 0, 0, 0, 128, 0, 0, 0]],
25
+ ['< -2^31 promoted to long', { long: -0x80000001 }, [4, 108, 111, 110, 103, 108, 255, 255, 255, 255, 127, 255, 255, 255]],
26
+
27
+ // floating point
28
+ ['float value', { double: 0.5 }, [6, 100, 111, 117, 98, 108, 101, 100, 63, 224, 0, 0, 0, 0, 0, 0]],
29
+ ['negative float value', { double: -0.5 }, [6, 100, 111, 117, 98, 108, 101, 100, 191, 224, 0, 0, 0, 0, 0, 0]],
30
+ // %% test some boundaries of precision?
31
+
32
+ // string
33
+ ['string', { string: 'boop' }, [6, 115, 116, 114, 105, 110, 103, 83, 0, 0, 0, 4, 98, 111, 111, 112]],
34
+
35
+ // buffer -> byte array
36
+ ['byte array from buffer', { bytes: Buffer.from([1, 2, 3, 4]) }, [5, 98, 121, 116, 101, 115, 120, 0, 0, 0, 4, 1, 2, 3, 4]],
37
+
38
+ // boolean, void
39
+ ['true', { bool: true }, [4, 98, 111, 111, 108, 116, 1]],
40
+ ['false', { bool: false }, [4, 98, 111, 111, 108, 116, 0]],
41
+ ['null', { void: null }, [4, 118, 111, 105, 100, 86]],
42
+
43
+ // array, object
44
+ ['array', { array: [6, true, 'foo'] }, [5, 97, 114, 114, 97, 121, 65, 0, 0, 0, 12, 98, 6, 116, 1, 83, 0, 0, 0, 3, 102, 111, 111]],
45
+ [
46
+ 'object',
47
+ { object: { foo: 'bar', baz: 12 } },
48
+ [6, 111, 98, 106, 101, 99, 116, 70, 0, 0, 0, 18, 3, 102, 111, 111, 83, 0, 0, 0, 3, 98, 97, 114, 3, 98, 97, 122, 98, 12],
49
+ ],
50
+
51
+ // exotic types
52
+ [
53
+ 'timestamp',
54
+ { timestamp: { '!': 'timestamp', value: 1357212277527 } },
55
+ [9, 116, 105, 109, 101, 115, 116, 97, 109, 112, 84, 0, 0, 1, 60, 0, 39, 219, 23],
56
+ ],
57
+ [
58
+ 'decimal',
59
+ { decimal: { '!': 'decimal', value: { digits: 2345, places: 2 } } },
60
+ [7, 100, 101, 99, 105, 109, 97, 108, 68, 2, 0, 0, 9, 41],
61
+ ],
62
+ ['float', { float: { '!': 'float', value: 0.1 } }, [5, 102, 108, 111, 97, 116, 102, 61, 204, 204, 205]],
63
+ [
64
+ 'unsignedbyte',
65
+ { unsignedbyte: { '!': 'unsignedbyte', value: 255 } },
66
+ [12, 117, 110, 115, 105, 103, 110, 101, 100, 98, 121, 116, 101, 66, 255],
67
+ ],
68
+ [
69
+ 'unsignedshort',
70
+ { unsignedshort: { '!': 'unsignedshort', value: 65535 } },
71
+ [13, 117, 110, 115, 105, 103, 110, 101, 100, 115, 104, 111, 114, 116, 117, 255, 255],
72
+ ],
73
+ [
74
+ 'unsignedint',
75
+ { unsignedint: { '!': 'unsignedint', value: 4294967295 } },
76
+ [11, 117, 110, 115, 105, 103, 110, 101, 100, 105, 110, 116, 105, 255, 255, 255, 255],
77
+ ],
78
+ ];
79
+
80
+ function bufferToArray(b) {
81
+ return Array.prototype.slice.call(b);
82
+ }
83
+
84
+ describe('Codec', () => {
85
+
86
+ describe('Implicit encodings', () => {
87
+ testCases.forEach(([name, val, expect]) => {
88
+ it(name, () => {
89
+ const buffer = Buffer.alloc(1000);
90
+ const size = codec.encodeTable(buffer, val, 0);
91
+ const result = buffer.subarray(4, size);
92
+ assert.deepEqual(expect, bufferToArray(result));
93
+ });
94
+ });
95
+ });
96
+
97
+ // Whole frames
98
+ function roundtrip_table(t) {
99
+ const buf = Buffer.alloc(4096);
100
+ const size = codec.encodeTable(buf, t, 0);
101
+ const decoded = codec.decodeFields(buf.subarray(4, size)); // ignore the length-prefix
102
+ try {
103
+ assert.deepEqual(removeExplicitTypes(t), decoded);
104
+ } catch {
105
+ return false;
106
+ }
107
+ return true;
108
+ }
109
+
110
+ function roundtrips(T) {
111
+ return forAll(T).satisfy((v) => roundtrip_table({ value: v }));
112
+ }
113
+
114
+ describe('Roundtrip values', () => {
115
+ [
116
+ amqp.Octet,
117
+ amqp.ShortStr,
118
+ amqp.LongStr,
119
+ amqp.UShort,
120
+ amqp.ULong,
121
+ amqp.ULongLong,
122
+ amqp.UShort,
123
+ amqp.Short,
124
+ amqp.Long,
125
+ amqp.Bit,
126
+ amqp.Decimal,
127
+ amqp.Timestamp,
128
+ amqp.UnsignedByte,
129
+ amqp.UnsignedShort,
130
+ amqp.UnsignedInt,
131
+ amqp.Double,
132
+ amqp.Float,
133
+ amqp.FieldArray,
134
+ amqp.FieldTable,
135
+ ].forEach((T) => {
136
+ it(`${T.toString()} roundtrip`, roundtrips(T).asTest());
137
+ });
138
+ });
139
+
140
+ function roundtripMethod(Method) {
141
+ return forAll(Method).satisfy((method) => {
142
+ const buf = defs.encodeMethod(method.id, 0, method.fields);
143
+ // FIXME depends on framing, ugh
144
+ const fs1 = defs.decode(method.id, buf.subarray(11, buf.length));
145
+ assertEqualModuloDefaults(method, fs1);
146
+ return true;
147
+ });
148
+ }
149
+
150
+ function roundtripProperties(Properties) {
151
+ return forAll(Properties).satisfy((properties) => {
152
+ const buf = defs.encodeProperties(properties.id, 0, properties.size, properties.fields);
153
+ // FIXME depends on framing, ugh
154
+ const fs1 = defs.decode(properties.id, buf.subarray(19, buf.length));
155
+ assert.equal(properties.size, ints.readUInt64BE(buf, 11));
156
+ assertEqualModuloDefaults(properties, fs1);
157
+ return true;
158
+ });
159
+ }
160
+
161
+ describe('Roundtrip methods', () => {
162
+ amqp.methods.forEach((Method) => {
163
+ it(`${Method.toString()} roundtrip`, roundtripMethod(Method).asTest());
164
+ });
165
+ });
166
+
167
+ describe('Roundtrip properties', () => {
168
+ amqp.properties.forEach((Properties) => {
169
+ it(`${Properties.toString()} roundtrip`, roundtripProperties(Properties).asTest());
170
+ });
171
+ });
172
+ });
@@ -0,0 +1,196 @@
1
+ const { describe, it, afterEach } = require('node:test');
2
+ const assert = require('node:assert');
3
+ const net = require('node:net');
4
+ const connect = require('../lib/connect').connect;
5
+ const credentialsFromUrl = require('../lib/connect').credentialsFromUrl;
6
+ const defs = require('../lib/defs');
7
+ const { plain, amqplain } = require('../lib/credentials')
8
+ const { latch, runServer } = require('./lib/util');
9
+
10
+ const urlparse = require('url-parse');
11
+
12
+ describe('Connect', () => {
13
+
14
+ describe('Credentials', () => {
15
+ function assertCredentials(creds, username, password) {
16
+ assert.strictEqual(creds.mechanism, 'PLAIN');
17
+ assert.strictEqual(creds.username, username);
18
+ assert.strictEqual(creds.password, password);
19
+ }
20
+
21
+ it('no creds', () => {
22
+ const parts = urlparse('amqp://localhost');
23
+ const creds = credentialsFromUrl(parts);
24
+ assertCredentials(creds, 'guest', 'guest');
25
+ });
26
+
27
+ it('usual user:pass', () => {
28
+ const parts = urlparse('amqp://user:pass@localhost');
29
+ const creds = credentialsFromUrl(parts);
30
+ assertCredentials(creds, 'user', 'pass');
31
+ });
32
+
33
+ it('missing user', () => {
34
+ const parts = urlparse('amqps://:password@localhost');
35
+ const creds = credentialsFromUrl(parts);
36
+ assertCredentials(creds, '', 'password');
37
+ });
38
+
39
+ it('missing password', () => {
40
+ const parts = urlparse('amqps://username:@localhost');
41
+ const creds = credentialsFromUrl(parts);
42
+ assertCredentials(creds, 'username', '');
43
+ });
44
+
45
+ it('escaped colons', () => {
46
+ const parts = urlparse('amqp://user%3Aname:pass%3Aword@localhost');
47
+ const creds = credentialsFromUrl(parts);
48
+ assertCredentials(creds, 'user:name', 'pass:word');
49
+ });
50
+ });
51
+
52
+ describe('Connect API', () => {
53
+
54
+ let connection;
55
+
56
+ afterEach((_t, done) => {
57
+ if (connection) connection.close(() => done())
58
+ else done();
59
+ });
60
+
61
+ it('Connection refused', (_t, done) => {
62
+ connect('amqp://localhost:23450', {}, (err) => {
63
+ assert.strictEqual(err.code, 'ECONNREFUSED');
64
+ done();
65
+ });
66
+ });
67
+
68
+ // %% this ought to fail the promise, rather than throwing an error
69
+ it('bad URL', (_t, done) => {
70
+ assert.throws(() => connect('blurble'), (err) => {
71
+ assert.match(err.message, /Expected amqp: or amqps: as the protocol/);
72
+ return true;
73
+ });
74
+ done();
75
+ });
76
+
77
+ it('wrongly typed open option', (_t, done) => {
78
+ connect('amqp://localhost?frameMax=NOT_A_NUMBER', {}, (err) => {
79
+ assert.match(err.message, /Field 'frameMax' is the wrong type/);
80
+ done();
81
+ });
82
+ });
83
+
84
+ it('serverProperties', (_t, done) => {
85
+ connect({ protocol: 'amqp', hostname: 'localhost' }, {}, (err, _connection) => {
86
+ connection = _connection;
87
+ assert.ifError(err);
88
+ assert.equal(connection.serverProperties.product, 'RabbitMQ');
89
+ done();
90
+ });
91
+ });
92
+
93
+ it('using custom heartbeat option', (_t, done) => {
94
+ connect({ heartbeat: 20 }, {}, (err, _connection) => {
95
+ assert.ifError(err);
96
+ connection = _connection;
97
+ assert.strictEqual(connection.heartbeat, 20);
98
+ done();
99
+ });
100
+ });
101
+
102
+ it('wrongly typed heartbeat option', (_t, done) => {
103
+ connect('amqp://localhost?heartbeat=NOT_A_NUMBER', {}, (err) => {
104
+ assert.match(err.message, /Field 'heartbeat' is the wrong type/);
105
+ done();
106
+ });
107
+ });
108
+
109
+ it('using plain credentials', (_t, done) => {
110
+ connect('amqp://localhost', { credentials: plain('guest', 'guest') }, (err, _connection) => {
111
+ assert.ifError(err);
112
+ connection = _connection;
113
+ done();
114
+ });
115
+ });
116
+
117
+ it('using amqplain credentials', (_t, done) => {
118
+ connect('amqp://localhost', { credentials: amqplain('guest', 'guest') }, (err, _connection) => {
119
+ assert.ifError(err);
120
+ connection = _connection;
121
+ done();
122
+ });
123
+ });
124
+
125
+ it('ipv6', (_t, done) => {
126
+ connect('amqp://[::1]', {}, (err, _connection) => {
127
+ assert.ifError(err);
128
+ connection = _connection;
129
+ done();
130
+ });
131
+ });
132
+
133
+ it('using unsupported mechanism', (_t, done) => {
134
+ const credentials = { mechanism: 'UNSUPPORTED', response: () => Buffer.from('') };
135
+ connect('amqp://localhost', { credentials }, (err) => {
136
+ assert.match(err.message, /SASL mechanism UNSUPPORTED is not provided by the server/);
137
+ done();
138
+ });
139
+ });
140
+
141
+ it('with a given connection timeout', (_t, done) => {
142
+ const timeoutServer = net.createServer(() => { }).listen(31991);
143
+
144
+ connect('amqp://localhost:31991', { timeout: 50 }, (err) => {
145
+ timeoutServer.close();
146
+ assert.match(err.message, /ETIMEDOUT/);
147
+ done();
148
+ });
149
+ });
150
+ });
151
+
152
+ describe('Errors on connect', () => {
153
+
154
+ let server;
155
+
156
+ afterEach(() => {
157
+ if (server) server.close();
158
+ });
159
+
160
+ it('closes underlying connection on authentication error', (_t, done) => {
161
+ const decrementLatch = latch(2, done);
162
+ server = net.createServer((socket) => {
163
+ socket.once('data', (protocolHeader) => {
164
+ assert.deepStrictEqual(protocolHeader, Buffer.from(`AMQP${String.fromCharCode(0, 0, 9, 1)}`));
165
+ runServer(socket, (send, wait) => {
166
+ send(defs.ConnectionStart, {
167
+ versionMajor: 0,
168
+ versionMinor: 9,
169
+ serverProperties: {},
170
+ mechanisms: Buffer.from('PLAIN'),
171
+ locales: Buffer.from('en_US'),
172
+ });
173
+ wait(defs.ConnectionStartOk)().then(() => {
174
+ send(defs.ConnectionClose, {
175
+ replyCode: 403,
176
+ replyText: 'ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN',
177
+ classId: 0,
178
+ methodId: 0,
179
+ });
180
+ });
181
+ });
182
+ });
183
+
184
+ // Wait for the connection to be closed after the authentication error
185
+ socket.once('end', () => decrementLatch());
186
+ });
187
+ server.listen(0);
188
+
189
+ connect(`amqp://localhost:${server.address().port}`, {}, (err) => {
190
+ assert.match(err.message, /Handshake terminated by server: 403 \(ACCESS-REFUSED\)/);
191
+ decrementLatch();
192
+ });
193
+ });
194
+ });
195
+
196
+ });
@@ -0,0 +1,330 @@
1
+ const { describe, it, beforeEach, afterEach } = require('node:test');
2
+ const assert = require('node:assert');
3
+ const defs = require('../lib/defs');
4
+ const Connection = require('../lib/connection').Connection;
5
+ const HEARTBEAT = require('../lib/frame').HEARTBEAT;
6
+ const HB_BUF = require('../lib/frame').HEARTBEAT_BUF;
7
+ const OPEN_OPTS = require('./lib/data').OPEN_OPTS;
8
+ const heartbeat = require('../lib/heartbeat');
9
+ const { latch, handshake, runServer, socketPair } = require('./lib/util');
10
+
11
+ const LOG_ERRORS = process.env.LOG_ERRORS;
12
+
13
+ function connectionTest(client, server) {
14
+ return (_t, done) => {
15
+ const decrementLatch = latch(2, done);
16
+ const pair = socketPair();
17
+ const c = new Connection(pair.client);
18
+ if (LOG_ERRORS) c.on('error', console.warn);
19
+ client(c, decrementLatch);
20
+
21
+ // NB only not a race here because the writes are synchronous
22
+ const protocolHeader = pair.server.read(8);
23
+ assert.deepEqual(Buffer.from(`AMQP${String.fromCharCode(0, 0, 9, 1)}`), protocolHeader);
24
+
25
+ runServer(pair.server, (send, wait) => {
26
+ server(send, wait, decrementLatch, pair.server);
27
+ });
28
+ };
29
+ }
30
+
31
+ describe('Connection', () => {
32
+
33
+ describe('Connection errors', () => {
34
+ it('socket close during open', (_t, done) => {
35
+ // RabbitMQ itself will take at least 3 seconds to close the socket
36
+ // in the event of a handshake problem. Instead of using a live
37
+ // connection, I'm just going to pretend.
38
+ const pair = socketPair();
39
+ const conn = new Connection(pair.client);
40
+ pair.server.on('readable', () => pair.server.end());
41
+ conn.open({}, (err) => {
42
+ assert.ok(err);
43
+ assert.match(err.message, /Socket closed abruptly during opening handshake/);
44
+ done();
45
+ });
46
+ });
47
+
48
+ it('bad frame during open', (_t, done) => {
49
+ const ss = socketPair();
50
+ const conn = new (require('../lib/connection').Connection)(ss.client);
51
+ ss.server.on('readable', () => {
52
+ ss.server.write(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
53
+ });
54
+ conn.open({}, (err) => {
55
+ assert.ok(err);
56
+ assert.match(err.message, /Invalid frame/);
57
+ done();
58
+ });
59
+ });
60
+ });
61
+
62
+ describe('Connection open', () => {
63
+ it('happy', connectionTest((c, cb) => {
64
+ c.open(OPEN_OPTS, (err) => {
65
+ assert.ifError(err);
66
+ cb();
67
+ })
68
+ }, (send, wait, cb) => {
69
+ handshake(send, wait)
70
+ .then(cb, cb);
71
+ }));
72
+
73
+ it('wrong first frame', connectionTest((c, cb) => {
74
+ c.open(OPEN_OPTS, (err) => {
75
+ assert.ok(err);
76
+ assert.match(err.message, /Expected ConnectionStart; got <ConnectionTune channel:0/);
77
+ cb()
78
+ });
79
+ }, (send, _wait, cb) => {
80
+ // bad server! bad! whatever were you thinking?
81
+ send(defs.ConnectionTune, { channelMax: 0, heartbeat: 0, frameMax: 0 })
82
+ cb();
83
+ }));
84
+
85
+ it('unexpected socket close', connectionTest((c, cb) => {
86
+ c.open(OPEN_OPTS, (err) => {
87
+ assert.ok(err);
88
+ assert.match(err.message, /Socket closed abruptly during opening handshake/);
89
+ cb();
90
+ });
91
+ }, (send, wait, cb, socket) => {
92
+ send(defs.ConnectionStart, {
93
+ versionMajor: 0,
94
+ versionMinor: 9,
95
+ serverProperties: {},
96
+ mechanisms: Buffer.from('PLAIN'),
97
+ locales: Buffer.from('en_US'),
98
+ });
99
+ return wait(defs.ConnectionStartOk)()
100
+ .then(() => socket.end())
101
+ .then(cb, cb);
102
+ }));
103
+ });
104
+
105
+ describe('Connection running', () => {
106
+ it('wrong frame on channel 0', connectionTest((c, cb) => {
107
+ c.once('error', (err) => {
108
+ assert.match(err.message, /Unexpected frame on channel 0/);
109
+ cb()
110
+ });
111
+ c.open(OPEN_OPTS);
112
+ }, (send, wait, cb) => {
113
+ handshake(send, wait)
114
+ // there's actually nothing that would plausibly be sent to a
115
+ // just opened connection, so this is violating more than one
116
+ // rule. Nonetheless.
117
+ .then(() => send(defs.ChannelOpenOk, { channelId: Buffer.from('') }, 0))
118
+ .then(wait(defs.ConnectionClose))
119
+ .then((_close) => send(defs.ConnectionCloseOk, {}, 0))
120
+ .then(cb, cb);
121
+ }));
122
+
123
+ it('unopened channel', connectionTest((c, cb) => {
124
+ c.once('error', (err) => {
125
+ assert.match(err.message, /Frame on unknown channel/);
126
+ cb();
127
+ });
128
+ c.open(OPEN_OPTS);
129
+ }, (send, wait, cb) => {
130
+ handshake(send, wait)
131
+ // there's actually nothing that would plausibly be sent to a
132
+ // just opened connection, so this is violating more than one
133
+ // rule. Nonetheless.
134
+ .then(() => send(defs.ChannelOpenOk, { channelId: Buffer.from('') }, 3))
135
+ .then(wait(defs.ConnectionClose))
136
+ .then((_close) => send(defs.ConnectionCloseOk, {}, 0))
137
+ .then(cb, cb);
138
+ }));
139
+
140
+ it('unexpected socket close', connectionTest((c, cb) => {
141
+ const decrementLatch = latch(2, cb);
142
+ c.on('error', (err) => {
143
+ assert.match(err.message, /Unexpected close/);
144
+ decrementLatch();
145
+ });
146
+ c.on('close', (err) => {
147
+ assert.match(err.message, /Unexpected close/);
148
+ decrementLatch();
149
+ });
150
+ c.open(OPEN_OPTS, (err) => {
151
+ assert.ifError(err);
152
+ c.sendHeartbeat();
153
+ });
154
+ }, (send, wait, cb, socket) => {
155
+ handshake(send, wait)
156
+ .then(wait())
157
+ .then(() => socket.end())
158
+ .then(cb, cb);
159
+ }));
160
+
161
+ it('connection.blocked', connectionTest((c, cb) => {
162
+ c.on('blocked', (reason) => {
163
+ assert.strictEqual(reason, 'felt like it');
164
+ cb();
165
+ });
166
+ c.open(OPEN_OPTS);
167
+ }, (send, wait, cb, _socket) => {
168
+ handshake(send, wait)
169
+ .then(() => send(defs.ConnectionBlocked, { reason: 'felt like it' }, 0))
170
+ .then(cb, cb);
171
+ }));
172
+
173
+ it('connection.unblocked', connectionTest((c, cb) => {
174
+ c.on('unblocked', () => cb());
175
+ c.open(OPEN_OPTS);
176
+ }, (send, wait, cb, _socket) => {
177
+ handshake(send, wait)
178
+ .then(() => send(defs.ConnectionUnblocked, {}, 0))
179
+ .then(cb, cb);
180
+ }));
181
+ });
182
+
183
+ describe('Connection close', () => {
184
+ it('happy', connectionTest((c, cb) => {
185
+ const decrementLatch = latch(2, cb);
186
+ c.on('close', () => decrementLatch());
187
+ c.open(OPEN_OPTS, (err) => {
188
+ assert.ifError(err);
189
+ c.close((err) => {
190
+ assert.ifError(err);
191
+ decrementLatch();
192
+ });
193
+ });
194
+ }, (send, wait, cb) => {
195
+ handshake(send, wait)
196
+ .then(wait(defs.ConnectionClose))
197
+ .then((_close) => send(defs.ConnectionCloseOk, {}))
198
+ .then(cb, cb);
199
+ }));
200
+
201
+ it('interleaved close frames', connectionTest((c, cb) => {
202
+ const decrementLatch = latch(2, cb);
203
+ c.on('close', () => decrementLatch());
204
+ c.open(OPEN_OPTS, (err) => {
205
+ assert.ifError(err);
206
+ c.close((err) => {
207
+ assert.ifError(err);
208
+ decrementLatch();
209
+ });
210
+ });
211
+ }, (send, wait, cb) => {
212
+ handshake(send, wait)
213
+ .then(wait(defs.ConnectionClose))
214
+ .then(() => send(defs.ConnectionClose, {
215
+ replyText: 'Ha!',
216
+ replyCode: defs.constants.REPLY_SUCCESS,
217
+ methodId: 0,
218
+ classId: 0,
219
+ }))
220
+ .then(wait(defs.ConnectionCloseOk))
221
+ .then(() => send(defs.ConnectionCloseOk, {}))
222
+ .then(cb, cb);
223
+ }));
224
+
225
+ it('server error close', connectionTest((c, cb) => {
226
+ const decrementLatch = latch(2, cb);
227
+ c.once('close', (err) => {
228
+ assert.match(err.message, /Connection closed: 541 \(INTERNAL-ERROR\) with message "Begone"/);
229
+ decrementLatch();
230
+ });
231
+ c.once('error', (err) => {
232
+ assert.match(err.message, /Connection closed: 541 \(INTERNAL-ERROR\) with message "Begone"/);
233
+ decrementLatch();
234
+ });
235
+ c.open(OPEN_OPTS);
236
+ }, (send, wait, cb) => {
237
+ handshake(send, wait)
238
+ .then(() => send(defs.ConnectionClose, {
239
+ replyText: 'Begone',
240
+ replyCode: defs.constants.INTERNAL_ERROR,
241
+ methodId: 0,
242
+ classId: 0,
243
+ }))
244
+ .then(wait(defs.ConnectionCloseOk))
245
+ .then(cb, cb);
246
+ }));
247
+
248
+ it('operator-intiated close', connectionTest((c, cb) => {
249
+ c.once('close', (err) => {
250
+ assert.match(err.message, /Connection closed: 320 \(CONNECTION-FORCED\) with message "Begone"/);
251
+ cb();
252
+ });
253
+ c.once('error', (err) => assert.fail(`Unexepcted error: ${err.message}`));
254
+ c.open(OPEN_OPTS);
255
+ }, (send, wait, cb) => {
256
+ handshake(send, wait)
257
+ .then(() => send(defs.ConnectionClose, {
258
+ replyText: 'Begone',
259
+ replyCode: defs.constants.CONNECTION_FORCED,
260
+ methodId: 0,
261
+ classId: 0,
262
+ }))
263
+ .then(wait(defs.ConnectionCloseOk))
264
+ .then(cb, cb);
265
+ }));
266
+
267
+ it('double close', connectionTest((c, cb) => {
268
+ c.open(OPEN_OPTS, (err) => {
269
+ assert.ifError(err);
270
+ c.close();
271
+ // NB no synchronisation, we do this straight away
272
+ assert.throws(() => c.close());
273
+ cb();
274
+ });
275
+ }, (send, wait, cb) => {
276
+ handshake(send, wait)
277
+ .then(wait(defs.ConnectionClose))
278
+ .then(() => send(defs.ConnectionCloseOk, {}))
279
+ .then(cb, cb);
280
+ }));
281
+ });
282
+
283
+ describe('heartbeats', () => {
284
+
285
+ beforeEach(() => {
286
+ heartbeat.UNITS_TO_MS = 20;
287
+ });
288
+
289
+ afterEach(() => {
290
+ heartbeat.UNITS_TO_MS = 1000;
291
+ });
292
+
293
+ it('send heartbeat after open', connectionTest((c, cb) => {
294
+ const opts = Object.create(OPEN_OPTS);
295
+ opts.heartbeat = 1;
296
+ // Don't leave the error waiting to happen for the next test
297
+ c.on('error', (err) => {
298
+ assert.match(err.message, /Heartbeat timeout/)
299
+ });
300
+ c.open(opts);
301
+ cb()
302
+ }, (send, wait, cb, socket) => {
303
+ let timer;
304
+ handshake(send, wait)
305
+ .then(() => {
306
+ timer = setInterval(() => socket.write(HB_BUF), heartbeat.UNITS_TO_MS);
307
+ })
308
+ .then(wait())
309
+ .then((hb) => {
310
+ assert.strictEqual(hb, HEARTBEAT);
311
+ cb();
312
+ }).finally(() => clearInterval(timer));
313
+ }));
314
+
315
+ it('detect lack of heartbeats', connectionTest((c, cb) => {
316
+ const opts = Object.create(OPEN_OPTS);
317
+ opts.heartbeat = 1;
318
+ c.once('error', (err) => {
319
+ assert.match(err.message, /Heartbeat timeout/)
320
+ cb();
321
+ });
322
+ c.open(opts);
323
+ }, (send, wait, cb, _socket) => {
324
+ handshake(send, wait)
325
+ .then(cb, cb);
326
+ // conspicuously not sending anything ...
327
+ }));
328
+ });
329
+
330
+ });