Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using wx to prevent concurrent writes to the cache #6

Merged
merged 1 commit into from
Feb 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ module.exports = function (folder, hash, log, disable) {
if (err) {
return cb(err)
}
writeFile(cacheFile, JSON.stringify(data, null, 2), function () {
writeFile(cacheFile, JSON.stringify(data, null, 2), {flag: 'wx'}, function () {
// Don't wait, don't care
})
cb(null, data)
Expand Down
35 changes: 35 additions & 0 deletions test/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,16 @@ function processFile (source, cb) {
})
}

function wait (duration) {
return function () {
return new Promise(function (resolve) {
setTimeout(resolve, duration)
})
}
}

const fileA = createFile('a.js', 'var a = 1')
const fileB = createFile('b.js', 'var b = 1')

test('cache one file', function (t) {
var persist = Promise.promisify(brfypersist(tmpTarget, {}))
Expand All @@ -43,3 +52,29 @@ test('cache one file', function (t) {
})
})
})

test('parallel caching only writes once', function (t) {
var persist = Promise.promisify(brfypersist(tmpTarget, {}))
var _firstFallback
var fallback = function (source, cb) {
if (!_firstFallback) {
_firstFallback = cb
return
}
setImmediate(function () {
// Triggering a writing of the cache in the same tick
_firstFallback(null, {first: true})
cb(null, {first: false})
})
}
return Promise.all([
persist(fileB, null, null, fallback),
persist(fileB, null, null, fallback)
])
.then(wait(100)) // The cache file may not have been written yet
.then(function (results) {
const cacheFilePath = path.join(tmpTarget, 'bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f_d63c02b75372e4e64783538bff55c8f18ce4cf0c.json')
t.ok(fs.existsSync(cacheFilePath), 'tmp created')
t.same(JSON.parse(fs.readFileSync(cacheFilePath, 'utf-8')), {first: true}, 'Only the first write succeeded')
})
})