-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
252 lines (213 loc) · 8.45 KB
/
index.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
const tedious = require('tedious');
let logger = {};
class ConnectionPool
{
constructor(poolConfig, connectionConfig)
{
this.config = {pool: poolConfig, connection: connectionConfig};
this.config.pool.min = this.config.pool.min !== undefined ? this.config.pool.min : 1;
this.config.pool.max = this.config.pool.max !== undefined ? this.config.pool.max : 10;
this.config.pool.idleTimeout = this.config.pool.idleTimeout !== undefined ? this.config.pool.idleTimeout : 30000;
this.config.pool.acquireTimeout = this.config.pool.acquireTimeout !== undefined ? this.config.pool.acquireTimeout : 60000;
this.config.pool.log = this.config.pool.log || false;
if(typeof this.config.pool.log.log === 'function')
{
logger = this.config.pool.log;
}
else if(typeof this.config.pool.log === 'function')
{
logger.log = this.config.pool.log;
}
else if(this.config.pool.log)
{
logger.log = (...args) => console.log(...args);
}
else
{
logger.log = () => {};
}
this.clientID = 0;
this.connectionID = 0;
this.waitingClients = [];
this.connections = [];
this.drained = false;
this.connect();
}
acquire(callback)
{
return new Promise((resolve, reject) =>
{
callback = typeof callback === 'function' ? callback : () => {};
let resolved = false;
const client = {};
const callbackFn = (error, connection) =>
{
if(!resolved)
{
logger.log('debug', `Responding to client: ${client.id} (waiting clients: ${this.waitingClients.length})`);
clearTimeout(client.timerID);
resolved = true;
if(error)
{
logger.log('error', error.message);
callback(error);
return reject(error);
}
callback(null, connection);
return resolve(connection);
}
};
const timerFn = () =>
{
const error = new Error(`Unable to acquire connection from pool in ${this.config.pool.acquireTimeout}ms.`);
for(let i = this.waitingClients.length-1; i >= 0; i--)
{
if(this.waitingClients[i].id === client.id)
{
this.waitingClients.splice(i, 1);
break;
}
}
client.callback(error);
};
client.id = ++this.clientID;
client.timerID = setTimeout(timerFn, this.config.pool.acquireTimeout);
client.callback = callbackFn;
this.waitingClients.push(client);
logger.log('debug', `Added new client: ${client.id} (waiting clients: ${this.waitingClients.length})`);
this.respond();
})
}
connect()
{
if(this.connections.length < this.config.pool.min)
{
logger.log('debug', `Refilling connection pool (pool size: ${this.connections.length})`);
const needed = this.config.pool.min - this.connections.length;
for(let i=0; i < needed; i++)
{
this.openConnection();
}
}
}
handleError(error, connection)
{
logger.log('error', error.message);
connection.close();
}
addConnection(error, connection)
{
if(error)
{
this.handleError(error, connection);
return;
}
logger.log('debug', `Opened connection: ${connection.meta.id} (pool size: ${this.connections.length})`);
if(this.connections.length+1 <= this.config.pool.max)
{
this.connections.push(connection);
this.respond();
}
else
{
logger.log('debug', `Connection pool is full.`);
connection.close();
}
}
prepareConnection(connection)
{
connection.meta = {};
connection.meta.id = ++this.connectionID;
connection.meta.timestamp = new Date();
connection.meta.available = true;
connection.meta.timerID = setTimeout(() => this.removeConnection(connection), this.config.pool.idleTimeout);
connection.once('connect', (error) => this.addConnection(error, connection));
connection.once('error', (error) => this.handleError(error, connection));
connection.on('infoMessage', (info) => logger.log('debug', `Error: ${info.number}. State: ${info.state}. Class: ${info.class}. Message: ${info.message}. Procedure: ${info.procedure}. Line Number: ${info.lineNumber}`));
connection.on('errorMessage', (error) => logger.log('debug', `Error: ${error.number}. State: ${error.state}. Class: ${error.class}. Message: ${error.message}. Procedure: ${error.procedure}. Line Number: ${error.lineNumber}`));
connection.once('end', () => this.removeConnection(connection, true));
connection.release = () =>
{
connection.meta.timestamp = new Date();
connection.meta.available = true;
clearTimeout(connection.meta.timerID);
connection.meta.timerID = setTimeout(() => this.removeConnection(connection), this.config.pool.idleTimeout);
this.respond();
};
}
openConnection()
{
const timestamps = this.connections.sort((a, b) =>
{
if(a.meta.timestamp < b.meta.timestamp)
{
return -1;
}
else if(a.meta.timestamp > b.meta.timestamp)
{
return 1;
}
return 0;
});
if(this.connections.length+1 <= this.config.pool.max && (this.connections.length <= 1 || timestamps[timestamps.length-1] - timestamps[0] >= this.config.pool.idleTimeout))
{
const connection = new tedious.Connection(this.config.connection);
this.prepareConnection(connection);
}
}
removeConnection(connection, force)
{
if(force || (new Date() - connection.meta.timestamp >= this.config.pool.idleTimeout && this.connections.length-1 >= this.config.pool.min))
{
['connect', 'error', 'errorMessage', 'infoMessage', 'end'].forEach((eventName) => connection.removeAllListeners(eventName));
connection.close();
for(let i=this.connections.length-1; i >= 0; i--)
{
if(this.connections[i].meta.id === connection.meta.id)
{
this.connections.splice(i, 1);
break;
}
}
logger.log('debug', `Closed connection: ${connection.meta.id} (pool size: ${this.connections.length})`);
this.connect();
}
}
respond()
{
const client = this.waitingClients.shift();
if(client)
{
for(const connection of this.connections)
{
if(connection.meta.available && connection.loggedIn)
{
connection.meta.available = false;
connection.meta.timestamp = new Date();
clearTimeout(connection.meta.timerID);
connection.meta.timerID = setTimeout(() => this.removeConnection(connection), this.config.pool.idleTimeout);
logger.log('debug', `Reusing connection: ${connection.meta.id} (pool size: ${this.connections.length})`);
return client.callback(null, connection);
}
}
this.waitingClients.unshift(client);
this.openConnection();
}
}
drain()
{
logger.log('debug', 'Draining connection pool (pool size: ${this.connections.length})');
for(let i = this.connections.length-1; i >= 0; i--)
{
this.connections[i].close();
}
const error = new Error('Connection pool has been drained, no new connections can be opened');
for(let i = this.waitingClients.length-1; i >= 0; i--)
{
this.waitingClients[i](error);
this.waitingClients.splice(i, 1);
}
this.drained = true;
}
}
module.exports = ConnectionPool;