Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

Commit ffda23b

Browse files
committed
Added 'maxUses' parameter to automatically purge instances that have been used more than a specified number of times
1 parent ba68257 commit ffda23b

2 files changed

Lines changed: 24 additions & 4 deletions

File tree

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,14 @@ import createPhantomPool from 'phantom-pool'
6363
const pool = createPhantomPool({
6464
max: 10, // default
6565
min: 2, // default
66-
// specifies how long a resource can stay idle in pool before being removed
66+
// how long a resource can stay idle in pool before being removed
6767
idleTimeoutMillis: 30000, // default.
68+
// maximum number of times an individual resource can be reused before being destroyed; set to 0 to disable
69+
maxUses: 50, // default
70+
// function to validate an instance prior to use; see https://github.com/coopernurse/node-pool#createpool
71+
validator: () => Promise.resolve(true), // defaults to always resolving true
72+
// validate resource before borrowing; required for `maxUses and `validator`
73+
testOnBorrow: true // default
6874
// For all opts, see opts at https://github.com/coopernurse/node-pool#createpool
6975
phantomArgs: [['--ignore-ssl-errors=true', '--disk-cache=true'], {
7076
logLevel: 'debug',

src/index.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,37 @@ export default ({
1010
min = 2,
1111
// specifies how long a resource can stay idle in pool before being removed
1212
idleTimeoutMillis = 30000,
13+
// specifies the maximum number of times a resource can be reused before being destroyed
14+
maxUses = 50,
15+
testOnBorrow = true,
1316
phantomArgs = [],
14-
validator,
17+
validator = () => Promise.resolve(true),
1518
...otherConfig
1619
} = {}) => {
1720
// TODO: randomly destroy old instances to avoid resource leak?
1821
const factory = {
19-
create: () => phantom.create(...phantomArgs),
22+
create: () => phantom.create(...phantomArgs)
23+
.then(instance => {
24+
instance.useCount = 0
25+
return instance
26+
}),
2027
destroy: (instance) => instance.exit(),
21-
validate: validator,
28+
validate: (instance) => validator(instance)
29+
.then(valid => Promise.resolve(valid && (maxUses <= 0 || instance.useCount < maxUses))),
2230
}
2331
const config = {
2432
max,
2533
min,
2634
idleTimeoutMillis,
35+
testOnBorrow,
2736
...otherConfig,
2837
}
2938
const pool = genericPool.createPool(factory, config)
39+
const genericAcquire = pool.acquire.bind(pool)
40+
pool.acquire = () => genericAcquire().then(r => {
41+
r.useCount += 1
42+
return r
43+
})
3044
pool.use = (fn) => {
3145
let resource
3246
return pool.acquire()

0 commit comments

Comments
 (0)