pool.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict'
  2. const {
  3. PoolBase,
  4. kClients,
  5. kNeedDrain,
  6. kAddClient,
  7. kGetDispatcher
  8. } = require('./pool-base')
  9. const Client = require('./client')
  10. const {
  11. InvalidArgumentError
  12. } = require('./core/errors')
  13. const util = require('./core/util')
  14. const { kUrl, kInterceptors } = require('./core/symbols')
  15. const buildConnector = require('./core/connect')
  16. const kOptions = Symbol('options')
  17. const kConnections = Symbol('connections')
  18. const kFactory = Symbol('factory')
  19. function defaultFactory (origin, opts) {
  20. return new Client(origin, opts)
  21. }
  22. class Pool extends PoolBase {
  23. constructor (origin, {
  24. connections,
  25. factory = defaultFactory,
  26. connect,
  27. connectTimeout,
  28. tls,
  29. maxCachedSessions,
  30. socketPath,
  31. autoSelectFamily,
  32. autoSelectFamilyAttemptTimeout,
  33. ...options
  34. } = {}) {
  35. super()
  36. if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
  37. throw new InvalidArgumentError('invalid connections')
  38. }
  39. if (typeof factory !== 'function') {
  40. throw new InvalidArgumentError('factory must be a function.')
  41. }
  42. if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
  43. throw new InvalidArgumentError('connect must be a function or an object')
  44. }
  45. if (typeof connect !== 'function') {
  46. connect = buildConnector({
  47. ...tls,
  48. maxCachedSessions,
  49. socketPath,
  50. timeout: connectTimeout == null ? 10e3 : connectTimeout,
  51. ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
  52. ...connect
  53. })
  54. }
  55. this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
  56. ? options.interceptors.Pool
  57. : []
  58. this[kConnections] = connections || null
  59. this[kUrl] = util.parseOrigin(origin)
  60. this[kOptions] = { ...util.deepClone(options), connect }
  61. this[kOptions].interceptors = options.interceptors
  62. ? { ...options.interceptors }
  63. : undefined
  64. this[kFactory] = factory
  65. }
  66. [kGetDispatcher] () {
  67. let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
  68. if (dispatcher) {
  69. return dispatcher
  70. }
  71. if (!this[kConnections] || this[kClients].length < this[kConnections]) {
  72. dispatcher = this[kFactory](this[kUrl], this[kOptions])
  73. this[kAddClient](dispatcher)
  74. }
  75. return dispatcher
  76. }
  77. }
  78. module.exports = Pool