lockbase v5.0.2
lockbase
A queued locking library useful for databases.
Installation
npm install --save lockbaseUsage
The lockbase module has the following methods:
adda new lockremovean existing lockcancelall locksfindall lockswaitfor key to have no more locksimportStateexportStateonfor adding a listenerofffor removing a listener
import lockbase from 'lockbase';
const locks = lockbase();
// Add a lock, and wait until it becomes active
const lockId = await locks.add(
'users', // path to lock
{
id: 'optional custom id' // defaults to increments starting at 1,
somethingElse: 'abc' // add custom metadata
}
);
// Remove a lock when you're finished with it
locks.remove(lockId);
const usersLocks = locks.find('users');
/*
usersLocks === [{
id: 1,
path: 'users'
}]
*/
// Wait until a key has no locks associated with it
// This will wait until `users` is unlocked.
await locks.wait('users.email')
// Cancel all locks, rejecting any promises that are waiting.
locks.cancel(new Error('server is closing down'))Queue and Events
The queue holds all active locks, future locks and waits.
The lockbase module is actually an EventEmitter that emits two events:
queue:insertwhen an item is added to the queuequeue:removewhen an item is removedresolved:{id}when an item is resolved
locks.on('queue.insert', item => {
console.log('item has been inserted', item);
});
locks.on('queue.remove', item => {
console.log('item has been removed', item);
});
locks.on('resolved.abcd', item => {
console.log('item abcd has been resolved', item);
});
locks.on('change', ({ item, event } => {
console.log(`item has been ${event}`, { event, item });
});Export lock state
If you are running multiple servers, where a primary server is used, you may need to hand over lock state. For example, if using raft, following a leader election.
You can export the lock state as a JSON object and import it into another server.
const exportedState = locks1.exportState();
/*
exportedState === {
queue: [{
id: 1,
path: 'users'
}],
incremental: 1
}
*/
locks2.importState(exportedState);Paths
Paths follow dot notation and will match partially.
userswill matchusers,users.email,users.anythingElseusers.emailwill matchusers.emailandusers.email.subpath
Example
const lockbase = require('lockbase');
const locks = lockbase();
locks.add('users').then(lock => {
const isLocked = locks.find('users.email')
console.log(isLocked) // === true
setTimeout(() => locks.remove(lock), 500);
});
locks.add('users').then(lock => {
// This will not be called for 500ms
locks.remove(lock);
});3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago