diff --git a/src/errors/index.js b/src/errors/index.js index 23addfbf..5a1d7327 100644 --- a/src/errors/index.js +++ b/src/errors/index.js @@ -1,5 +1,20 @@ 'use strict' +/** + * Error raised when there is lock already in place when repo is being opened. + */ +class LockExistsError extends Error { + constructor (message) { + super(message) + this.name = 'LockExistsError' + this.code = 'ERR_LOCK_EXISTS' + this.message = message + } +} + +LockExistsError.code = 'ERR_LOCK_EXISTS' +exports.LockExistsError = LockExistsError + /** * Error raised when requested item is not found. */ diff --git a/src/lock-memory.js b/src/lock-memory.js index e5ea4204..d01ccced 100644 --- a/src/lock-memory.js +++ b/src/lock-memory.js @@ -1,5 +1,6 @@ 'use strict' +const errors = require('./errors') const debug = require('debug') const log = debug('repo:lock') @@ -17,6 +18,11 @@ const LOCKS = {} exports.lock = async (dir) => { // eslint-disable-line require-await const file = dir + '/' + lockFile log('locking %s', file) + + if (LOCKS[file] === true) { + throw new errors.LockExistsError(`Lock already being held for file: ${file}`) + } + LOCKS[file] = true const closer = { async close () { // eslint-disable-line require-await diff --git a/test/browser.js b/test/browser.js index ef4a3cf0..92981754 100644 --- a/test/browser.js +++ b/test/browser.js @@ -23,4 +23,5 @@ describe('IPFS Repo Tests on the Browser', () => { require('./keystore-test')(repo) require('./config-test')(repo) require('./api-addr-test')(repo) + require('./lock-test')(repo) }) diff --git a/test/lock-test.js b/test/lock-test.js index 0aa7bd7d..26df0b09 100644 --- a/test/lock-test.js +++ b/test/lock-test.js @@ -41,16 +41,10 @@ module.exports = (repo) => { }) describe('lock-memory', () => { - it('should lock a dir', async () => { + it('should lock and unlock dir', async () => { const dir = '/foo/bar' expect(await lockMemory.locked(dir)).to.be.false() - await lockMemory.lock(dir) - expect(await lockMemory.locked(dir)).to.be.true() - }) - - it('should unlock a dir', async () => { - const dir = '/foo/bar' const closer = await lockMemory.lock(dir) expect(await lockMemory.locked(dir)).to.be.true()