-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresource-pool.js
58 lines (53 loc) · 1.43 KB
/
resource-pool.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
const async_hooks = require("async_hooks");
class ResourcePool {
constructor() {
this._sessions = {};
this._subsessions = {};
this._activeSessionId = null;
this._initHook();
}
_initHook() {
this._hook = async_hooks
.createHook({
init: asyncId => {
if (this._activeSessionId) {
this._subsessions[asyncId] = this._activeSessionId;
this._sessions[this._activeSessionId]._refs.add(asyncId);
}
},
before: asyncId => {
if (this._sessions[asyncId]) {
this._activeSessionId = asyncId;
} else if (this._subsessions[asyncId]) {
this._activeSessionId = this._subsessions[asyncId];
}
},
after: asyncId => {
this._activeSessionId = null;
},
destroy: asyncId => {
if (this._sessions[asyncId]) {
for (const ref of this._sessions[asyncId]._refs) {
delete this._subsessions[ref];
}
delete this._sessions[asyncId];
}
delete this._subsessions[asyncId];
}
})
.enable();
}
_register(resource) {
this._sessions[resource.asyncId()] = {
resource,
_refs: new Set()
};
}
getCurrentResource() {
if (this._sessions[this._activeSessionId]) {
return this._sessions[this._activeSessionId].resource;
}
return null;
}
}
module.exports = ResourcePool;