pool.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. allowH2,
  34. ...options
  35. } = {}) {
  36. super()
  37. if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
  38. throw new InvalidArgumentError('invalid connections')
  39. }
  40. if (typeof factory !== 'function') {
  41. throw new InvalidArgumentError('factory must be a function.')
  42. }
  43. if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
  44. throw new InvalidArgumentError('connect must be a function or an object')
  45. }
  46. if (typeof connect !== 'function') {
  47. connect = buildConnector({
  48. ...tls,
  49. maxCachedSessions,
  50. allowH2,
  51. socketPath,
  52. timeout: connectTimeout,
  53. ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
  54. ...connect
  55. })
  56. }
  57. this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)
  58. ? options.interceptors.Pool
  59. : []
  60. this[kConnections] = connections || null
  61. this[kUrl] = util.parseOrigin(origin)
  62. this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
  63. this[kOptions].interceptors = options.interceptors
  64. ? { ...options.interceptors }
  65. : undefined
  66. this[kFactory] = factory
  67. }
  68. [kGetDispatcher] () {
  69. for (const client of this[kClients]) {
  70. if (!client[kNeedDrain]) {
  71. return client
  72. }
  73. }
  74. if (!this[kConnections] || this[kClients].length < this[kConnections]) {
  75. const dispatcher = this[kFactory](this[kUrl], this[kOptions])
  76. this[kAddClient](dispatcher)
  77. return dispatcher
  78. }
  79. }
  80. }
  81. module.exports = Pool