Mutex read/write lock for levelup.
npm install level-mutex
level-mutex is an abstract "lock" around a
levelup store. What it does is cycle between reads and writes, allowing all writes to return in order while queuing all reads, then running all reads and returning in order, then writing all the pending writes again.
level-mutex uses node.js' single threaded nature to your advantage so that you can maintain a higher order locking structure to insure various types of read-on-write consistency semantics.
This is currently used in couchup to ensure users cannot update a document without providing the latest revision.
While you do scope
level-mutex to a single levelup store there is nothing stopping you from having many mutexes around the same store provided you're using each to manage a separate higher order consistency guarantee. For instance,
couchup uses a mutex per database and an indefinite number of databases might exist in a single levelup store.
var levelup = require'levelup'mutex = require'level-mutex';var store = levelup'./testdb'mymutex = mutexstorepending =;mymutexgetkey// verify that the revision being written is the current one in the databaseif e || valuerevision !=== revision return cb'rev is out of date'// if this key is being written then nobody has read it yet which means// someone writing it can't be writing to the new revisionif pendingindexOfkey !== -1 return cb'rev is out of date'pendingpushkey// bump the revvaluerevision = valuerevision + 1mymutexputkey valueif e return cbecbnull rev:valuerevision// flush all pending keys when writes have been flushed.mymutexon'flushed'pending =