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

Commit

Permalink
fix(match): Rewrite the conditional stream logic (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
iarna authored and zkat committed May 4, 2017
1 parent 39abb54 commit 66bba4b
Showing 1 changed file with 38 additions and 43 deletions.
81 changes: 38 additions & 43 deletions cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const ssri = require('ssri')
const through = require('mississippi').through
const to = require('mississippi').to
const url = require('url')
const stream = require('stream')

const MAX_MEM_SIZE = 5 * 1024 * 1024 // 5MB

Expand Down Expand Up @@ -57,51 +58,45 @@ module.exports = class Cache {
status: 200
})
}
return Promise.resolve().then(() => {
const cachePath = this._path
let disturbed = false
// avoid opening cache file handles until a user actually tries to
// read from it.
const body = through((chunk, enc, cb) => {
if (disturbed) {
cb(null, chunk, enc)
} else {
disturbed = true
if (opts.memoize !== false && info.size > MAX_MEM_SIZE) {
pipe(
cacache.get.stream.byDigest(cachePath, info.integrity, {
memoize: opts.memoize
}),
body,
() => {}
)
} else {
// cacache is much faster at bulk reads
cacache.get.byDigest(cachePath, info.integrity, {
memoize: opts.memoize
}).then(data => {
body.write(data, () => {
body.end()
})
}, err => body.emit('error', err))
}
cb() // throw away dummy data
let body
const cachePath = this._path
// avoid opening cache file handles until a user actually tries to
// read from it.
if (opts.memoize !== false && info.size > MAX_MEM_SIZE) {
body = new stream.PassThrough()
const realRead = body._read
body._read = function (size) {
body._read = realRead
pipe(
cacache.get.stream.byDigest(cachePath, info.integrity, {
memoize: opts.memoize
}),
body,
err => body.emit(err))
return realRead.call(this, size)
}
} else {
let readOnce = false
// cacache is much faster at bulk reads
body = new stream.Readable({
read () {
if (readOnce) return this.push(null)
readOnce = true
cacache.get.byDigest(cachePath, info.integrity, {
memoize: opts.memoize
}).then(data => {
this.push(data)
this.push(null)
}, err => this.emit('error', err))
}
})
body.write('dummy')
return new fetch.Response(body, {
url: req.url,
headers: resHeaders,
status: 200,
size: info.size
})
}).catch(err => {
if (err.code === 'ENOENT') {
return null
} else {
throw err
}
})
}
return Promise.resolve(new fetch.Response(body, {
url: req.url,
headers: resHeaders,
status: 200,
size: info.size
}))
}
})
}
Expand Down

0 comments on commit 66bba4b

Please sign in to comment.