db.getObjectField('global', 'userCount', function(err, numUsers) {
		var	cacheOpts = {
				max: 50,
				maxAge: 1000 * 60 * 60 * 24
			};

		if (!err && numUsers > 0) {
			cacheOpts.max = Math.floor(numUsers / 20);
		}
		lang_cache = cache(cacheOpts);
	});
Beispiel #2
0
function HNItemCache (options) {
  EventEmitter.call(this);

  options || (options = {});
  defaults(options, {
    maxAge : ms('1m'),
    max    : 10000
  });

  this.reqs  = {};
  this.cache = LRU(options);
}
Beispiel #3
0
App.prototype.initAuthCache = function () {
    var cacheOptions = this.config.authCache || {};

    if (cacheOptions.max === undefined) {
        cacheOptions.max = 100;
    }
    if (cacheOptions.maxAge === undefined) {
        cacheOptions.maxAge = 2 * 60 * 1000;
    }

    this.authCache = LRU(cacheOptions);
};
 createCache(breaker, options) {
   return lruCache({
     max: options.cacheMaxEntries || 5000,
     length: function calcLength(n, key) {
       return n * 2 + key.length;
     },
     dispose: function cacheDispose(key) {
       breaker.logger.silly('Breaker::cache Cache dispose:', key);
     },
     maxAge: options.cacheMaxAge || 1000 * 60 * 60 // 60 secs * 60 mins = 1 hour
   });
 }
Beispiel #5
0
function Master() {

    this.storage = lru_cache({
        max: 100000,
        maxAge: 1000 * 60 * 60 * 8 // 8h
    });

    //this.storage = {};
    this.hub = null;
    this.redis = null;
    this.tcpClients = {};
}
Beispiel #6
0
module.exports = function init(options) {
  var size = _.get(options, 'size') || 1000;
  var cache = lruCache({ max: size });

  return {
    incrementAndGet: function(key, next) {
      var redeliveries = cache.get(key) + 1 || 1;
      cache.set(key, redeliveries);
      next(null, redeliveries);
    },
  };
};
Beispiel #7
0
WISERedisCache.prototype.set = function(query, value) {
  var cache = this.cache[query.typeName];

  if (!cache) {
    cache = this.cache[query.typeName] = LRU({max: this.cacheSize});
  }

  cache.set(query.value, value);

  var data = BSON.serialize(value, false, true, false);
  this.client.set(query.typeName + "-" + query.value, data);
};
  constructor() {
    this._flowConfigDirCache = new ConfigCache('.flowconfig');

    this._flowExecInfoCache = LRU({
      max: 10,
      maxAge: 1000 * 30, // 30 seconds
    });

    this._disposables = new CompositeDisposable();

    this._observeSettings();
  }
var serve = function() {
  var cache = LRU(200);
  var server = http.createServer(function(request, response) {
    request.connection.unref();

    var id = request.url.replace(/^\//, '');
    var html = cache.get(id);

    if(!html) {
      response.writeHead(404);
      response.end();
    } else {
      response.writeHead(200, {
        'Content-Type': 'text/html',
        'Content-Length': html.length
      });
      response.end(html);
    }
  });

  var listen = thunky(function(cb) {
    server.listen(0, function() {
      server.unref();

      var port = server.address().port;
      cb(null, 'http://localhost:' + port);
    });
  });

  var set = function(id, html, cb) {
    listen(function(err, base) {
      if(err) return cb(err);
      cache.set(id, html);
      cb(null, base + '/' + id);
    });
  };

  var safeDestroy = function(cb) {
    try {
      // throws if server is not started
      server.destroy(cb);
    } catch(err) {
      if(cb) cb();
    }
  };

  server.set = set;
  server.safeDestroy = safeDestroy;
  serverDestroy(server);

  return server;
};
Beispiel #10
0
function createRenderer (bundle, options) {
  // https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
  return createBundleRenderer(bundle, Object.assign(options, {
    cache: LRU({
      max: 1000,
      maxAge: 1000 * 60 * 15
    }),
    // this is only needed when vue-server-renderer is npm-linked
    basedir: resolve('../dist'),
    // recommended for performance
    runInNewContext: false
  }))
}
Beispiel #11
0
function BlockController(options) {
  var self = this;
  this.node = options.node;
  this.transactionService = options.transactionService;

  this.blockSummaryCache = LRU(options.blockSummaryCacheSize || BlockController.DEFAULT_BLOCKSUMMARY_CACHE_SIZE);
  this.blockCacheConfirmations = 6;
  this.blockCache = LRU(options.blockCacheSize || BlockController.DEFAULT_BLOCK_CACHE_SIZE);

  this.poolStrings = {};
  pools.forEach(function(pool) {
    pool.searchStrings.forEach(function(s) {
      self.poolStrings[s] = {
        poolName: pool.poolName,
        url: pool.url
      };
    });
  });

  this.common = new Common({ log: this.node.log });

}
Beispiel #12
0
function Cache(options) {
  if (typeof(options) !== 'object')
    throw new TypeError('options (object) required');

  this._cache = LRU(options.size || 1000);
  this._age = (options.age || 300) * 1000;

  var self = this;
  this.__defineGetter__('age', function() { return self._age / 1000; });
  this.__defineSetter__('age', function(a) {
    self._age = a * 1000;
  });
}
Beispiel #13
0
/**
 *
 * @param config
 * @param [instrument]
 * @param {callback} [cb]
 */
function memoryCacheLayer(config, instrument, cb) {
  if(!instrument) {
    this.instrument = instrument.namespace('cache-layer.memory');
  }

  this.cache = lru({
    max: config.max || 200
  });

  if(cb) {
    cb(null);
  }
}
Beispiel #14
0
/*!
 * \class Perishable Version Vector with Exceptions
 * \brief objet that represents a version vector with exceptions. However, 
 * exceptions are slowly disappearing over time. Eventually, the exceptions
 * are considered as delivered messages. Also, each entry of the vector also
 * tends to disappear if it has not been used for a while. This kind of vector
 * is usefull in contexts not fully asynchronous, i.e., there is a bounded 
 * period of time between the generation of a message and its reception.
 * \param uid the unique site identifier holding this version vector
 * \param options the options that intialize the perishable paramters. For more
 * informations, check the lru-cache module.
 */
function PVVwE(uid, options){
    // #1 initialize the underlying parameters
    // #1a the vector of perishable data
    this.options = options || { maxAge: 1000*60*60 }; // default 1h
    this.vector = LRU(this.options);
    // #1b the local data which are not perishable
    this.local = {e:uid, v:0};
    // #2 regularly discard stale data
    var self = this;
    setInterval(function(){
	self.vector.forEach(function(value,key,cache){self.vector.get(key);});
    }, this.options.maxAge);
};
Beispiel #15
0
///--- API

/**
 * Router class handles mapping of http verbs and a regexp path,
 * to an array of handler functions.
 * @class
 * @public
 * @param  {Object} options an options object
 */
function Router(options) {
    assert.object(options, 'options');
    assert.object(options.log, 'options.log');

    EventEmitter.call(this);

    this.cache = LRU({max: 100});
    this.contentType = options.contentType || [];

    if (!Array.isArray(this.contentType)) {
        this.contentType = [this.contentType];
    }
    assert.arrayOfString(this.contentType, 'options.contentType');

    this.strict = Boolean(options.strictRouting);
    this.log = options.log;
    this.mounts = {};
    this.name = 'RestifyRouter';

    // A list of methods to routes
    this.routes = {
        DELETE: [],
        GET: [],
        HEAD: [],
        OPTIONS: [],
        PATCH: [],
        POST: [],
        PUT: []
    };

    // So we can return 405 vs 404, we maintain a reverse mapping of URLs
    // to method
    this.reverse = {};

    this.versions = options.versions || options.version || [];

    if (!Array.isArray(this.versions)) {
        this.versions = [this.versions];
    }
    assert.arrayOfString(this.versions, 'options.versions');

    this.versions.forEach(function (v) {
        if (semver.valid(v)) {
            return (true);
        }

        throw new InvalidArgumentError('%s is not a valid semver', v);
    });
    this.versions.sort();

}
Beispiel #16
0
function KinesisStream(options) {
  if (typeof options == 'string') options = {name: options}
  if (!options || !options.name) throw new Error('A stream name must be given')
  stream.Duplex.call(this, {objectMode: true})
  this.options = options
  this.name = options.name
  this.writeConcurrency = options.writeConcurrency || 1
  this.sequenceCache = lruCache(options.cacheSize || 1000)
  this.currentWrites = 0
  this.buffer = []
  this.paused = true
  this.fetching = false
  this.shards = []
}
Beispiel #17
0
module.exports = function (options) {
  var seneca = this
  var extend = seneca.util.deepextend

  opts = extend(opts, options)
  opts.cache = Cache(options.size)

  seneca.add({role: opts.role, cmd: 'get'}, get)
  seneca.add({role: opts.role, res: 'part'}, update)

  return {
    name: opts.plugin
  }
}
Beispiel #18
0
function Reader(db, opts) {
  opts = opts || {};
  opts.cache = opts.cache || {};
  opts.cache.max = opts.cache.max || 50000;
  opts.cache.maxAge = opts.cache.maxAge || 60 * 60 * 1000; // 1hr

  this.cache = LRU(opts.cache);

  this.db = db;

  this.metadata = new Metadata(this.db);
  this.decoder = new Decoder(this.db, this.metadata.searchTreeSize + DATA_SECTION_SEPARATOR_SIZE);

  this.setupNodeReaderFn(this.metadata.recordSize);
}
Beispiel #19
0
function SecurityService(opts) {

    this.log = opts.logger.createLogger('Security');
    this.log.$$TRACE('construct(%j)', opts);

    if (!opts.groupCache)
    opts.groupCache = {
        max: 1000,
        maxAge: 0
    }

    if (!opts.userCache)
    opts.userCache = {
        max: 1000,
        maxAge: 0
    }

    this.options = opts;

    this.__groupCache = LRU(this.options.groupCache);
    this.__userCache = LRU(this.options.userCache);
    this.__passwordCache = LRU(this.options.userCache);//alongside the user cache

}
Beispiel #20
0
// Creates a new SparqlDatasource
function SparqlDatasource(options) {
  if (!(this instanceof SparqlDatasource))
    return new SparqlDatasource(options);
  Datasource.call(this, options);
  this._countCache = LRU({ max: 1000, maxAge: 1000 * 60 * 60 * 3 });

  // Set endpoint URL and default graph
  options = options || {};
  this._endpoint = this._endpointUrl = (options.endpoint || '').replace(/[\?#][^]*$/, '');

  if (!options.defaultGraph)
    this._endpointUrl += '?query=';
  else
    this._endpointUrl += '?default-graph-uri=' + encodeURIComponent(options.defaultGraph) + '&query=';
}
Beispiel #21
0
function CoAPServer(options, listener) {
  if (!(this instanceof CoAPServer)) {
    return new CoAPServer(options)
  }

  if (typeof options === 'function') {
    listener = options
    options = null
  }

  if (!options)
    options = {}

  this._options = options
  this._proxiedRequests = {}

  this._middlewares = [
    middlewares.parseRequest
  ]

  if (options.proxy) {
    this._middlewares.push(middlewares.proxyRequest)
    this._middlewares.push(middlewares.handleProxyResponse)
  }

  this._middlewares.push(middlewares.handleServerRequest)

  // We use an LRU cache for the responses to avoid
  // DDOS problems.
  // max packet size is 1280
  // 32 MB / 1280 = 26214
  // The max lifetime is roughly 200s per packet.
  // Which gave us 131 packets/second guarantee
  this._lru = LRU({
      max: options.cacheSize || (32768 * 1024)
    , length: function(n) { return n.length }
    , maxAge: parameters.exchangeLifetime
    , dispose:  function(key, value) {
                  if (value.sender)
                    value.sender.reset()
                }
  })

  this._series = series()

  if (listener)
    this.on('request', listener)
}
Beispiel #22
0
  constructor(nuxt, renderer) {
    this.nuxt = nuxt
    this.renderer = renderer
    this.options = nuxt.options
    this.vueRenderer = VueServerRenderer.createRenderer()
    this.cache = LRU({})

    // Add VueMeta to Vue (this is only for SPA mode)
    // See lib/app/index.js
    Vue.use(VueMeta, {
      keyName: 'head',
      attribute: 'data-n-head',
      ssrAttribute: 'data-n-head-ssr',
      tagIDKeyName: 'hid'
    })
  }
Beispiel #23
0
//TODO: should this be in utils?
function cache(f, maxSize) {
  var c = LRU(maxSize);
  var cf = function() {
    var args = Array.prototype.slice.call(arguments);
    var stringedArgs = util.serialize(args);
    if (c.has(stringedArgs)) {
      return c.get(stringedArgs);
    } else {
      //TODO: check for recursion, cache size, etc?
      var r = f.apply(this, args);
      c.set(stringedArgs, r);
      return r
    }
  }
  return cf
}
Beispiel #24
0
Cache.prototype._initLru = function (cb) {
  var options = this.options;
  var self = this;
  this.cache = lru(options);
  this.storage = {
    get: function (key, cb) {
      return cb && cb(null, self.cache.get(key) || null);
    },
    setex: function (key, expire, value, cb) {
      self.cache.set(key, value);
      return cb && cb(null);
    },
    del: function (key, cb) {
      for (var i = 0; i < key.length; i++) {
        self.cache.del(key[i]);
      }
      return cb && cb(null);
    },
    end: function (cb) {
      self.cache.reset();
      return cb && cb();
    },
    flushdb: function (cb) {
      self.cache.reset();
      return cb && cb(null);
    },
    smembers: function (key, cb) {
      return cb(null, Object.keys(self.keySet || {}));
    },
    sadd: function (setKey, key, cb) {
      self.keySet = self.keySet || {};
      self.keySet[key] = 1;
      return cb(null);
    },
    srem: function() {
      var len = arguments.length;
      var keySet = self.keySet;
      for (var i = 1; i < len - 1; i++) {
        delete keySet[arguments[i]];
      }
      arguments[arguments.length - 1](null);
    }
  }
  return cb && cb(null);
}
Beispiel #25
0
function Compile(compilers) {
    this.compilersById = {};
    var self = this;
    compilers.forEach(function (compiler) {
        self.compilersById[compiler.id] = compiler;
    });
    this.okOptions = new RegExp(gccProps('optionsWhitelistRe', '.*'));
    this.badOptions = new RegExp(gccProps('optionsBlacklistRe'));
    this.cache = LRU({
        max: gccProps('cacheMb') * 1024 * 1024,
        length: function (n) {
            return JSON.stringify(n).length;
        }
    });
    this.cacheHits = 0;
    this.cacheMisses = 0;
    this.compileQueue = new Queue(gccProps("maxConcurrentCompiles", 1), Infinity);
}
Beispiel #26
0
function Chaps(opts) {
  if (opts.cache !== false || opts.LRU) {
    opts.cache = true;
    opts.LRU = _.defaults(opts.LRU || {}, {
      // default LRU values
      length: function() {
        return 1;
      },
      max: 100,
      maxAge: 60000 // cache for 1 minute
    });
    /* eslint new-cap:0 */
    this.cache = LRU(opts.LRU);
  }

  this.opts = opts;
  return this;
}
Beispiel #27
0
    test('`clearCache` work properly, LRU', function () {
        var expected = '<p>Old</p>'
            , oldCache = ejs.cache
            , file = __dirname + '/tmp/clearCache.ejs'
            , options = {cache: true, filename: file}
            , out;

        ejs.cache = LRU();

        out = ejs.render('<p>Old</p>', {}, options);
        assert.equal(out, expected);
        ejs.clearCache();
        expected = '<p>New</p>';
        out = ejs.render('<p>New</p>', {}, options);
        assert.equal(out, expected);

        ejs.cache = oldCache;
    });
Beispiel #28
0
    it('should cache the response', (done) => {
      const c = cache()
      const app = createApp(c)
      app.use(function * (next) {
        if (yield this.cashed()) return
        this.body = new Buffer('lol')
      })

      request(app.listen())
      .get('/')
      .expect(200)
      .expect('lol', (err, res) => {
        if (err) return done(err)

        assert.equal(c.get('/').body.toString('utf8'), 'lol')
        done()
      })
    })
Beispiel #29
0
    it('should not cache the response', (done) => {
      const c = cache()
      const app = createApp(c)
      app.use(function * (next) {
        if (yield this.cashed()) return
        this.body = 'lol'
      })

      request(app.listen())
      .post('/')
      .expect('lol')
      .expect(200, (err, res) => {
        if (err) return done(err)

        assert(!c.get('/'))
        done()
      })
    })
Beispiel #30
0
module.exports = function(fn, options) {

  var usesNext;
  if (typeof options === 'undefined') {
    options = 10000;
  } else if (typeof options === 'object' && options.next) {
    usesNext = options.next;
    delete options.next;
  }

  var cache = lru(options);

  if (usesNext) {
    /* asynchronous function, with callback as last argument */
    return function() {
      var args = Array.prototype.slice.call(arguments);
      var next = args.pop();
      var key = args.join('\x01');
      if (cache.has(key)) {
        return next(cache.get(key));
      } else {
        args.push(function() {
          cache.set(key, arguments);
          return next.apply(null, arguments);
        });
        fn.apply(null, args);
      }
    };
  } else {
    /* synchronous function */
    return function() {
      var args = Array.prototype.slice.call(arguments);
      var key = args.join('\x01');
      var results;
      if (cache.has(key)) {
        results = cache.get(key);
      } else {
        results = fn.apply(null, args);
        cache.set(key, results);
      }
      return results;
    };
  }
};