Skip to content

Commit

Permalink
Initial commit, cache for synchronous modules and apis
Browse files Browse the repository at this point in the history
  • Loading branch information
jtblin committed Mar 26, 2014
0 parents commit 3281681
Show file tree
Hide file tree
Showing 8 changed files with 382 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea/
.DS_Store
.DS_Store?
node_modules/
43 changes: 43 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
Copyright (c) Jerome Touffe-Blin ("Author")
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The ISC License

Copyright (c) Isaac Z. Schlueter

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# sync-cache

Cache for synchronous modules e.g. using Fibers based on [Isaac's AsyncCache](https://github.com/isaacs/async-cache).
By default use [lru-cache](https://github.com/isaacs/node-lru-cache) but can be passed any store that follows a simple api.

## Usage

npm install sync-cache --save

```js
var SyncCache = require('sync-cache');
var client = require('./my-sync-module');
var cache = new SyncCache({ max: 1000, maxAge: 1000*60*60, load: client.find });

// ...

var value = cache.get(params);
// Do something with value
```

## Options

- `load` function to execute when no item is found in the cache
- `max` number of items to cache (passed to `lru-cache` or configured cache store), defaults **Infinity**
- `maxAge` maximum number of milliseconds to keep items, defaults **null**
- `stale` boolean to indicate if cache should return stale items (`lru-cache`),default **false**
- `store` cache store object, default **lru-cache**

## API

### get (key)

Returns an item from the cache. If the item is not found, call the load handler to retrieve the item and
save the item in the cache.

### set (key, value)

Save the value in the cache for key.

### del (key)

Delete an item from the cache.

### reset ()

Remove all items from the cache.
**Note** support varies with underlying cache stores, e.g. not possible with `sync-memcached-store`.

### has (key)

Check if a key exists without returning the value.
**Note** support varies with underlying cache stores, e.g. it is the same as a `get` with `sync-memcached-store`.

### peek (key)

Calls underlying cache store `peek` method.
**Note** support varies with underlying cache stores, e.g. not possible with `sync-memcached-store`.

## Cache stores

To create a new cache store for SyncCache, it must support the same API i.e. get, has, set, del, reset, has, peek.
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "sync-cache",
"version": "0.0.1",
"description": "Cache for synchronous modules e.g. using Fibers based on Isaac's AsyncCache",
"main": "sync-cache.js",
"scripts": {
"test": "NODE_ENV=test mocha -w test/"
},
"keywords": [
"cache",
"lru",
"sync",
"syncho",
"fibers"
],
"repository": {
"type": "git",
"url": "https://github.com/jtblin/sync-cache"
},
"author": "Jerome Touffe-Blin <jtblin@gmail.com>",
"license": "BSD-2-Clause",
"dependencies": {
"lru-cache": "~2.5.0"
},
"devDependencies": {
"mocha": "~1.18.2",
"chai": "~1.9.1",
"syncho": "0.0.2",
"sinon": "~1.9.0",
"sinon-chai": "~2.5.0"
}
}
71 changes: 71 additions & 0 deletions sync-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
module.exports = SyncCache;

var LRU = require('lru-cache'), qs = require('querystring');

function SyncCache(opts) {
if (! opts || typeof opts !== 'object')
throw new Error('options must be an object');

if (! opts.load)
throw new Error('load function is required');

if (! (this instanceof SyncCache))
return new SyncCache(opts);

this._opts = opts;
this._cache = opts.store ? opts.store : new LRU(opts);
this._load = opts.load;
this._allowStale = opts.stale;
}

Object.defineProperty(SyncCache.prototype, 'itemCount', {
get: function () {
return this._cache.itemCount;
},
enumerable: true,
configurable: true
});

SyncCache.prototype.get = function (origKey) {
var key = convertKey(origKey);
var has = this._cache.has(key);
var cached = this._cache.get(key);
if (has && void 0 !== cached)
return cached;

if (void 0 !== cached && this._allowStale && !has)
return cached;

var res = this._load(origKey);
this._cache.set(key, res);
return res;
};

SyncCache.prototype.set = function(key, val) {
key = convertKey(key);
return this._cache.set(key, val);
};

SyncCache.prototype.reset = function() {
return this._cache.reset();
};

SyncCache.prototype.has = function(key) {
key = convertKey(key);
return this._cache.has(key);
};

SyncCache.prototype.del = function(key) {
key = convertKey(key);
return this._cache.del(key);
};

SyncCache.prototype.peek = function(key) {
key = convertKey(key);
return this._cache.peek(key);
};

function convertKey (key) {
return typeof key === 'object' ? qs.stringify(key) : key;
}

4 changes: 4 additions & 0 deletions test/mocha.opts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
--slow 20
--growl
--reporter spec
--require test/support/setup
6 changes: 6 additions & 0 deletions test/support/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
var chai = require("chai");
global.should = chai.should();
global.expect = chai.expect;
global.sinon = require("sinon");
var sinonChai = require("sinon-chai");
chai.use(sinonChai);
161 changes: 161 additions & 0 deletions test/sync-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
describe('SyncCache', function () {

var SyncCache = require('../sync-cache'), sandbox;

function Store () {
}
Store.prototype.get = Store.prototype.set = Store.prototype.del = Store.prototype.has = Store.prototype.peek = Store.prototype.reset = noop;
function noop () {}

beforeEach(function () {
sandbox = sinon.sandbox.create();
});

afterEach(function () {
sandbox.restore();
});

describe('#set', function () {
it('writes data to the cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('set').once().withExactArgs('key', 'value').returns(true);
var cache = new SyncCache({store: new Store, load: noop});
cache.set('key', 'value').should.be.true;
mock.verify();
});
});

describe('#has', function () {
it('checks if the key exists in the cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('has').once().withExactArgs('key').returns(true);
var cache = new SyncCache({store: new Store, load: noop});
cache.has('key').should.be.true;
mock.verify();
});
});

describe('#get', function () {
it('gets data from the cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('has').once().withExactArgs('key').returns(true);
mock.expects('get').once().withExactArgs('key').returns(true);
var cache = new SyncCache({store: new Store, load: noop});
cache.get('key').should.be.true;
mock.verify();
});

it('gets data from the handler if no data in cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('has').once().withExactArgs('key').returns(false);
mock.expects('get').once().withExactArgs('key').returns(void 0);
var load = sandbox.spy();
var cache = new SyncCache({store: new Store, load: load});
cache.get('key');
load.should.have.been.calledOnce;
load.should.have.been.calledWith('key');
mock.verify();
});

it('returns the data from the cache if stale data and allow stale is true', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('has').once().withExactArgs('key').returns(false);
mock.expects('get').once().withExactArgs('key').returns(true);
var load = sandbox.spy();
var cache = new SyncCache({store: new Store, load: load, stale: true});
cache.get('key').should.be.true;
load.should.not.have.been.called;
mock.verify();
});

