async-atomic-store
An agnostic little store abstraction for reading, writing and appending on the same data from multiple sources in a locking manner, that allows concurrent/parallel (like from many async sources) write, append and read.
API
The interface is simple, you provide your read
, write
and data
methods, and it outputs an async-locking write
, read
, append
, lock
and data
methods.
All those methods are async (return a promise), even if they have non-async data underneath, because of the async locking mechanism, which is similar to a LOCK TABLE
and not LOCK ROW
. This does not use loops or saturate the event loop.
If any method throw
, the lock will be released and no changes are made.
; // guaranteed to return that point-in-time value; // at this exact point, "id" will be "my value"await store.write"id", "my value"; // passes the current value to the callback, modify it then write at the same key.// transformedValue = "my value + my value"; // locks everything, passes the current point-in-time datasource, and return an arbitrary value.// This exists for everything that isn't covered by the other "keyed" methods, but you need to// do some async work before returning a value// value = "ok";
Provides the following type-safe adapters for your data:
AsyncArray
;;await store.write0, "ok";await store.lock; myArray === "ok";myArray === "item";
AsyncMap
;;await store.write"str", "ing"; myMap.get"str" === "ing";
AsyncObject
;;await store.lock; myObj.goCrazy.with.it === true;
Examples
Explicit implementations of different data sources
Using Map
for ; i < 10; i++ assert await store.data.get1!.deep.object === 45, 'Object value should always be 45'
Using Set
:
await Promise.all assert data.join'' === '0123', 'set should be exactly 0123'
Redundantly using Atomics
and SharedArrayBuffer
:
for ; i < 16; i++ store.append1,currentValue + 1 assert currentData === 121, 'Index 1 should be 121'
License
MIT