Skip to content

Commit

Permalink
blockstore: prevent blocks writes at the same position
Browse files Browse the repository at this point in the history
  • Loading branch information
braydonf committed Feb 28, 2019
1 parent 8e29cfb commit 8f4bbac
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/blockstore/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ class FileBlockStore extends AbstractBlockStore {

if (options.network != null)
this.network = Network.get(options.network);

this.writing = false;
}

/**
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -280,6 +287,8 @@ class FileBlockStore extends AbstractBlockStore {
b.put(layout.R.encode(), bw.writeU32(fileno).render());

await b.write();

this.writing = false;
}

/**
Expand Down
25 changes: 25 additions & 0 deletions test/blockstore-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 8f4bbac

Please sign in to comment.