connection.js
20.7 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
'use strict';
const EventEmitter = require('events').EventEmitter;
const crypto = require('crypto');
const debugOptions = require('./utils').debugOptions;
const parseHeader = require('../wireprotocol/shared').parseHeader;
const decompress = require('../wireprotocol/compression').decompress;
const Response = require('./commands').Response;
const BinMsg = require('./msg').BinMsg;
const MongoNetworkError = require('../error').MongoNetworkError;
const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;
const MongoError = require('../error').MongoError;
const Logger = require('./logger');
const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED;
const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG;
const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;
const Buffer = require('safe-buffer').Buffer;
const Query = require('./commands').Query;
const CommandResult = require('./command_result');
let _id = 0;
const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4;
const DEBUG_FIELDS = [
'host',
'port',
'size',
'keepAlive',
'keepAliveInitialDelay',
'noDelay',
'connectionTimeout',
'socketTimeout',
'ssl',
'ca',
'crl',
'cert',
'rejectUnauthorized',
'promoteLongs',
'promoteValues',
'promoteBuffers',
'checkServerIdentity'
];
let connectionAccountingSpy = undefined;
let connectionAccounting = false;
let connections = {};
/**
* A class representing a single connection to a MongoDB server
*
* @fires Connection#connect
* @fires Connection#close
* @fires Connection#error
* @fires Connection#timeout
* @fires Connection#parseError
* @fires Connection#message
*/
class Connection extends EventEmitter {
/**
* Creates a new Connection instance
*
* **NOTE**: Internal class, do not instantiate directly
*
* @param {Socket} socket The socket this connection wraps
* @param {Object} options Various settings
* @param {object} options.bson An implementation of bson serialize and deserialize
* @param {string} [options.host='localhost'] The host the socket is connected to
* @param {number} [options.port=27017] The port used for the socket connection
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
* @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled
* @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
* @param {number} [options.socketTimeout=0] TCP Socket timeout setting
* @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits
* @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers.
* @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes)
*/
constructor(socket, options) {
super();
options = options || {};
if (!options.bson) {
throw new TypeError('must pass in valid bson parser');
}
this.id = _id++;
this.options = options;
this.logger = Logger('Connection', options);
this.bson = options.bson;
this.tag = options.tag;
this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE;
this.port = options.port || 27017;
this.host = options.host || 'localhost';
this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 0;
// These values are inspected directly in tests, but maybe not necessary to keep around
this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;
this.keepAliveInitialDelay =
typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000;
this.connectionTimeout =
typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000;
if (this.keepAliveInitialDelay > this.socketTimeout) {
this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2);
}
// Debug information
if (this.logger.isDebug()) {
this.logger.debug(
`creating connection ${this.id} with options [${JSON.stringify(
debugOptions(DEBUG_FIELDS, options)
)}]`
);
}
// Response options
this.responseOptions = {
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false
};
// Flushing
this.flushing = false;
this.queue = [];
// Internal state
this.writeStream = null;
this.destroyed = false;
this.timedOut = false;
// Create hash method
const hash = crypto.createHash('sha1');
hash.update(this.address);
this.hashedName = hash.digest('hex');
// All operations in flight on the connection
this.workItems = [];
// setup socket
this.socket = socket;
this.socket.once('error', errorHandler(this));
this.socket.once('timeout', timeoutHandler(this));
this.socket.once('close', closeHandler(this));
this.socket.on('data', dataHandler(this));
if (connectionAccounting) {
addConnection(this.id, this);
}
}
setSocketTimeout(value) {
if (this.socket) {
this.socket.setTimeout(value);
}
}
resetSocketTimeout() {
if (this.socket) {
this.socket.setTimeout(this.socketTimeout);
}
}
static enableConnectionAccounting(spy) {
if (spy) {
connectionAccountingSpy = spy;
}
connectionAccounting = true;
connections = {};
}
static disableConnectionAccounting() {
connectionAccounting = false;
connectionAccountingSpy = undefined;
}
static connections() {
return connections;
}
get address() {
return `${this.host}:${this.port}`;
}
/**
* Unref this connection
* @method
* @return {boolean}
*/
unref() {
if (this.socket == null) {
this.once('connect', () => this.socket.unref());
return;
}
this.socket.unref();
}
/**
* Flush all work Items on this connection
*
* @param {*} err The error to propagate to the flushed work items
*/
flush(err) {
while (this.workItems.length > 0) {
const workItem = this.workItems.shift();
if (workItem.cb) {
workItem.cb(err);
}
}
}
/**
* Destroy connection
* @method
*/
destroy(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = Object.assign({ force: false }, options);
if (connectionAccounting) {
deleteConnection(this.id);
}
if (this.socket == null) {
this.destroyed = true;
return;
}
if (options.force || this.timedOut) {
this.socket.destroy();
this.destroyed = true;
if (typeof callback === 'function') callback(null, null);
return;
}
this.socket.end(err => {
this.destroyed = true;
if (typeof callback === 'function') callback(err, null);
});
}
/**
* Write to connection
* @method
* @param {Command} command Command to write out need to implement toBin and toBinUnified
*/
write(buffer) {
// Debug Log
if (this.logger.isDebug()) {
if (!Array.isArray(buffer)) {
this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`);
} else {
for (let i = 0; i < buffer.length; i++)
this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`);
}
}
// Double check that the connection is not destroyed
if (this.socket.destroyed === false) {
// Write out the command
if (!Array.isArray(buffer)) {
this.socket.write(buffer, 'binary');
return true;
}
// Iterate over all buffers and write them in order to the socket
for (let i = 0; i < buffer.length; i++) {
this.socket.write(buffer[i], 'binary');
}
return true;
}
// Connection is destroyed return write failed
return false;
}
/**
* Return id of connection as a string
* @method
* @return {string}
*/
toString() {
return '' + this.id;
}
/**
* Return json object of connection
* @method
* @return {object}
*/
toJSON() {
return { id: this.id, host: this.host, port: this.port };
}
/**
* Is the connection connected
* @method
* @return {boolean}
*/
isConnected() {
if (this.destroyed) return false;
return !this.socket.destroyed && this.socket.writable;
}
/**
* @ignore
*/
command(ns, command, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
const conn = this;
const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 0;
const bson = conn.options.bson;
const query = new Query(bson, ns, command, {
numberToSkip: 0,
numberToReturn: 1
});
const noop = () => {};
function _callback(err, result) {
callback(err, result);
callback = noop;
}
function errorHandler(err) {
conn.resetSocketTimeout();
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
conn.removeListener('message', messageHandler);
if (err == null) {
err = new MongoError(`runCommand failed for connection to '${conn.address}'`);
}
// ignore all future errors
conn.on('error', noop);
_callback(err);
}
function messageHandler(msg) {
if (msg.responseTo !== query.requestId) {
return;
}
conn.resetSocketTimeout();
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
conn.removeListener('message', messageHandler);
msg.parse({ promoteValues: true });
const response = msg.documents[0];
if (response.ok === 0 || response.$err || response.errmsg || response.code) {
_callback(new MongoError(response));
return;
}
_callback(undefined, new CommandResult(response, this, msg));
}
conn.setSocketTimeout(socketTimeout);
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler));
conn.on('message', messageHandler);
conn.write(query.toBin());
}
}
const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError'];
function deleteConnection(id) {
// console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : ''))
delete connections[id];
if (connectionAccountingSpy) {
connectionAccountingSpy.deleteConnection(id);
}
}
function addConnection(id, connection) {
// console.log("=== added connection " + id + " :: " + connection.port)
connections[id] = connection;
if (connectionAccountingSpy) {
connectionAccountingSpy.addConnection(id, connection);
}
}
//
// Connection handlers
function errorHandler(conn) {
return function(err) {
if (connectionAccounting) deleteConnection(conn.id);
// Debug information
if (conn.logger.isDebug()) {
conn.logger.debug(
`connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]`
);
}
conn.emit('error', new MongoNetworkError(err), conn);
};
}
function timeoutHandler(conn) {
return function() {
if (connectionAccounting) deleteConnection(conn.id);
if (conn.logger.isDebug()) {
conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`);
}
conn.timedOut = true;
conn.emit(
'timeout',
new MongoNetworkTimeoutError(`connection ${conn.id} to ${conn.address} timed out`, {
beforeHandshake: conn.ismaster == null
}),
conn
);
};
}
function closeHandler(conn) {
return function(hadError) {
if (connectionAccounting) deleteConnection(conn.id);
if (conn.logger.isDebug()) {
conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`);
}
if (!hadError) {
conn.emit(
'close',
new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`),
conn
);
}
};
}
// Handle a message once it is received
function processMessage(conn, message) {
const msgHeader = parseHeader(message);
if (msgHeader.opCode !== OP_COMPRESSED) {
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
conn.emit(
'message',
new ResponseConstructor(
conn.bson,
message,
msgHeader,
message.slice(MESSAGE_HEADER_SIZE),
conn.responseOptions
),
conn
);
return;
}
msgHeader.fromCompressed = true;
let index = MESSAGE_HEADER_SIZE;
msgHeader.opCode = message.readInt32LE(index);
index += 4;
msgHeader.length = message.readInt32LE(index);
index += 4;
const compressorID = message[index];
index++;
decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => {
if (err) {
conn.emit('error', err);
return;
}
if (decompressedMsgBody.length !== msgHeader.length) {
conn.emit(
'error',
new MongoError(
'Decompressing a compressed message from the server failed. The message is corrupt.'
)
);
return;
}
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
conn.emit(
'message',
new ResponseConstructor(
conn.bson,
message,
msgHeader,
decompressedMsgBody,
conn.responseOptions
),
conn
);
});
}
function dataHandler(conn) {
return function(data) {
// Parse until we are done with the data
while (data.length > 0) {
// If we still have bytes to read on the current message
if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) {
// Calculate the amount of remaining bytes
const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead;
// Check if the current chunk contains the rest of the message
if (remainingBytesToRead > data.length) {
// Copy the new data into the exiting buffer (should have been allocated when we know the message size)
data.copy(conn.buffer, conn.bytesRead);
// Adjust the number of bytes read so it point to the correct index in the buffer
conn.bytesRead = conn.bytesRead + data.length;
// Reset state of buffer
data = Buffer.alloc(0);
} else {
// Copy the missing part of the data into our current buffer
data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead);
// Slice the overflow into a new buffer that we will then re-parse
data = data.slice(remainingBytesToRead);
// Emit current complete message
const emitBuffer = conn.buffer;
// Reset state of buffer
conn.buffer = null;
conn.sizeOfMessage = 0;
conn.bytesRead = 0;
conn.stubBuffer = null;
processMessage(conn, emitBuffer);
}
} else {
// Stub buffer is kept in case we don't get enough bytes to determine the
// size of the message (< 4 bytes)
if (conn.stubBuffer != null && conn.stubBuffer.length > 0) {
// If we have enough bytes to determine the message size let's do it
if (conn.stubBuffer.length + data.length > 4) {
// Prepad the data
const newData = Buffer.alloc(conn.stubBuffer.length + data.length);
conn.stubBuffer.copy(newData, 0);
data.copy(newData, conn.stubBuffer.length);
// Reassign for parsing
data = newData;
// Reset state of buffer
conn.buffer = null;
conn.sizeOfMessage = 0;
conn.bytesRead = 0;
conn.stubBuffer = null;
} else {
// Add the the bytes to the stub buffer
const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length);
// Copy existing stub buffer
conn.stubBuffer.copy(newStubBuffer, 0);
// Copy missing part of the data
data.copy(newStubBuffer, conn.stubBuffer.length);
// Exit parsing loop
data = Buffer.alloc(0);
}
} else {
if (data.length > 4) {
// Retrieve the message size
const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
// If we have a negative sizeOfMessage emit error and return
if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) {
const errorObject = {
err: 'socketHandler',
trace: '',
bin: conn.buffer,
parseState: {
sizeOfMessage: sizeOfMessage,
bytesRead: conn.bytesRead,
stubBuffer: conn.stubBuffer
}
};
// We got a parse Error fire it off then keep going
conn.emit('parseError', errorObject, conn);
return;
}
// Ensure that the size of message is larger than 0 and less than the max allowed
if (
sizeOfMessage > 4 &&
sizeOfMessage < conn.maxBsonMessageSize &&
sizeOfMessage > data.length
) {
conn.buffer = Buffer.alloc(sizeOfMessage);
// Copy all the data into the buffer
data.copy(conn.buffer, 0);
// Update bytes read
conn.bytesRead = data.length;
// Update sizeOfMessage
conn.sizeOfMessage = sizeOfMessage;
// Ensure stub buffer is null
conn.stubBuffer = null;
// Exit parsing loop
data = Buffer.alloc(0);
} else if (
sizeOfMessage > 4 &&
sizeOfMessage < conn.maxBsonMessageSize &&
sizeOfMessage === data.length
) {
const emitBuffer = data;
// Reset state of buffer
conn.buffer = null;
conn.sizeOfMessage = 0;
conn.bytesRead = 0;
conn.stubBuffer = null;
// Exit parsing loop
data = Buffer.alloc(0);
// Emit the message
processMessage(conn, emitBuffer);
} else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) {
const errorObject = {
err: 'socketHandler',
trace: null,
bin: data,
parseState: {
sizeOfMessage: sizeOfMessage,
bytesRead: 0,
buffer: null,
stubBuffer: null
}
};
// We got a parse Error fire it off then keep going
conn.emit('parseError', errorObject, conn);
// Clear out the state of the parser
conn.buffer = null;
conn.sizeOfMessage = 0;
conn.bytesRead = 0;
conn.stubBuffer = null;
// Exit parsing loop
data = Buffer.alloc(0);
} else {
const emitBuffer = data.slice(0, sizeOfMessage);
// Reset state of buffer
conn.buffer = null;
conn.sizeOfMessage = 0;
conn.bytesRead = 0;
conn.stubBuffer = null;
// Copy rest of message
data = data.slice(sizeOfMessage);
// Emit the message
processMessage(conn, emitBuffer);
}
} else {
// Create a buffer that contains the space for the non-complete message
conn.stubBuffer = Buffer.alloc(data.length);
// Copy the data to the stub buffer
data.copy(conn.stubBuffer, 0);
// Exit parsing loop
data = Buffer.alloc(0);
}
}
}
}
};
}
/**
* A server connect event, used to verify that the connection is up and running
*
* @event Connection#connect
* @type {Connection}
*/
/**
* The server connection closed, all pool connections closed
*
* @event Connection#close
* @type {Connection}
*/
/**
* The server connection caused an error, all pool connections closed
*
* @event Connection#error
* @type {Connection}
*/
/**
* The server connection timed out, all pool connections closed
*
* @event Connection#timeout
* @type {Connection}
*/
/**
* The driver experienced an invalid message, all pool connections closed
*
* @event Connection#parseError
* @type {Connection}
*/
/**
* An event emitted each time the connection receives a parsed message from the wire
*
* @event Connection#message
* @type {Connection}
*/
module.exports = Connection;