evict.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. ;(function(){
  2. var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
  3. var ev = {}, empty = {}, u;
  4. Gun.on('opt', function(root){
  5. this.to.next(root);
  6. if(root.once){ return }
  7. if(typeof process == 'undefined'){ return }
  8. var util = process.memoryUsage, heap;
  9. if(!util){ return }
  10. try{ heap = require('v8').getHeapStatistics }catch(e){}
  11. if(!heap){ return }
  12. ev.max = parseFloat(root.opt.memory || (heap().heap_size_limit / 1024 / 1024) || process.env.WEB_MEMORY || 1399) * 0.8; // max_old_space_size defaults to 1400 MB. Note: old space !== memory space though. // KEEPING USED_HEA_SIZE < HEAP_SIZE_LIMIT ONLY THING TO BE BELOW TO PREVENT CRASH!
  13. setInterval(check, 1000);
  14. function check(){
  15. var used = util().rss / 1024 / 1024;
  16. var hused = heap().used_heap_size / 1024 / 1024;
  17. if(hused < ev.max && used < ev.max){ return }
  18. //if(used < ev.max){ return }
  19. console.STAT && console.STAT('evict memory:', hused.toFixed(), used.toFixed(), ev.max.toFixed());
  20. GC();//setTimeout(GC, 1);
  21. }
  22. function GC(){
  23. var S = +new Date;
  24. var souls = Object.keys(root.graph||empty);
  25. var toss = Math.ceil(souls.length * 0.01);
  26. //var S = +new Date;
  27. Gun.list.map(souls, function(soul){
  28. if(--toss < 0){ return }
  29. root.$.get(soul).off();
  30. });
  31. root.dup.drop(1000 * 9); // clean up message tracker
  32. console.STAT && console.STAT(S, +new Date - S, 'evict');
  33. }
  34. /*
  35. root.on('in', function(msg){
  36. this.to.next(msg);
  37. if(msg.get){
  38. return;
  39. }
  40. Gun.graph.is(msg, function(node, soul){
  41. var meta = (root.next||empty)[soul];
  42. if(!meta){ return }
  43. Gun.node.is(node, function(data, key){
  44. });
  45. });
  46. });
  47. */
  48. });
  49. }());