Skip to content
This repository has been archived by the owner on Feb 12, 2024. It is now read-only.

Commit

Permalink
feat(object): add lru cache to object get/put
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddias committed Nov 8, 2016
1 parent f46cdc5 commit c439f39
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"is-ipfs": "^0.2.1",
"isstream": "^0.1.2",
"multiaddr": "^2.0.3",
"lru-cache": "^4.0.1",
"multipart-stream": "^2.0.1",
"ndjson": "^1.4.3",
"once": "^1.4.0",
Expand Down
30 changes: 30 additions & 0 deletions src/api/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const promisify = require('promisify-es6')
const bs58 = require('bs58')
const bl = require('bl')
const cleanMultihash = require('../clean-multihash')
const LRU = require('lru-cache')
const lruOptions = {
max: 128
}

const cache = LRU(lruOptions)

module.exports = (send) => {
const api = {
Expand All @@ -15,6 +21,7 @@ module.exports = (send) => {
callback = options
options = {}
}

if (!options) {
options = {}
}
Expand All @@ -25,6 +32,12 @@ module.exports = (send) => {
return callback(err)
}

const node = cache.get(multihash)

if (node) {
return callback(null, node)
}

send({
path: 'object/get',
args: multihash
Expand All @@ -38,9 +51,12 @@ module.exports = (send) => {
return new DAGLink(l.Name, l.Size, new Buffer(bs58.decode(l.Hash)))
}))

cache.set(multihash, node)

callback(null, node)
})
}),

put: promisify((obj, options, callback) => {
if (typeof options === 'function') {
callback = options
Expand Down Expand Up @@ -122,6 +138,8 @@ module.exports = (send) => {
return callback(new Error('Stored object was different from constructed object'))
}

cache.set(result.Hash, node)

callback(null, node)
})
}
Expand All @@ -142,6 +160,12 @@ module.exports = (send) => {
return callback(err)
}

const node = cache.get(multihash)

if (node) {
return callback(null, node.data)
}

send({
path: 'object/data',
args: multihash
Expand Down Expand Up @@ -172,6 +196,12 @@ module.exports = (send) => {
return callback(err)
}

const node = cache.get(multihash)

if (node) {
return callback(null, node.links)
}

send({
path: 'object/links',
args: multihash
Expand Down

0 comments on commit c439f39

Please sign in to comment.