-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathconnection-pool.js
570 lines (505 loc) · 15.6 KB
/
connection-pool.js
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
'use strict'
const { EventEmitter } = require('events')
const debug = require('debug')('mssql:base')
const { parseSqlConnectionString } = require('@tediousjs/connection-string')
const tarn = require('tarn')
const { IDS } = require('../utils')
const ConnectionError = require('../error/connection-error')
const shared = require('../shared')
const clone = require('rfdc/default')
const { MSSQLError } = require('../error')
/**
* Class ConnectionPool.
*
* Internally, each `Connection` instance is a separate pool of TDS connections. Once you create a new `Request`/`Transaction`/`Prepared Statement`, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool.
*
* @property {Boolean} connected If true, connection is established.
* @property {Boolean} connecting If true, connection is being established.
*
* @fires ConnectionPool#connect
* @fires ConnectionPool#close
*/
class ConnectionPool extends EventEmitter {
/**
* Create new Connection.
*
* @param {Object|String} config Connection configuration object or connection string.
* @param {basicCallback} [callback] A callback which is called after connection has established, or an error has occurred.
*/
constructor (config, callback) {
super()
IDS.add(this, 'ConnectionPool')
debug('pool(%d): created', IDS.get(this))
this._connectStack = []
this._closeStack = []
this._connected = false
this._connecting = false
this._healthy = false
if (typeof config === 'string') {
try {
this.config = this.constructor.parseConnectionString(config)
} catch (ex) {
if (typeof callback === 'function') {
return setImmediate(callback, ex)
}
throw ex
}
} else {
this.config = clone(config)
}
// set defaults
this.config.port = this.config.port || 1433
this.config.options = this.config.options || {}
this.config.stream = this.config.stream || false
this.config.parseJSON = this.config.parseJSON || false
this.config.arrayRowMode = this.config.arrayRowMode || false
this.config.validateConnection = 'validateConnection' in this.config ? this.config.validateConnection : true
if (/^(.*)\\(.*)$/.exec(this.config.server)) {
this.config.server = RegExp.$1
this.config.options.instanceName = RegExp.$2
}
if (typeof this.config.options.useColumnNames !== 'undefined' && this.config.options.useColumnNames !== true) {
const ex = new MSSQLError('Invalid options `useColumnNames`, use `arrayRowMode` instead')
if (typeof callback === 'function') {
return setImmediate(callback, ex)
}
throw ex
}
if (typeof callback === 'function') {
this.connect(callback)
}
}
get connected () {
return this._connected
}
get connecting () {
return this._connecting
}
get healthy () {
return this._healthy
}
static parseConnectionString (connectionString) {
return this._parseConnectionString(connectionString)
}
static _parseConnectionString (connectionString) {
const parsed = parseSqlConnectionString(connectionString, true, true)
return Object.entries(parsed).reduce((config, [key, value]) => {
switch (key) {
case 'application name':
break
case 'applicationintent':
Object.assign(config.options, {
readOnlyIntent: value === 'readonly'
})
break
case 'asynchronous processing':
break
case 'attachdbfilename':
break
case 'authentication':
break
case 'column encryption setting':
break
case 'connection timeout':
Object.assign(config, {
connectionTimeout: value * 1000
})
break
case 'connection lifetime':
break
case 'connectretrycount':
break
case 'connectretryinterval':
Object.assign(config.options, {
connectionRetryInterval: value * 1000
})
break
case 'context connection':
break
case 'current language':
Object.assign(config.options, {
language: value
})
break
case 'data source':
{
let server = value
let instanceName
let port = 1433
if (/^np:/i.test(server)) {
throw new Error('Connection via Named Pipes is not supported.')
}
if (/^tcp:/i.test(server)) {
server = server.substr(4)
}
if (/^(.*)\\(.*)$/.exec(server)) {
server = RegExp.$1
instanceName = RegExp.$2
}
if (/^(.*),(.*)$/.exec(server)) {
server = RegExp.$1.trim()
port = parseInt(RegExp.$2.trim(), 10)
}
if (server === '.' || server === '(.)' || server.toLowerCase() === '(localdb)' || server.toLowerCase() === '(local)') {
server = 'localhost'
}
Object.assign(config, {
port,
server
})
Object.assign(config.options, {
instanceName
})
break
}
case 'encrypt':
Object.assign(config.options, {
encrypt: !!value
})
break
case 'enlist':
break
case 'failover partner':
break
case 'initial catalog':
Object.assign(config, {
database: value
})
break
case 'integrated security':
break
case 'max pool size':
Object.assign(config.pool, {
max: value
})
break
case 'min pool size':
Object.assign(config.pool, {
min: value
})
break
case 'multipleactiveresultsets':
break
case 'multisubnetfailover':
Object.assign(config.options, {
multiSubnetFailover: value
})
break
case 'network library':
break
case 'packet size':
Object.assign(config.options, {
packetSize: value
})
break
case 'password':
Object.assign(config, {
password: value
})
break
case 'persist security info':
break
case 'poolblockingperiod':
break
case 'pooling':
break
case 'replication':
break
case 'transaction binding':
Object.assign(config.options, {
enableImplicitTransactions: value.toLowerCase() === 'implicit unbind'
})
break
case 'transparentnetworkipresolution':
break
case 'trustservercertificate':
Object.assign(config.options, {
trustServerCertificate: value
})
break
case 'type system version':
break
case 'user id': {
let user = value
let domain
if (/^(.*)\\(.*)$/.exec(user)) {
domain = RegExp.$1
user = RegExp.$2
}
Object.assign(config, {
domain,
user
})
break
}
case 'user instance':
break
case 'workstation id':
Object.assign(config.options, {
workstationId: value
})
break
case 'request timeout':
Object.assign(config, {
requestTimeout: parseInt(value, 10)
})
break
case 'stream':
Object.assign(config, {
stream: !!value
})
break
case 'useutc':
Object.assign(config.options, {
useUTC: !!value
})
break
case 'parsejson':
Object.assign(config, {
parseJSON: !!value
})
break
}
return config
}, { options: {}, pool: {} })
}
/**
* Acquire connection from this connection pool.
*
* @param {ConnectionPool|Transaction|PreparedStatement} requester Requester.
* @param {acquireCallback} [callback] A callback which is called after connection has been acquired, or an error has occurred. If omited, method returns Promise.
* @return {ConnectionPool|Promise}
*/
acquire (requester, callback) {
const acquirePromise = shared.Promise.resolve(this._acquire().promise).catch(err => {
this.emit('error', err)
throw err
})
if (typeof callback === 'function') {
acquirePromise.then(connection => callback(null, connection, this.config)).catch(callback)
return this
}
return acquirePromise
}
_acquire () {
if (!this.pool) {
return shared.Promise.reject(new ConnectionError('Connection not yet open.', 'ENOTOPEN'))
} else if (this.pool.destroyed) {
return shared.Promise.reject(new ConnectionError('Connection is closing', 'ENOTOPEN'))
}
return this.pool.acquire()
}
/**
* Release connection back to the pool.
*
* @param {Connection} connection Previously acquired connection.
* @return {ConnectionPool}
*/
release (connection) {
debug('connection(%d): released', IDS.get(connection))
if (this.pool) {
this.pool.release(connection)
}
return this
}
/**
* Creates a new connection pool with one active connection. This one initial connection serves as a probe to find out whether the configuration is valid.
*
* @param {basicCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
* @return {ConnectionPool|Promise}
*/
connect (callback) {
if (typeof callback === 'function') {
this._connect(callback)
return this
}
return new shared.Promise((resolve, reject) => {
return this._connect(err => {
if (err) return reject(err)
resolve(this)
})
})
}
/**
* @private
* @param {basicCallback} callback
*/
_connect (callback) {
if (this._connected) {
debug('pool(%d): already connected, executing connect callback immediately', IDS.get(this))
return setImmediate(callback, null, this)
}
this._connectStack.push(callback)
if (this._connecting) {
return
}
this._connecting = true
debug('pool(%d): connecting', IDS.get(this))
// create one test connection to check if everything is ok
this._poolCreate().then((connection) => {
debug('pool(%d): connected', IDS.get(this))
this._healthy = true
return this._poolDestroy(connection).then(() => {
// prepare pool
this.pool = new tarn.Pool(
Object.assign({
create: () => this._poolCreate()
.then(connection => {
this._healthy = true
return connection
})
.catch(err => {
if (this.pool.numUsed() + this.pool.numFree() <= 0) {
this._healthy = false
}
throw err
}),
validate: this._poolValidate.bind(this),
destroy: this._poolDestroy.bind(this),
max: 10,
min: 0,
idleTimeoutMillis: 30000,
propagateCreateError: true
}, this.config.pool)
)
this._connecting = false
this._connected = true
})
}).then(() => {
this._connectStack.forEach((cb) => {
setImmediate(cb, null, this)
})
}).catch(err => {
this._connecting = false
this._connectStack.forEach((cb) => {
setImmediate(cb, err)
})
}).then(() => {
this._connectStack = []
})
}
get size () {
return this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates()
}
get available () {
return this.pool.numFree()
}
get pending () {
return this.pool.numPendingAcquires()
}
get borrowed () {
return this.pool.numUsed()
}
/**
* Close all active connections in the pool.
*
* @param {basicCallback} [callback] A callback which is called after connection has closed, or an error has occurred. If omited, method returns Promise.
* @return {ConnectionPool|Promise}
*/
close (callback) {
if (typeof callback === 'function') {
this._close(callback)
return this
}
return new shared.Promise((resolve, reject) => {
this._close(err => {
if (err) return reject(err)
resolve(this)
})
})
}
/**
* @private
* @param {basicCallback} callback
*/
_close (callback) {
// we don't allow pools in a connecting state to be closed because it means there are far too many
// edge cases to deal with
if (this._connecting) {
debug('pool(%d): close called while connecting', IDS.get(this))
setImmediate(callback, new ConnectionError('Cannot close a pool while it is connecting'))
}
if (!this.pool) {
debug('pool(%d): already closed, executing close callback immediately', IDS.get(this))
return setImmediate(callback, null)
}
this._closeStack.push(callback)
if (this.pool.destroyed) return
this._connecting = this._connected = this._healthy = false
this.pool.destroy().then(() => {
debug('pool(%d): pool closed, removing pool reference and executing close callbacks', IDS.get(this))
this.pool = null
this._closeStack.forEach(cb => {
setImmediate(cb, null)
})
}).catch(err => {
this.pool = null
this._closeStack.forEach(cb => {
setImmediate(cb, err)
})
}).then(() => {
this._closeStack = []
})
}
/**
* Returns new request using this connection.
*
* @return {Request}
*/
request () {
return new shared.driver.Request(this)
}
/**
* Returns new transaction using this connection.
*
* @return {Transaction}
*/
transaction () {
return new shared.driver.Transaction(this)
}
/**
* Creates a new query using this connection from a tagged template string.
*
* @variation 1
* @param {Array} strings Array of string literals.
* @param {...*} keys Values.
* @return {Request}
*/
/**
* Execute the SQL command.
*
* @variation 2
* @param {String} command T-SQL command to be executed.
* @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
query () {
if (typeof arguments[0] === 'string') { return new shared.driver.Request(this).query(arguments[0], arguments[1]) }
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
return new shared.driver.Request(this)._template(strings, values, 'query')
}
/**
* Creates a new batch using this connection from a tagged template string.
*
* @variation 1
* @param {Array} strings Array of string literals.
* @param {...*} keys Values.
* @return {Request}
*/
/**
* Execute the SQL command.
*
* @variation 2
* @param {String} command T-SQL command to be executed.
* @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
* @return {Request|Promise}
*/
batch () {
if (typeof arguments[0] === 'string') { return new shared.driver.Request(this).batch(arguments[0], arguments[1]) }
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
return new shared.driver.Request(this)._template(strings, values, 'batch')
}
}
module.exports = ConnectionPool