-
Notifications
You must be signed in to change notification settings - Fork 16
/
pakmanaged.js
4342 lines (3652 loc) · 125 KB
/
pakmanaged.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var global = Function("return this;")();
/*!
* Ender: open module JavaScript framework (client-lib)
* copyright Dustin Diaz & Jacob Thornton 2011 (@ded @fat)
* http://ender.no.de
* License MIT
*/
!function (context) {
// a global object for node.js module compatiblity
// ============================================
context['global'] = context
// Implements simple module system
// losely based on CommonJS Modules spec v1.1.1
// ============================================
var modules = {}
, old = context.$
function require (identifier) {
// modules can be required from ender's build system, or found on the window
var module = modules[identifier] || window[identifier]
if (!module) throw new Error("Requested module '" + identifier + "' has not been defined.")
return module
}
function provide (name, what) {
return (modules[name] = what)
}
context['provide'] = provide
context['require'] = require
function aug(o, o2) {
for (var k in o2) k != 'noConflict' && k != '_VERSION' && (o[k] = o2[k])
return o
}
function boosh(s, r, els) {
// string || node || nodelist || window
if (typeof s == 'string' || s.nodeName || (s.length && 'item' in s) || s == window) {
els = ender._select(s, r)
els.selector = s
} else els = isFinite(s.length) ? s : [s]
return aug(els, boosh)
}
function ender(s, r) {
return boosh(s, r)
}
aug(ender, {
_VERSION: '0.3.6'
, fn: boosh // for easy compat to jQuery plugins
, ender: function (o, chain) {
aug(chain ? boosh : ender, o)
}
, _select: function (s, r) {
return (r || document).querySelectorAll(s)
}
})
aug(boosh, {
forEach: function (fn, scope, i) {
// opt out of native forEach so we can intentionally call our own scope
// defaulting to the current item and be able to return self
for (i = 0, l = this.length; i < l; ++i) i in this && fn.call(scope || this[i], this[i], i, this)
// return self for chaining
return this
},
$: ender // handy reference to self
})
ender.noConflict = function () {
context.$ = old
return this
}
if (typeof module !== 'undefined' && module.exports) module.exports = ender
// use subscript notation as extern for Closure compilation
context['ender'] = context['$'] = context['ender'] || ender
}(this);
// pakmanager:xtend
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
module.exports = extend
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target
}
provide("xtend", module.exports);
}(global));
// pakmanager:through
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data === null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}
provide("through", module.exports);
}(global));
// pakmanager:ap
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
exports = module.exports = ap;
function ap (args, fn) {
return function () {
var rest = [].slice.call(arguments)
, first = args.slice()
first.push.apply(first, rest)
return fn.apply(this, first);
};
}
exports.pa = pa;
function pa (args, fn) {
return function () {
var rest = [].slice.call(arguments)
rest.push.apply(rest, args)
return fn.apply(this, rest);
};
}
exports.apa = apa;
function apa (left, right, fn) {
return function () {
return fn.apply(this,
left.concat.apply(left, arguments).concat(right)
);
};
}
exports.partial = partial;
function partial (fn) {
var args = [].slice.call(arguments, 1);
return ap(args, fn);
}
exports.partialRight = partialRight;
function partialRight (fn) {
var args = [].slice.call(arguments, 1);
return pa(args, fn);
}
exports.curry = curry;
function curry (fn) {
return partial(partial, fn);
}
exports.curryRight = function curryRight (fn) {
return partial(partialRight, fn);
}
provide("ap", module.exports);
}(global));
// pakmanager:postgres-array
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
'use strict'
exports.parse = function (source, transform) {
return new ArrayParser(source, transform).parse()
}
function ArrayParser (source, transform) {
this.source = source
this.transform = transform || identity
this.position = 0
this.entries = []
this.recorded = []
this.dimension = 0
}
ArrayParser.prototype.isEof = function () {
return this.position >= this.source.length
}
ArrayParser.prototype.nextCharacter = function () {
var character = this.source[this.position++]
if (character === '\\') {
return {
value: this.source[this.position++],
escaped: true
}
}
return {
value: character,
escaped: false
}
}
ArrayParser.prototype.record = function (character) {
this.recorded.push(character)
}
ArrayParser.prototype.newEntry = function (includeEmpty) {
var entry
if (this.recorded.length > 0 || includeEmpty) {
entry = this.recorded.join('')
if (entry === 'NULL' && !includeEmpty) {
entry = null
}
if (entry !== null) entry = this.transform(entry)
this.entries.push(entry)
this.recorded = []
}
}
ArrayParser.prototype.parse = function (nested) {
var character, parser, quote
while (!this.isEof()) {
character = this.nextCharacter()
if (character.value === '{' && !quote) {
this.dimension++
if (this.dimension > 1) {
parser = new ArrayParser(this.source.substr(this.position - 1), this.transform)
this.entries.push(parser.parse(true))
this.position += parser.position - 2
}
} else if (character.value === '}' && !quote) {
this.dimension--
if (!this.dimension) {
this.newEntry()
if (nested) return this.entries
}
} else if (character.value === '"' && !character.escaped) {
if (quote) this.newEntry(true)
quote = !quote
} else if (character.value === ',' && !quote) {
this.newEntry()
} else {
this.record(character.value)
}
}
if (this.dimension !== 0) {
throw new Error('array dimension not balanced')
}
return this.entries
}
function identity (value) {
return value
}
provide("postgres-array", module.exports);
}(global));
// pakmanager:postgres-bytea
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
'use strict'
module.exports = function parseBytea (input) {
if (/^\\x/.test(input)) {
// new 'hex' style response (pg >9.0)
return new Buffer(input.substr(2), 'hex')
}
var output = ''
var i = 0
while (i < input.length) {
if (input[i] !== '\\') {
output += input[i]
++i
} else {
if (/[0-7]{3}/.test(input.substr(i + 1, 3))) {
output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8))
i += 4
} else {
var backslashes = 1
while (i + backslashes < input.length && input[i + backslashes] === '\\') {
backslashes++
}
for (var k = 0; k < Math.floor(backslashes / 2); ++k) {
output += '\\'
}
i += Math.floor(backslashes / 2) * 2
}
}
}
return new Buffer(output, 'binary')
}
provide("postgres-bytea", module.exports);
}(global));
// pakmanager:postgres-date
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
'use strict'
var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?/
var DATE = /^(\d{1,})-(\d{2})-(\d{2})$/
var TIME_ZONE = /([Z|+\-])(\d{2})?:?(\d{2})?:?(\d{2})?/
var BC = /BC$/
module.exports = function parseDate (isoDate) {
var matches = DATE_TIME.exec(isoDate)
if (!matches) {
// Force YYYY-MM-DD dates to be parsed as local time
return DATE.test(isoDate) ?
new Date(isoDate + ' 00:00:00') :
null
}
var isBC = BC.test(isoDate)
var year = parseInt(matches[1], 10)
var isFirstCentury = year > 0 && year < 100
year = (isBC ? '-' : '') + year
var month = parseInt(matches[2], 10) - 1
var day = matches[3]
var hour = parseInt(matches[4], 10)
var minute = parseInt(matches[5], 10)
var second = parseInt(matches[6], 10)
var ms = matches[7]
ms = ms ? 1000 * parseFloat(ms) : 0
var date
var offset = timeZoneOffset(isoDate)
if (offset != null) {
var utc = Date.UTC(year, month, day, hour, minute, second, ms)
date = new Date(utc - offset)
} else {
date = new Date(year, month, day, hour, minute, second, ms)
}
if (isFirstCentury) {
date.setUTCFullYear(year)
}
return date
}
// match timezones:
// Z (UTC)
// -05
// +06:30
var types = ['Z', '+', '-']
function timeZoneOffset (isoDate) {
var zone = TIME_ZONE.exec(isoDate.split(' ')[1])
if (!zone) return
var type = zone[1]
if (!~types.indexOf(type)) {
throw new Error('Unidentified time zone part: ' + type)
}
if (type === 'Z') {
return 0
}
var sign = type === '-' ? -1 : 1
var offset = parseInt(zone[2], 10) * 3600 +
parseInt(zone[3] || 0, 10) * 60 +
parseInt(zone[4] || 0, 10)
return offset * sign * 1000
}
provide("postgres-date", module.exports);
}(global));
// pakmanager:postgres-interval
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
'use strict'
var extend = require('xtend/mutable')
module.exports = PostgresInterval
function PostgresInterval (raw) {
if (!(this instanceof PostgresInterval)) {
return new PostgresInterval(raw)
}
extend(this, parse(raw))
}
var properties = ['seconds', 'minutes', 'hours', 'days', 'months', 'years']
PostgresInterval.prototype.toPostgres = function () {
return properties
.filter(this.hasOwnProperty, this)
.map(function (property) {
return this[property] + ' ' + property
}, this)
.join(' ')
}
var NUMBER = '([+-]?\\d+)'
var YEAR = NUMBER + '\\s+years?'
var MONTH = NUMBER + '\\s+mons?'
var DAY = NUMBER + '\\s+days?'
var TIME = '([+-])?(\\d\\d):(\\d\\d):(\\d\\d):?(\\d\\d\\d)?'
var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function (regexString) {
return '(' + regexString + ')?'
})
.join('\\s*'))
// Positions of values in regex match
var positions = {
years: 2,
months: 4,
days: 6,
hours: 9,
minutes: 10,
seconds: 11,
milliseconds: 12
}
// We can use negative time
var negatives = ['hours', 'minutes', 'seconds']
function parse (interval) {
if (!interval) return {}
var matches = INTERVAL.exec(interval)
var isNegative = matches[8] === '-'
return Object.keys(positions)
.reduce(function (parsed, property) {
var position = positions[property]
var value = matches[position]
// no empty string
if (!value) return parsed
value = parseInt(value, 10)
// no zeros
if (!value) return parsed
if (isNegative && ~negatives.indexOf(property)) {
value *= -1
}
parsed[property] = value
return parsed
}, {})
}
provide("postgres-interval", module.exports);
}(global));
// pakmanager:split
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
//filter will reemit the data if cb(err,pass) pass is truthy
// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'
var through = require('through')
var Decoder = require('string_decoder').StringDecoder
module.exports = split
//TODO pass in a function to map across the lines.
function split (matcher, mapper, options) {
var decoder = new Decoder()
var soFar = ''
var maxLength = options && options.maxLength;
var trailing = options && options.trailing === false ? false : true
if('function' === typeof matcher)
mapper = matcher, matcher = null
if (!matcher)
matcher = /\r?\n/
function emit(stream, piece) {
if(mapper) {
try {
piece = mapper(piece)
}
catch (err) {
return stream.emit('error', err)
}
if('undefined' !== typeof piece)
stream.queue(piece)
}
else
stream.queue(piece)
}
function next (stream, buffer) {
var pieces = ((soFar != null ? soFar : '') + buffer).split(matcher)
soFar = pieces.pop()
if (maxLength && soFar.length > maxLength)
stream.emit('error', new Error('maximum buffer reached'))
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i]
emit(stream, piece)
}
}
return through(function (b) {
next(this, decoder.write(b))
},
function () {
if(decoder.end)
next(this, decoder.end())
if(trailing && soFar != null)
emit(this, soFar)
this.queue(null)
})
}
provide("split", module.exports);
}(global));
// pakmanager:buffer-writer
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
//binary data writer tuned for creating
//postgres message packets as effeciently as possible by reusing the
//same buffer to avoid memcpy and limit memory allocations
var Writer = module.exports = function(size) {
this.size = size || 1024;
this.buffer = Buffer(this.size + 5);
this.offset = 5;
this.headerPosition = 0;
};
//resizes internal buffer if not enough size left
Writer.prototype._ensure = function(size) {
var remaining = this.buffer.length - this.offset;
if(remaining < size) {
var oldBuffer = this.buffer;
this.buffer = new Buffer(oldBuffer.length + size);
oldBuffer.copy(this.buffer);
}
};
Writer.prototype.addInt32 = function(num) {
this._ensure(4);
this.buffer[this.offset++] = (num >>> 24 & 0xFF);
this.buffer[this.offset++] = (num >>> 16 & 0xFF);
this.buffer[this.offset++] = (num >>> 8 & 0xFF);
this.buffer[this.offset++] = (num >>> 0 & 0xFF);
return this;
};
Writer.prototype.addInt16 = function(num) {
this._ensure(2);
this.buffer[this.offset++] = (num >>> 8 & 0xFF);
this.buffer[this.offset++] = (num >>> 0 & 0xFF);
return this;
};
//for versions of node requiring 'length' as 3rd argument to buffer.write
var writeString = function(buffer, string, offset, len) {
buffer.write(string, offset, len);
};
//overwrite function for older versions of node
if(Buffer.prototype.write.length === 3) {
writeString = function(buffer, string, offset, len) {
buffer.write(string, offset);
};
}
Writer.prototype.addCString = function(string) {
//just write a 0 for empty or null strings
if(!string) {
this._ensure(1);
} else {
var len = Buffer.byteLength(string);
this._ensure(len + 1); //+1 for null terminator
writeString(this.buffer, string, this.offset, len);
this.offset += len;
}
this.buffer[this.offset++] = 0; // null terminator
return this;
};
Writer.prototype.addChar = function(c) {
this._ensure(1);
writeString(this.buffer, c, this.offset, 1);
this.offset++;
return this;
};
Writer.prototype.addString = function(string) {
string = string || "";
var len = Buffer.byteLength(string);
this._ensure(len);
this.buffer.write(string, this.offset);
this.offset += len;
return this;
};
Writer.prototype.getByteLength = function() {
return this.offset - 5;
};
Writer.prototype.add = function(otherBuffer) {
this._ensure(otherBuffer.length);
otherBuffer.copy(this.buffer, this.offset);
this.offset += otherBuffer.length;
return this;
};
Writer.prototype.clear = function() {
this.offset = 5;
this.headerPosition = 0;
this.lastEnd = 0;
};
//appends a header block to all the written data since the last
//subsequent header or to the beginning if there is only one data block
Writer.prototype.addHeader = function(code, last) {
var origOffset = this.offset;
this.offset = this.headerPosition;
this.buffer[this.offset++] = code;
//length is everything in this packet minus the code
this.addInt32(origOffset - (this.headerPosition+1));
//set next header position
this.headerPosition = origOffset;
//make space for next header
this.offset = origOffset;
if(!last) {
this._ensure(5);
this.offset += 5;
}
};
Writer.prototype.join = function(code) {
if(code) {
this.addHeader(code, true);
}
return this.buffer.slice(code ? 0 : 5, this.offset);
};
Writer.prototype.flush = function(code) {
var result = this.join(code);
this.clear();
return result;
};
provide("buffer-writer", module.exports);
}(global));
// pakmanager:generic-pool
(function (context) {
var module = { exports: {} }, exports = module.exports
, $ = require("ender")
;
var PriorityQueue = function(size) {
var me = {}, slots, i, total = null;
// initialize arrays to hold queue elements
size = Math.max(+size | 0, 1);
slots = [];
for (i = 0; i < size; i += 1) {
slots.push([]);
}
// Public methods
me.size = function () {
var i;
if (total === null) {
total = 0;
for (i = 0; i < size; i += 1) {
total += slots[i].length;
}
}
return total;
};
me.enqueue = function (obj, priority) {
var priorityOrig;
// Convert to integer with a default value of 0.
priority = priority && + priority | 0 || 0;
// Clear cache for total.
total = null;
if (priority) {
priorityOrig = priority;
if (priority < 0 || priority >= size) {
priority = (size - 1);
// put obj at the end of the line
console.error("invalid priority: " + priorityOrig + " must be between 0 and " + priority);
}
}
slots[priority].push(obj);
};
me.dequeue = function (callback) {
var obj = null, i, sl = slots.length;
// Clear cache for total.
total = null;
for (i = 0; i < sl; i += 1) {
if (slots[i].length) {
obj = slots[i].shift();
break;
}
}
return obj;
};
return me;
};
/**
* Generate an Object pool with a specified `factory`.
*
* @param {Object} factory
* Factory to be used for generating and destorying the items.
* @param {String} factory.name
* Name of the factory. Serves only logging purposes.
* @param {Function} factory.create
* Should create the item to be acquired,
* and call it's first callback argument with the generated item as it's argument.
* @param {Function} factory.destroy
* Should gently close any resources that the item is using.
* Called before the items is destroyed.
* @param {Function} factory.validate
* Should return true if connection is still valid and false
* If it should be removed from pool. Called before item is
* acquired from pool.
* @param {Number} factory.max
* Maximum number of items that can exist at the same time. Default: 1.
* Any further acquire requests will be pushed to the waiting list.
* @param {Number} factory.min
* Minimum number of items in pool (including in-use). Default: 0.
* When the pool is created, or a resource destroyed, this minimum will
* be checked. If the pool resource count is below the minimum, a new
* resource will be created and added to the pool.
* @param {Number} factory.idleTimeoutMillis
* Delay in milliseconds after the idle items in the pool will be destroyed.
* And idle item is that is not acquired yet. Waiting items doesn't count here.
* @param {Number} factory.reapIntervalMillis
* Cleanup is scheduled in every `factory.reapIntervalMillis` milliseconds.
* @param {Boolean|Function} factory.log
* Whether the pool should log activity. If function is specified,
* that will be used instead. The function expects the arguments msg, loglevel
* @param {Number} factory.priorityRange
* The range from 1 to be treated as a valid priority
* @param {RefreshIdle} factory.refreshIdle
* Should idle resources be destroyed and recreated every idleTimeoutMillis? Default: true.
* @param {Bool} [factory.returnToHead=false]
* Returns released object to head of available objects list
* @returns {Object} An Object pool that works with the supplied `factory`.
*/
exports.Pool = function (factory) {
var me = {},
idleTimeoutMillis = factory.idleTimeoutMillis || 30000,
reapInterval = factory.reapIntervalMillis || 1000,
refreshIdle = ('refreshIdle' in factory) ? factory.refreshIdle : true,
availableObjects = [],
waitingClients = new PriorityQueue(factory.priorityRange || 1),
count = 0,
removeIdleScheduled = false,
removeIdleTimer = null,
draining = false,
returnToHead = factory.returnToHead || false,
// Prepare a logger function.
log = factory.log ?
(function (str, level) {
if (typeof factory.log === 'function') {
factory.log(str, level);
}
else {
console.log(level.toUpperCase() + " pool " + factory.name + " - " + str);
}
}
) :
function () {};
factory.validate = factory.validate || function() { return true; };
factory.max = parseInt(factory.max, 10);
factory.min = parseInt(factory.min, 10);
factory.max = Math.max(isNaN(factory.max) ? 1 : factory.max, 1);
factory.min = Math.min(isNaN(factory.min) ? 0 : factory.min, factory.max-1);
///////////////
/**
* Request the client to be destroyed. The factory's destroy handler
* will also be called.
*
* This should be called within an acquire() block as an alternative to release().
*
* @param {Object} obj
* The acquired item to be destoyed.
*/
me.destroy = function(obj) {
count -= 1;
availableObjects = availableObjects.filter(function(objWithTimeout) {
return (objWithTimeout.obj !== obj);
});
factory.destroy(obj);
ensureMinimum();
};
/**
* Checks and removes the available (idle) clients that have timed out.
*/
function removeIdle() {
var toRemove = [],
now = new Date().getTime(),
i,
al, tr,
timeout;
removeIdleScheduled = false;
// Go through the available (idle) items,
// check if they have timed out
for (i = 0, al = availableObjects.length; i < al && (refreshIdle || (count - factory.min > toRemove.length)); i += 1) {
timeout = availableObjects[i].timeout;
if (now >= timeout) {
// Client timed out, so destroy it.
log("removeIdle() destroying obj - now:" + now + " timeout:" + timeout, 'verbose');
toRemove.push(availableObjects[i].obj);
}
}
for (i = 0, tr = toRemove.length; i < tr; i += 1) {
me.destroy(toRemove[i]);
}
// Replace the available items with the ones to keep.
al = availableObjects.length;
if (al > 0) {
log("availableObjects.length=" + al, 'verbose');
scheduleRemoveIdle();
} else {
log("removeIdle() all objects removed", 'verbose');
}
}
/**