From 0bd37053e465c1cdb494b532a89c91790fa600af Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Thu, 2 Jul 2020 10:58:58 -0300 Subject: [PATCH] Fixed race condition --- index.js | 4 +++- test.js | 38 ++++++++++++++++++++++++-------------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 5b2edee..b1575b3 100644 --- a/index.js +++ b/index.js @@ -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 diff --git a/test.js b/test.js index f1d67b8..1793044 100644 --- a/test.js +++ b/test.js @@ -1,3 +1,4 @@ +const { promisify } = require('util') const test = require('tape') const randomAccessTest = require('random-access-test') const racf = require('./') @@ -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())) @@ -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) + } +})