Web Locks API
Web Locks API
implementation for Node.js based on
worker_threads,
Atomics,
SharedArrayBuffer,
asynchronous functions,
and queue.
See specification: wicg.github.io/web-locks/ and documentation: developer.mozilla.org/en-US/docs/Web/API/Lock
This implementation is a part of Metarhia technology stack, needed for the first pilot project of Node.js application server based on parallel programming and workload micro-isolation. Web Locks API is intended to be merged into Node.js in future.
worker_threads
support.AbortSignal support to cancel a lock request while waiting.$ npm install web-locksconst { locks, AbortController } = require('web-locks');
// Exclusive lock (default)
await locks.request('Resource name', async (lock) => {
// use named resource; it is released after the callback settles
});
// Cancel a waiting request with AbortSignal
const controller = new AbortController();
const pending = locks.request(
'Resource name',
{ signal: controller.signal },
async () => {
// critical section
},
);
controller.abort(); // rejects pending with AbortErrorAttach workers so locks are coordinated across threads:
const { Worker } = require('worker_threads');
const { locks } = require('web-locks');
const worker = new Worker('./worker.js');
locks.attach(worker);locks.request(name, handler): Promiselocks.request(name, options, handler): Promisename: string — resource nameoptions.mode?: 'exclusive' — only exclusive is supportedoptions.signal?: AbortSignal — abort waiting for the lockhandler: (lock: Lock) => void | Promise — runs while holding the lockAlready-aborted signals reject immediately. Aborting while waiting cancels the
queued request and rejects with AbortError (or signal.reason when set).
locks.query(): Promiseheld: Array — currently held lockspending: Array — queued lock requestslocks.attach(worker): voidRegisters a worker_threads.Worker for cross-thread lock coordination.
locks: LockManagerAbortController, AbortSignal, AbortError — native when available,
otherwise a small polyfillThis implementation of Web Locks API is MIT licensed.
No open issues yet, or sync has not completed.