Debian Codegraph @

lib/dispatcher/balanced-pool.js

raw
1 'use strict'
2
3 const {
4 BalancedPoolMissingUpstreamError,
5 InvalidArgumentError
6 } = require('../core/errors')
7 const {
8 PoolBase,
9 kClients,
10 kNeedDrain,
11 kAddClient,
12 kRemoveClient,
13 kGetDispatcher
14 } = require('./pool-base')
15 const Pool = require('./pool')
16 const { kUrl } = require('../core/symbols')
17 const util = require('../core/util')
18 const kFactory = Symbol('factory')
19
20 const kOptions = Symbol('options')
21 const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
22 const kCurrentWeight = Symbol('kCurrentWeight')
23 const kIndex = Symbol('kIndex')
24 const kWeight = Symbol('kWeight')
25 const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
26 const kErrorPenalty = Symbol('kErrorPenalty')
27
28 /**
29 * Calculate the greatest common divisor of two numbers by
30 * using the Euclidean algorithm.
31 *
32 * @param {number} a
33 * @param {number} b
34 * @returns {number}
35 */
36 function getGreatestCommonDivisor (a, b) {
37 if (a === 0) return b
38
39 while (b !== 0) {
40 const t = b
41 b = a % b
42 a = t
43 }
44 return a
45 }
46
47 function defaultFactory (origin, opts) {
48 return new Pool(origin, opts)
49 }
50
51 class BalancedPool extends PoolBase {
52 constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
53 if (typeof factory !== 'function') {
54 throw new InvalidArgumentError('factory must be a function.')
55 }
56
57 super()
58
59 this[kOptions] = { ...util.deepClone(opts) }
60 this[kIndex] = -1
61 this[kCurrentWeight] = 0
62
63 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
64 this[kErrorPenalty] = this[kOptions].errorPenalty || 15
65
66 if (!Array.isArray(upstreams)) {
67 upstreams = [upstreams]
68 }
69
70 this[kFactory] = factory
71
72 for (const upstream of upstreams) {
73 this.addUpstream(upstream)
74 }
75 this._updateBalancedPoolStats()
76 }
77
78 addUpstream (upstream) {
79 const upstreamOrigin = util.parseOrigin(upstream).origin
80
81 if (this[kClients].find((pool) => (
82 pool[kUrl].origin === upstreamOrigin &&
83 pool.closed !== true &&
84 pool.destroyed !== true
85 ))) {
86 return this
87 }
88 const pool = this[kFactory](upstreamOrigin, this[kOptions])
89
90 this[kAddClient](pool)
91 pool.on('connect', () => {
92 pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
93 })
94
95 pool.on('connectionError', () => {
96 pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
97 this._updateBalancedPoolStats()
98 })
99
100 pool.on('disconnect', (...args) => {
101 const err = args[2]
102 if (err && err.code === 'UND_ERR_SOCKET') {
103 // decrease the weight of the pool.
104 pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
105 this._updateBalancedPoolStats()
106 }
107 })
108
109 for (const client of this[kClients]) {
110 client[kWeight] = this[kMaxWeightPerServer]
111 }
112
113 this._updateBalancedPoolStats()
114
115 return this
116 }
117
118 _updateBalancedPoolStats () {
119 let result = 0
120 for (let i = 0; i < this[kClients].length; i++) {
121 result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
122 }
123
124 this[kGreatestCommonDivisor] = result
125 }
126
127 removeUpstream (upstream) {
128 const upstreamOrigin = util.parseOrigin(upstream).origin
129
130 const pool = this[kClients].find((pool) => (
131 pool[kUrl].origin === upstreamOrigin &&
132 pool.closed !== true &&
133 pool.destroyed !== true
134 ))
135
136 if (pool) {
137 this[kRemoveClient](pool)
138 }
139
140 return this
141 }
142
143 getUpstream (upstream) {
144 const upstreamOrigin = util.parseOrigin(upstream).origin
145
146 return this[kClients].find((pool) => (
147 pool[kUrl].origin === upstreamOrigin &&
148 pool.closed !== true &&
149 pool.destroyed !== true
150 ))
151 }
152
153 get upstreams () {
154 return this[kClients]
155 .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
156 .map((p) => p[kUrl].origin)
157 }
158
159 [kGetDispatcher] () {
160 // We validate that pools is greater than 0,
161 // otherwise we would have to wait until an upstream
162 // is added, which might never happen.
163 if (this[kClients].length === 0) {
164 throw new BalancedPoolMissingUpstreamError()
165 }
166
167 let counter = 0
168
169 let maxWeightIndex = -1
170
171 while (counter++ < this[kClients].length) {
172 this[kIndex] = (this[kIndex] + 1) % this[kClients].length
173 const pool = this[kClients][this[kIndex]]
174
175 // decrease the current weight every `this[kClients].length`.
176 if (this[kIndex] === 0) {
177 // Set the current weight to the next lower weight.
178 this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
179
180 if (this[kCurrentWeight] <= 0) {
181 this[kCurrentWeight] = this[kMaxWeightPerServer]
182 }
183 }
184
185 // Skip unavailable pools after updating the current weight for this cycle.
186 if (
187 pool[kNeedDrain] ||
188 pool.closed === true ||
189 pool.destroyed === true
190 ) {
191 continue
192 }
193
194 // Track the best fallback if no pool matches the current weight.
195 if (maxWeightIndex === -1 || pool[kWeight] > this[kClients][maxWeightIndex][kWeight]) {
196 maxWeightIndex = this[kIndex]
197 }
198
199 if (pool[kWeight] >= this[kCurrentWeight]) {
200 return pool
201 }
202 }
203
204 if (maxWeightIndex === -1) {
205 return
206 }
207
208 this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
209 this[kIndex] = maxWeightIndex
210 return this[kClients][maxWeightIndex]
211 }
212 }
213
214 module.exports = BalancedPool