Skip to content

Commit

Permalink
Fixed race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
tinchoz49 committed Jul 2, 2020
1 parent fb300c2 commit 0bd3705
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,9 @@ WriteRequest.prototype.run = function (req) {
if (err) return req.callback(err)

this.req = req
if (!this.writer || this.writer.length !== file.size) return this.makeWriter()
if (!this.writer) {
return this.makeWriter()
}

const end = req.offset + req.size
if (end > file.size && !this.lock()) return
Expand Down
38 changes: 24 additions & 14 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { promisify } = require('util')
const test = require('tape')
const randomAccessTest = require('random-access-test')
const racf = require('./')
Expand All @@ -14,20 +15,8 @@ test('write/read concurrent requests', async t => {
const st = storage('random')

const rand = (min, max) => Math.floor(Math.random() * max) + min

const read = (...args) => new Promise((resolve, reject) => {
st.read(...args, (err) => {
if (err) return reject(err)
resolve()
})
})

const write = (...args) => new Promise((resolve, reject) => {
st.write(...args, (err) => {
if (err) return reject(err)
resolve()
})
})
const read = promisify(st.read.bind(st))
const write = promisify(st.write.bind(st))

try {
await new Promise(resolve => st.open(() => resolve()))
Expand Down Expand Up @@ -55,3 +44,24 @@ test('write/read concurrent requests', async t => {
t.end(err)
}
})

test('write concurrent requests over the same offset different size', async t => {
const st = storage('random')

const write = promisify(st.write.bind(st))

try {
await new Promise(resolve => st.open(() => resolve()))

await Promise.all([
write(0, Buffer.alloc(10)),
write(0, Buffer.alloc(1)),
write(0, Buffer.alloc(5))
])

t.pass('should write multiple requests over the same offset different size')
t.end()
} catch (err) {
t.end(err)
}
})

0 comments on commit 0bd3705

Please sign in to comment.