blockstore: prevent blocks writes at the same position

This commit is contained in:
Braydon Fuller 2019-02-28 11:04:46 -08:00
parent 2d08b296f7
commit abd2ae4b5d
No known key found for this signature in database
GPG Key ID: F24F232D108B3AD4
2 changed files with 34 additions and 0 deletions

View File

@ -45,6 +45,8 @@ class FileBlockStore extends AbstractBlockStore {
if (options.network != null)
this.network = Network.get(options.network);
this.writing = false;
}
/**
@ -231,6 +233,11 @@ class FileBlockStore extends AbstractBlockStore {
*/
async write(hash, data) {
if (this.writing)
throw new Error('Already writing.');
this.writing = true;
const mlength = 8;
const blength = data.length;
const length = data.length + mlength;
@ -280,6 +287,8 @@ class FileBlockStore extends AbstractBlockStore {
b.put(layout.R.encode(), bw.writeU32(fileno).render());
await b.write();
this.writing = false;
}
/**

View File

@ -477,6 +477,31 @@ describe('BlockStore', function() {
}
});
it('will not write blocks at the same position', (done) => {
let err = null;
let finished = 0;
for (let i = 0; i < 16; i++) {
const block = random.randomBytes(128);
const hash = random.randomBytes(32);
// Accidently don't use `await` and attempt to
// write multiple blocks in parallel and at the
// same file position.
const promise = store.write(hash, block);
promise.catch((e) => {
err = e;
}).finally(() => {
finished += 1;
if (finished >= 16) {
assert(err);
assert(err.message, 'Already writing.');
done();
}
});
}
});
it('will return null if block not found', async () => {
const hash = random.randomBytes(32);
const block = await store.read(hash);