UNPKG

1.12 kBJavaScriptView Raw
1
2var Type = require('./type');
3function Dup(){
4 this.cache = {};
5}
6Dup.prototype.track = function(id){
7 this.cache[id] = Type.time.is();
8 if (!this.to) {
9 this.gc(); // Engage GC.
10 }
11 return id;
12};
13Dup.prototype.check = function(id){
14 // Have we seen this ID recently?
15 return Type.obj.has(this.cache, id)? this.track(id) : false; // Important, bump the ID's liveliness if it has already been seen before - this is critical to stopping broadcast storms.
16}
17Dup.prototype.gc = function(){
18 var de = this, now = Type.time.is(), oldest = now, maxAge = 5 * 60 * 1000;
19 // TODO: Gun.scheduler already does this? Reuse that.
20 Type.obj.map(de.cache, function(time, id){
21 oldest = Math.min(now, time);
22 if ((now - time) < maxAge){ return }
23 Type.obj.del(de.cache, id);
24 });
25 var done = Type.obj.empty(de.cache);
26 if(done){
27 de.to = null; // Disengage GC.
28 return;
29 }
30 var elapsed = now - oldest; // Just how old?
31 var nextGC = maxAge - elapsed; // How long before it's too old?
32 de.to = setTimeout(function(){ de.gc() }, nextGC); // Schedule the next GC event.
33}
34module.exports = Dup;
35
\No newline at end of file