@zukhruf/mutex
A mutex for Node.js with interchangeable lock stores. You select who shares the locks: one object, the threads of one process, a parent process and its children, all processes on one host, or all machines that reach one server: a Postgres, SQL Server, MySQL or MariaDB database, or a Docker engine. The code that uses the mutex stays the same. Each lease has a fencing token, so a resource can refuse the late writes of a holder that lost its key.
The words in these documents have one meaning each. See the glossary in CONTEXT.md.
Use it
This project is an experiment.
npm install @zukhruf/mutex
import { Mutex } from '@zukhruf/mutex';
import { SqliteStore } from '@zukhruf/mutex/sqlite';
The root @zukhruf/mutex gives the core, with MutexElection. Each family of lock stores has its own import path: @zukhruf/mutex/memory, /thread, /ipc, /file-system, /sqlite, /socket, /postgres, /sqlserver, /mysql, /mariadb and /docker. The table in Select a lock store gives the path of each lock store.
Let one holder at a time run code for a key
Two requests ask for the last item at the same time. Each request reads the stock, waits for the database, and then writes the stock. Both requests read 1, so both sell the item.
if (stock > 0) {
// both requests see 1
await saveReservation(); // the other request runs here
stock -= 1; // both requests write
}
A mutex lets one holder at a time run this code for a key:
import { Mutex } from '@zukhruf/mutex';
import { MemoryStore } from '@zukhruf/mutex/memory';
const mutex = new Mutex(new MemoryStore());
const reserved = await mutex.acquire('product:42', async () => {
if (stock === 0) return false;
await saveReservation();
stock -= 1;
return true;
});
The full program is in the recipe Stop two requests from selling the last item.
Select a lock store
First find who writes to the resource. Then select the lock store with that reach. Each family of lock stores has its own import path. The root @zukhruf/mutex gives only the core: Mutex, Key, the acquire modes, LockStore, AcquireOptions, LockHandle, leaseFor and LeaseLostError (ADR 0020).
| Lock store |
Import |
Reach |
Order |
A holder stops |
Needs |
| MemoryStore |
@zukhruf/mutex/memory |
One object |
First come, first served |
The locks stop with the process |
Nothing |
| ThreadStore |
@zukhruf/mutex/thread |
One process (threads) |
First come, first served |
Released when the worker exits |
adopt(worker) |
| IpcStore |
@zukhruf/mutex/ipc |
Parent and its children |
First come, first served |
Released in approximately 2 ms |
fork() and adopt(child) |
| TicketQueueFileStore |
@zukhruf/mutex/file-system |
One host |
First come, first served |
Released after a waiter finds that it stopped |
A shared directory |
| LockFileStore |
@zukhruf/mutex/file-system |
One host |
No order |
Released after a waiter finds that it stopped |
A shared directory |
| SqliteStore |
@zukhruf/mutex/sqlite |
One host |
First come, first served in one process |
Released by the kernel |
A shared directory |
| SocketStore |
@zukhruf/mutex/socket |
One host |
First come, first served |
Released in approximately 2 ms |
A shared directory |
| PostgresStore |
@zukhruf/mutex/postgres |
Every machine that reaches the database |
Postgres' lock queue |
Released when its session ends |
A Postgres database and a connect function |
| SqlServerStore |
@zukhruf/mutex/sqlserver |
Every machine that reaches the database |
First come, first served in one process |
Released when its lease ends |
A SQL Server table, a sequence and a connect function |
| MysqlStore |
@zukhruf/mutex/mysql |
Every machine that reaches the database |
MySQL's lock queue |
Released when its session ends |
A MySQL database and a connect function |
| MariadbStore |
@zukhruf/mutex/mariadb |
Every machine that reaches the database |
MariaDB's lock queue |
Released when its session ends |
A MariaDB database and a connect function |
| DockerEngineStore |
@zukhruf/mutex/docker |
Every machine that reaches the Docker engine |
No order between processes |
Released when its attach ends |
A Docker engine, an image with cat, and @zukhruf/docker |
If you are not sure:
- One process: use
MemoryStore.
- Several processes on one host: use
SqliteStore.
- Many machines that already use Postgres: use
PostgresStore.
- Many machines that already use SQL Server: use
SqlServerStore.
- Many machines that already use MySQL: use
MysqlStore.
- Many machines that already use MariaDB: use
MariadbStore.
- Many machines that already use one Docker engine, with no database: use
DockerEngineStore.
Wait or skip while a key is busy
A key is exclusive for every caller. The acquire mode decides only what one caller does while the key is busy: wait (the default), or skip.
import { Modes } from '@zukhruf/mutex';
const report = mutex.key('report:daily', { mode: Modes.skipIfBusy() });
const tick = await report.run(buildReport); // a cron tick skips if a report runs
if (!tick.acquired) return;
const fresh = await report.run(buildReport, { mode: Modes.wait() }); // an admin waits, then runs
await mutex.acquire('product:42', reserve, {
mode: Modes.skipIfBusy({ waitAtMost: 500, clock: globalThis }),
});
A mode that can skip returns { acquired: true, value } | { acquired: false }, and TypeScript makes you check acquired.
To stop a wait, give a signal to the call: mutex.acquire(key, task, { signal }). When the signal aborts, the call rejects with signal.reason, and the task does not run. See Acquire modes.
Check if a key has a holder
A status view must show if a task runs, but it must not make the key busy. isHeld tells if a key has a holder now, and it never acquires the key:
const running = await report.isHeld(); // or: await mutex.isHeld('report:daily')
A caller that skips if busy is never refused because of a holder check. The holder can change before the answer arrives, so show the answer, but do not acquire a key because of it: an acquire mode decides that. See ADR 0015.
Refuse the writes of a stale holder
A holder can lose its key and not know it, for example when its process freezes. Each lease has a fencing token that increases with each grant. Send the token with each write, and let the resource refuse lower tokens:
await mutex.acquire('product:42', async (lease) => {
await database.run(
`UPDATE stock SET quantity = quantity - 1, fence = ?
WHERE product = ? AND fence <= ? AND quantity > 0`,
[lease.token.value, 'product:42', lease.token.value],
);
});
Sometimes the lock store sees the loss, for example after a failover of SocketStore. Then the signal of the lease aborts with LeaseLostError, and the task can stop before its next write. When the task ends, the call rejects with LeaseLostError:
await mutex.acquire('product:42', async (lease) => {
for (const order of orders) {
lease.signal.throwIfAborted();
await ship(order, lease.token);
}
});
The signal is a warning. A frozen holder can write before its lock store sees the loss, so the fencing token is still the protection.
The lease is a FencedLease of @zukhruf/fencing. Import FencingToken and the token sources from @zukhruf/fencing. LeaseLostError is from @zukhruf/lease, and this package also exports it, because its calls reject with it.
See Fencing tokens and the recipe Protect a database from stale holders.
Elect a leader with a key
MutexElection makes a key a backend of LeaderElection of @zukhruf/election: the holder of the key leads. To run a task each time this process leads, and to wait for the key again after each term, start a LeaderSelector of @zukhruf/election over it. A Spring LockRegistryLeaderInitiator leads over a lock of a LockRegistry in the same way (ADR 0036).
import { setTimeout as delay } from 'node:timers/promises';
import { Backoff } from '@zukhruf/async';
import { LeaderSelector, type LeaderSelectorListener } from '@zukhruf/election';
import { Mutex, MutexElection } from '@zukhruf/mutex';
import { MemoryStore } from '@zukhruf/mutex/memory';
const mutex = new Mutex(new MemoryStore());
const election = () =>
new MutexElection({ key: mutex.key('warehouse-writer'), clock: globalThis });
const autoRequeue = {
backoff: new Backoff({
initial: 1_000,
multiplier: 2,
max: 60_000,
jitter: { kind: 'full' },
}),
clock: globalThis,
};
const writer = (name: string): LeaderSelectorListener => ({
takeLeadership: async (term, signal) => {
console.log(`${name} leads at epoch ${term.epoch}`);
// Write until the selector stops the task: a dispose, an interrupt or a loss.
while (!signal.aborted) await delay(100);
console.log(`${name} gives the key up`);
},
});
const first = LeaderSelector.start(election(), writer('first'), {
autoRequeue,
});
const second = LeaderSelector.start(election(), writer('second'), {
autoRequeue,
});
await delay(150);
await first[Symbol.asyncDispose](); // The standby leads at once.
await delay(150);
await second[Symbol.asyncDispose]();
Output:
first leads at epoch 1
first gives the key up
second leads at epoch 2
second gives the key up
What the selector does after each round, and its errors, are in the README of @zukhruf/election (Run a task each time this process leads). The election over a key:
- The election picks the acquire mode of each step. A campaign tries the key once, as
Modes.skipIfBusy() does, and then waits in the line of the key, as Modes.wait() does, until its time is up. The mode of the key itself does not count, so campaign({ timeout: 0 }) never waits.
- The epoch of a term is the fencing token of its grant (ADR 0003). It is higher than each token that the lock store gave before, also to a holder that is not a candidate. On a
SocketStore, a token is epoch << 32 | sequence, so it can be 2^32 or more: give it to a resource as a fence, not to EpochTokenSource.
afterCleanShutdown is always false. A key keeps no state but its lock, so resign({ clean: true }) records nothing, and each next leader recovers.
- A lost lease ends the term. The signal of the term aborts with a
LeaseLostError whose cause is the loss of the lease (ADR 0013), for example when a SqlServerStore cannot renew its key (ADR 0035).
- The name of the election is the name of the key. A
LeaderSelectorWarning of a failed campaign has the detail election: <key>. Two keys with one name on two lock stores are two elections.
- A release that fails rejects the resign. A loss that comes while the term resigns is no failure. After a loss, a release that fails is a
TermWarning of @zukhruf/election.
Errors
| Error |
When |
LeaseLostError |
Another holder may have the key now. The signal of the lease aborts with it while the task runs, and the call rejects with it when the task ends. Its subject is the key. It is the class of @zukhruf/lease, and @zukhruf/mutex exports it too (ADR 0013). |
CoordinatorUnavailableError |
No coordinator is left that can grant the key, for example after the parent of an IpcStore stops. The request did not run. Its key is the key. @zukhruf/mutex/thread, /ipc and /socket export it (ADR 0004). |
GrantFailedError |
The coordinator could not mint a fencing token for the key. The request did not run, and the key is not held. Its key is the key. @zukhruf/mutex/thread, /ipc and /socket export it (ADR 0019). |
ProtocolVersionError |
The leader of a SocketStore speaks another protocol version. The request did not run. ours is the protocol version of this process, and theirs is the protocol version of the leader. @zukhruf/mutex/socket exports it (ADR 0014). |
NetworkDirectoryError |
The lock directory of a TicketQueueFileStore, LockFileStore, SqliteStore or SocketStore is on a network file system. directory and fileSystem name it. It is the class of @zukhruf/fs, and @zukhruf/mutex/file-system, /sqlite and /socket export it (src/lock-stores/network-directory.test.ts). |
signal.reason |
A call rejects with it when its signal aborts while it waits for the key. The task does not run (ADR 0008). |
A failure that no caller waits for is a process warning, in the shape of root ADR 0010. A 'warning' listener reads its type as name, its code, and its subject in detail, one <term>: <value> line each. Its cause is the failure, and its message ends with the failure's message. --disable-warning=<code or type> stops the print. Each type is a class that the package exports: MutexWarning from @zukhruf/mutex, DockerEngineStoreWarning from @zukhruf/mutex/docker, and LockServerWarning from @zukhruf/mutex/socket, so a listener can test warning instanceof the class (root ADR 0011). With two installed copies of the package, instanceof fails across the copies, so compare code.