it('gets data from the handler if stale data and allow stale is not true', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('has').once().withExactArgs('key').returns(false);
mock.expects('get').once().withExactArgs('key').returns(true);
var load = sandbox.spy();
var cache = new SyncCache({store: new Store, load: load});
cache.get('key');
load.should.have.been.calledOnce;
load.should.have.been.calledWith('key');
mock.verify();
});
});

describe('#del', function () {
it('deletes the item from the cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('del').once().withExactArgs('key').returns(true);
var cache = new SyncCache({store: new Store, load: noop});
cache.del('key').should.be.true;
mock.verify();
});
});

describe('#peek', function () {
it('peeks the item from the cache store', function () {
var mock = sandbox.mock(Store.prototype);
mock.expects('peek').once().withExactArgs('key').returns(true);
var cache = new SyncCache({store: new Store, load: noop});
cache.peek('key').should.be.true;
mock.verify();
});
});

describe('#convertKey', function () {
// TODO: add tests
});

describe('integration tests', function () {
var Sync = require('syncho'), fs = require('fs'), cache;

beforeEach(function () {
cache = new SyncCache({load: stat});
});

function stat (filepath) {
return fs.stat.sync(null, filepath);
}

it('loads data synchronously', function (done) {
Sync(function () {
var stats = cache.get('./package.json');
stats.should.exist;
stats.should.deep.equal(fs.statSync('./package.json'));
done();
});
});

it('retrieves data from the cache when it exists', function (done) {
Sync(function () {
var stat1 = cache.get('./package.json');
var stat2 = cache.get('./package.json');
stat1.should.equal(stat2);
done();
});
});

it('returns stale data from the cache when allow stale is true', function (done) {
Sync(function () {
cache = new SyncCache({load: stat, maxAge: 1, stale: true});
var stat1 = cache.get('./package.json');
Sync.sleep(2);
var stat2 = cache.get('./package.json');
stat1.should.equal(stat2);
done();
});
});

it('does not return stale data from the cache when allow stale is not true', function (done) {
Sync(function () {
cache = new SyncCache({load: stat, maxAge: 1});
var stat1 = cache.get('./package.json');
Sync.sleep(2);
var stat2 = cache.get('./package.json');
stat1.should.not.equal(stat2);
stat1.should.deep.equal(stat2);
done();
});
});
});

});

0 comments on commit 3281681

Please sign in to comment.