Last active
September 4, 2023 16:19
-
-
Save derekmc/cdba150b2ab3c5af7dc1177c1c86cd86 to your computer and use it in GitHub Desktop.
Simple example of a "softlock" concurrent database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let softlock = require('softlock'); | |
softlock.backoffAlgorithm('linear'); | |
softlock.maxResets(4); | |
let query = softlock.query(); | |
// Softlock is a concurrent database that emulates a locking mechanism using versioned keys. | |
// If a 'locked' key has been changed since the transaction started, then the transaction | |
// is rejected and the logic retried | |
query.lock(['a','b','c']); // these keys are locked, but their values are not retrieved. | |
query.get('d', 'e', 'f'); // the keys to use for this transaction, all these are locked | |
query.peek('fff'); // these values are retrieved, but the keys are not locked. | |
while(!query.fail && await query.submit()){ // internally, submit may wait according to a backoff algorithm. | |
// query.ready, indicates we are ready to start the transaction. | |
// note that the transaction logic may need to be re-run on new values, if the transaction was rejected. | |
if(query.ready){ | |
let a = query.values['a']; | |
let r = query.revisions['a']; | |
console.log(`The current revision for key 'a' is ${r}`); | |
query.set('a', a+1); | |
} | |
} | |
console.log(query.success? "Query succeeded." : "Query failed."); | |
if(query.fail){ | |
console.log("Query failed"); | |
} | |
query.get('b') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment