@bitclaw/mutex 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/retry.d.ts +24 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +25 -0
- package/dist/write-mutex.d.ts +34 -0
- package/dist/write-mutex.d.ts.map +1 -0
- package/dist/write-mutex.js +64 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Chavez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bitclaw/mutex
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Promise mutex, per-key mutex map and retry with exponential backoff. Zero dependencies and no runtime APIs, so it runs anywhere JavaScript does: Node, Bun, browsers, React Native, Electron.
|
|
4
|
+
|
|
5
|
+
> Part of [Warpkit](https://warpkit.dev/?utm_source=github&utm_medium=readme), my TypeScript SaaS starter.
|
|
6
|
+
> I'm open for consulting on this kind of work: [bitclaw.com/hire](https://bitclaw.com/hire?utm_source=github&utm_medium=readme).
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @bitclaw/mutex
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## WriteMutex
|
|
15
|
+
|
|
16
|
+
Callers run one at a time, in call order.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { WriteMutex } from '@bitclaw/mutex';
|
|
20
|
+
|
|
21
|
+
const sync = new WriteMutex();
|
|
22
|
+
|
|
23
|
+
// A network change and an app resume both trigger a sync; they never overlap.
|
|
24
|
+
await sync.acquire(() => flushQueue());
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`mutex.locked` is true while a caller is queued or running. Check it before closing what the mutex guards.
|
|
28
|
+
|
|
29
|
+
## WriteMutexMap
|
|
30
|
+
|
|
31
|
+
One mutex per key, created on first use.
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { WriteMutexMap } from '@bitclaw/mutex';
|
|
35
|
+
|
|
36
|
+
const locks = new WriteMutexMap();
|
|
37
|
+
await locks.withLock(userId, () => writeUserData(userId));
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## withRetry
|
|
41
|
+
|
|
42
|
+
Retries with exponential backoff and jitter while `shouldRetry` allows it, then rethrows the last error unchanged.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { withRetry } from '@bitclaw/mutex';
|
|
46
|
+
|
|
47
|
+
const isBusy = (error: unknown) =>
|
|
48
|
+
error instanceof Error && error.message.includes('database is locked');
|
|
49
|
+
|
|
50
|
+
await withRetry(() => db.write(row), {
|
|
51
|
+
maxAttempts: 5,
|
|
52
|
+
shouldRetry: isBusy,
|
|
53
|
+
onRetry: (error, attempt, delayMs) => console.warn(`retry ${attempt + 1} in ${delayMs}ms`)
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
| Option | Default |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `maxAttempts` | `3` (includes the first) |
|
|
60
|
+
| `baseDelayMs` | `100`, doubled per attempt, plus up to `baseDelayMs` of jitter |
|
|
61
|
+
| `maxDelayMs` | `2000` |
|
|
62
|
+
| `shouldRetry` | every error |
|
|
63
|
+
| `onRetry` | none |
|
|
64
|
+
| `sleep`, `random` | `setTimeout`, `Math.random`; inject them to test without waiting |
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/index.js
ADDED
package/dist/retry.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type RetryOptions = {
|
|
2
|
+
/** Total attempts, including the first. Default 3. */
|
|
3
|
+
maxAttempts?: number;
|
|
4
|
+
/** First backoff; doubles per attempt, plus jitter. Default 100. */
|
|
5
|
+
baseDelayMs?: number;
|
|
6
|
+
/** Upper bound on one backoff. Default 2000. */
|
|
7
|
+
maxDelayMs?: number;
|
|
8
|
+
/** Which errors are worth another attempt. Default: every error. */
|
|
9
|
+
shouldRetry?: (error: unknown, attempt: number) => boolean;
|
|
10
|
+
/** Called before each backoff, e.g. to log. */
|
|
11
|
+
onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
|
|
12
|
+
/** Override the wait, e.g. in tests. Default setTimeout. */
|
|
13
|
+
sleep?: (ms: number) => Promise<void>;
|
|
14
|
+
/** Override jitter, e.g. in tests. Default Math.random. */
|
|
15
|
+
random?: () => number;
|
|
16
|
+
};
|
|
17
|
+
/** Backoff before the attempt after `attempt` (0-based): exponential plus jitter. */
|
|
18
|
+
export declare function backoffDelay(attempt: number, baseDelayMs: number, maxDelayMs: number, random?: () => number): number;
|
|
19
|
+
/**
|
|
20
|
+
* Run fn, retrying with exponential backoff and jitter while shouldRetry
|
|
21
|
+
* says so. The last error is rethrown unchanged.
|
|
22
|
+
*/
|
|
23
|
+
export declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
24
|
+
//# sourceMappingURL=retry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../src/retry.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GAAG;IACzB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;IAC3D,+CAA+C;IAC/C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACrE,4DAA4D;IAC5D,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACvB,CAAC;AAKF,qFAAqF;AACrF,wBAAgB,YAAY,CAC1B,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,EAClB,MAAM,GAAE,MAAM,MAAoB,GACjC,MAAM,CAKR;AAED;;;GAGG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAC/B,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,CAAC,CAAC,CAuBZ"}
|
package/dist/retry.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const defaultSleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
2
|
+
/** Backoff before the attempt after `attempt` (0-based): exponential plus jitter. */
|
|
3
|
+
export function backoffDelay(attempt, baseDelayMs, maxDelayMs, random = Math.random) {
|
|
4
|
+
return Math.min(baseDelayMs * 2 ** attempt + random() * baseDelayMs, maxDelayMs);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Run fn, retrying with exponential backoff and jitter while shouldRetry
|
|
8
|
+
* says so. The last error is rethrown unchanged.
|
|
9
|
+
*/
|
|
10
|
+
export async function withRetry(fn, options = {}) {
|
|
11
|
+
const { maxAttempts = 3, baseDelayMs = 100, maxDelayMs = 2000, shouldRetry = () => true, onRetry, sleep = defaultSleep, random = Math.random } = options;
|
|
12
|
+
for (let attempt = 0;; attempt++) {
|
|
13
|
+
try {
|
|
14
|
+
return await fn();
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (attempt >= maxAttempts - 1 || !shouldRetry(error, attempt)) {
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
const delay = backoffDelay(attempt, baseDelayMs, maxDelayMs, random);
|
|
21
|
+
onRetry?.(error, attempt, delay);
|
|
22
|
+
await sleep(delay);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An async mutex: callers of acquire() run one at a time, in call order.
|
|
3
|
+
* JavaScript runs one task at a time per thread, so a promise queue is
|
|
4
|
+
* enough; no atomics.
|
|
5
|
+
*/
|
|
6
|
+
export declare class WriteMutex {
|
|
7
|
+
private queue;
|
|
8
|
+
private active;
|
|
9
|
+
/**
|
|
10
|
+
* True while at least one caller is queued on or executing inside
|
|
11
|
+
* acquire(). Callers that close or evict the resource this mutex guards
|
|
12
|
+
* must check this first: closing it under a queued or running acquire()
|
|
13
|
+
* defeats the serialization.
|
|
14
|
+
*/
|
|
15
|
+
get locked(): boolean;
|
|
16
|
+
/** Run fn once every earlier acquire() has settled. */
|
|
17
|
+
acquire<T>(fn: () => T | Promise<T>): Promise<T>;
|
|
18
|
+
}
|
|
19
|
+
/** One WriteMutex per key, created on first use. */
|
|
20
|
+
export declare class WriteMutexMap {
|
|
21
|
+
private mutexes;
|
|
22
|
+
/** Run fn under the mutex for key. */
|
|
23
|
+
withLock<T>(key: string, fn: () => T | Promise<T>): Promise<T>;
|
|
24
|
+
/** Forget the mutex for key, e.g. when evicting what it guards. */
|
|
25
|
+
delete(key: string): void;
|
|
26
|
+
/**
|
|
27
|
+
* True if the mutex for key has a caller queued or running. A key with
|
|
28
|
+
* no mutex yet is never locked.
|
|
29
|
+
*/
|
|
30
|
+
isLocked(key: string): boolean;
|
|
31
|
+
/** Number of tracked mutexes. */
|
|
32
|
+
get size(): number;
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=write-mutex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"write-mutex.d.ts","sourceRoot":"","sources":["../src/write-mutex.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,MAAM,CAAK;IAEnB;;;;;OAKG;IACH,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,uDAAuD;IACjD,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAkBvD;AAED,oDAAoD;AACpD,qBAAa,aAAa;IACxB,OAAO,CAAC,OAAO,CAAiC;IAEhD,sCAAsC;IAChC,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IASpE,mEAAmE;IACnE,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB;;;OAGG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAI9B,iCAAiC;IACjC,IAAI,IAAI,IAAI,MAAM,CAEjB;CACF"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An async mutex: callers of acquire() run one at a time, in call order.
|
|
3
|
+
* JavaScript runs one task at a time per thread, so a promise queue is
|
|
4
|
+
* enough; no atomics.
|
|
5
|
+
*/
|
|
6
|
+
export class WriteMutex {
|
|
7
|
+
queue = Promise.resolve();
|
|
8
|
+
active = 0;
|
|
9
|
+
/**
|
|
10
|
+
* True while at least one caller is queued on or executing inside
|
|
11
|
+
* acquire(). Callers that close or evict the resource this mutex guards
|
|
12
|
+
* must check this first: closing it under a queued or running acquire()
|
|
13
|
+
* defeats the serialization.
|
|
14
|
+
*/
|
|
15
|
+
get locked() {
|
|
16
|
+
return this.active > 0;
|
|
17
|
+
}
|
|
18
|
+
/** Run fn once every earlier acquire() has settled. */
|
|
19
|
+
async acquire(fn) {
|
|
20
|
+
this.active++;
|
|
21
|
+
let release;
|
|
22
|
+
const gate = new Promise(resolve => {
|
|
23
|
+
release = resolve;
|
|
24
|
+
});
|
|
25
|
+
const prior = this.queue;
|
|
26
|
+
this.queue = gate;
|
|
27
|
+
try {
|
|
28
|
+
await prior;
|
|
29
|
+
return await fn();
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
release();
|
|
33
|
+
this.active--;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** One WriteMutex per key, created on first use. */
|
|
38
|
+
export class WriteMutexMap {
|
|
39
|
+
mutexes = new Map();
|
|
40
|
+
/** Run fn under the mutex for key. */
|
|
41
|
+
async withLock(key, fn) {
|
|
42
|
+
let mutex = this.mutexes.get(key);
|
|
43
|
+
if (!mutex) {
|
|
44
|
+
mutex = new WriteMutex();
|
|
45
|
+
this.mutexes.set(key, mutex);
|
|
46
|
+
}
|
|
47
|
+
return mutex.acquire(fn);
|
|
48
|
+
}
|
|
49
|
+
/** Forget the mutex for key, e.g. when evicting what it guards. */
|
|
50
|
+
delete(key) {
|
|
51
|
+
this.mutexes.delete(key);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* True if the mutex for key has a caller queued or running. A key with
|
|
55
|
+
* no mutex yet is never locked.
|
|
56
|
+
*/
|
|
57
|
+
isLocked(key) {
|
|
58
|
+
return this.mutexes.get(key)?.locked ?? false;
|
|
59
|
+
}
|
|
60
|
+
/** Number of tracked mutexes. */
|
|
61
|
+
get size() {
|
|
62
|
+
return this.mutexes.size;
|
|
63
|
+
}
|
|
64
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitclaw/mutex",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Promise mutex, per-key mutex map and retry with backoff. Zero dependencies, any runtime: Node, Bun, browsers, React Native.",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"LICENSE",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"test": "bun test",
|
|
23
|
+
"test:watch": "bun test --watch",
|
|
24
|
+
"typecheck": "tsc --noEmit",
|
|
25
|
+
"lint": "biome check",
|
|
26
|
+
"lint:fix": "biome check --write",
|
|
27
|
+
"format": "biome format --write",
|
|
28
|
+
"knip": "knip",
|
|
29
|
+
"prepublishOnly": "npm run build && npm test",
|
|
30
|
+
"publish:patch": "npm version patch && git push --follow-tags",
|
|
31
|
+
"publish:minor": "npm version minor && git push --follow-tags",
|
|
32
|
+
"publish:major": "npm version major && git push --follow-tags"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@biomejs/biome": "2.4.15",
|
|
36
|
+
"knip": "6.12.2",
|
|
37
|
+
"@types/bun": "1.3.13",
|
|
38
|
+
"typescript": "5.9.3"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"mutex",
|
|
42
|
+
"lock",
|
|
43
|
+
"retry",
|
|
44
|
+
"backoff",
|
|
45
|
+
"react-native"
|
|
46
|
+
],
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/bitclaw/mutex.git"
|
|
50
|
+
}
|
|
51
|
+
}
|