Skip to content

Instantly share code, notes, and snippets.

@derekmc
Created October 28, 2020 16:16
Show Gist options
  • Select an option

  • Save derekmc/edd2d91b169ab8eeae422e6adb6c6975 to your computer and use it in GitHub Desktop.

Select an option

Save derekmc/edd2d91b169ab8eeae422e6adb6c6975 to your computer and use it in GitHub Desktop.

Async Softlock

Async softlock is an asynchronous database interface for reliably rejecting outdated transactions

Example:

// this caches the values of those keys locally too.
// an meta lock object can be called with 'lock' again to submit that, or with 'get' to add additional retrieval keys.
function fooQuery(){
  let query = db.lock("key1 key2 key3").get("key4 key5"); // lock: {success: false, failure: false, wait: async ()=>false, keyList: [''], valueList: [''], valueMap: {}, lockedRevisions:{}}
  // submit modifies the existing query object
  // the first time query.submit is called, only the lock is secured, success and failure will both be false.
  // once the query submits successfully, then 
  while(!(await query.submit()).success && !query.failure){ //lock.failure is a failure message or false.
    //if the database is too busy on one of those keys, it may tell you to wait.
    // sleep for query.wait sleep should return true for non-zero sleep times.
    if(await query.wait()) continue; // wait to try to lock keys again.
    let val1 = query.data.key1 + "x";
    let val2 = query.data.key2 + Math.floor(math.sqrt(val1.length/2));

    query.set('key1', val1).set('key2', val2);
  }
  return query.success;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment