-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
367 lines (282 loc) · 8.71 KB
/
main.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
'use strict';
const fs = require('fs'),
path = require('path'),
{Connection, Request, TYPES} = require('tedious');
// used to match type strings in parameter definitions
const TYPEHASH = {};
for(var k in TYPES) {
if(TYPES.hasOwnProperty(k)) {
TYPEHASH[k.toLowerCase()] = TYPES[k];
}
}
const
NEW = 0,
IDLE = 1,
BUSY = 2,
FAIL = 3,
MAX_POOL = 16;
function handleError(err, job) {
if(global.output) {
global.output.error(JSON.stringify(err));
if(job) global.output.error(JSON.stringify(job.queryDef));
} else console.log(JSON.stringify(err));
}
function setParameters(req, params, obj) {
for(var i = 0; i < params.length; i++) {
req.addParameter(params[i].name, TYPEHASH[params[i].type.toLowerCase()], obj[params[i].name], params[i].options);
}
}
function flattenResults(rows) {
var rr = [];
for(var i = 0; i < rows.length; i++) {
rr.push(Object.entries(rows[i]).reduce((a,v) => {a[v[0]] = v[1].value; return a;}, {}));
}
return rr;
}
function SQLServerPool(config) {
// load connection / tedious config
// will decode username, password, server ip from base64 obfuscation
// note, none of these settings are encrypted
const sqlcfg = Object.assign({
server: '127.0.0.1',
authentication: {
options: {
userName: '',
password: ''
}
}
}, config);
if(sqlcfg.authentication.options.userName.startsWith('data:')) sqlcfg.authentication.options.userName = atob(sqlcfg.authentication.options.userName.replace('data:',''));
if(sqlcfg.authentication.options.password.startsWith('data:')) sqlcfg.authentication.options.password = atob(sqlcfg.authentication.options.password.replace('data:',''));
if(sqlcfg.server.startsWith('data:')) sqlcfg.server = atob(sqlcfg.server.replace('data:',''));
const pool = [], requestQueue = [], self = this;
var running = true, queueProc, queueTimer = 100;
// create connection
function createConnection(config) {
if(!running) return null;
return new Connection(sqlcfg);
}
function acquireConnection() {
return new Promise((resolve) => {
if(!running) resolve(null);
// find and return idle connection
for(var i = pool.length - 1; i >= 0; i--) {
if(pool[i].status == IDLE) {
return resolve(pool[i]);
}
// remove broken connections
if(pool[i].status == FAIL) {
var broken = pool.splice(i,1);
broken.con.close();
}
}
// or attempt to create a new connection
if(pool.length < MAX_POOL) {
var con = createConnection(sqlcfg);
if(con == null) resolve(null);
var entry = {
con: con,
status: NEW
};
// when connection made, return to caller
con.on('connect', (err) => {
if(err) return handleError(err);
entry.status = IDLE;
return resolve(entry);
});
con.on('error', (err) => {
//console.log('aquireConnection()');
handleError(err);
entry.status = FAIL;
return resolve(null);
});
// if connection ends, remove from pool
con.on('end', () => {
for(var i = pool.length - 1; i >= 0; i--) {
if(pool[i] === entry)
return pool.splice(i,1);
}
});
pool.push(entry);
} else return resolve(null);
// no connections available, return null
});
}
async function queueProc() {
if(!running) return;
//console.log(`Queue Length: ${requestQueue.length} Pool: ${pool.length}`);
if(requestQueue.length > 0) {
var pooled = await acquireConnection();
if(pooled != null) {
var job = requestQueue.shift();
pooled.con.removeAllListeners('socketError');
pooled.con.on('socketError', (err) => {
console.log('queueProc()');
handleError(err);
pooled.status = FAIL;
job.pooled = null;
requestQueue.push(job);
pooled.con.removeAllListeners('socketError');
queueTimer = 2000;
});
job.pooled = pooled;
execJob(job);
}
}
if(running) {
//if(requestQueue.length > 0) setImmediate(queueProc);
//else setTimeout(queueProc, 500);
setTimeout(queueProc, queueTimer);
if(requestQueue.length > 0) queueTimer = Math.max(10, queueTimer - 10);
else queueTimer = Math.min(100, queueTimer + 10);
}
}
function createCallbackQuery(queryDef) {
return function(obj, optcallback) {
obj = obj || {};
const job = {
queryDef: queryDef,
params: obj,
callback: optcallback || queryDef.callback,
pooled: null
};
job.resultHandler = getCallbackHandler(job);
requestQueue.push(job);
}
}
function getCallbackHandler(job) {
if(!job.callback) job.callback = ()=>{};
return (err, rowCount, rows) => {
job.pooled.status = IDLE;
return job.callback(err, rowCount, rows);
}
}
function createPromiseQuery(queryDef) {
return function(obj) {
obj = obj || {};
return new Promise((resolve, reject) => {
const job = {
queryDef: queryDef,
params: obj,
resolve: resolve,
reject: reject,
pooled: null
};
job.resultHandler = getPromiseHandler(job);
requestQueue.push(job);
});
}
}
function getPromiseHandler(job) {
return (err, rowCount, rows) => {
if(err) {
handleError(err, job);
// if timeout occurred, need to requeue
if(err.code == "ETIMEOUT" || err.code == "ESOCKET") {
job.pooled.status = FAIL;
job.pooled = null;
return requestQueue.push(job);
} else return job.reject();
}
job.pooled.status = IDLE;
if(rowCount == 0) return job.resolve([]);
if(!job.queryDef.flatten) return job.resolve(rows);
return job.resolve(flattenResults(rows));
}
}
function execJob(job) {
job.pooled.status = BUSY;
const req = new Request(job.queryDef.sql, job.resultHandler);
setParameters(req, job.queryDef.params, job.params);
if(job.queryDef.timeout) req.setTimeout(job.queryDef.timeout);
job.pooled.con.execSql(req);
}
this.start = function() {
running = true;
return setImmediate(queueProc);
};
this.stop = function() {
running = false;
};
this.exit = function() {
for(var i = 0; i < pool.length; i++) {
pool[i].con.close();
}
};
// convenience method - passes query directly to Tedious
this.exec = async function(sql, callback) {
requestQueue.push((pooled) => {
pooled.status = BUSY;
pooled.con.execSql(new Request(sql, (err, count, rows) => {
pooled.status = IDLE;
if(callback) return callback(err, count, rows);
}));
});
};
// load an array of query definitions
// returns an object with function calls for each named query
this.loadQueries = function(queryList, baseDir) {
var queryHash = {};
// default basedir is the one above node_modules
if(!baseDir) baseDir = path.join(__dirname, '..', '..');
for(var i = 0; i < queryList.length; i++) {
// if sql starts with colon, load the query from a file
if(queryList[i].sql.substr(0,1) == ':')
queryList[i].sql = fs.readFileSync(path.join(baseDir, queryList[i].sql.substr(1)), 'utf8');
if(!queryList[i].params) queryList[i].params = [];
if(queryList[i].usePromise) queryHash[queryList[i].id] = createPromiseQuery(queryList[i]);
else queryHash[queryList[i].id] = createCallbackQuery(queryList[i]);
}
return queryHash;
};
// load a single query definition
// returns a function for calling the query
// if usePromise is true, will return a promise-style function
// rather than a callback-style one
/** @deprecated **/
this.loadQuery = function(sql, params, callback, usePromise) {
if(!callback) callback = function() {};
if(!params) params = [];
if(usePromise) {
return function(obj) {
obj = obj || {};
return new Promise(resolve => {
requestQueue.push((pooled) => {
pooled.status = BUSY;
var req = new Request(sql, (err, rowCount, rows) => {
if(err) return console.log(err);
pooled.status = IDLE;
return resolve(rowCount > 0 ? rows : []);
});
// cycle through params and set up
for(var i = 0; i < params.length; i++) {
req.addParameter(params[i].name, TYPEHASH[params[i].type.toLowerCase()], obj[params[i].name], params[i].options);
}
pooled.con.execSql(req);
});
});
};
}
return function(obj, optcallback) {
requestQueue.push((pooled) => {
obj = obj || {};
pooled.status = BUSY;
var req = new Request(sql, (err, rowCount, rows) => {
pooled.status = IDLE;
return (optcallback || callback)(err, rowCount, rows);
});
//console.log(sql);
// cycle through params and set up
for(var i = 0; i < params.length; i++) {
req.addParameter(params[i].name, TYPEHASH[params[i].type.toLowerCase()], obj[params[i].name], params[i].options);
}
console.log(` Request: ${req}`);
pooled.con.execSql(req);
});
};
};
return this;
}
module.exports = {
SQLServerPool
};