@noego/lock 0.0.0-stage → 0.0.2-dev.0
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/README.md +152 -2
- package/bin/lock +72 -0
- package/dist/binary.d.ts +1 -0
- package/dist/binary.js +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +263 -0
- package/dist/key.d.ts +3 -0
- package/dist/key.js +31 -0
- package/dist/transport.d.ts +19 -0
- package/dist/transport.js +112 -0
- package/dist/vitest.d.ts +22 -0
- package/dist/vitest.js +124 -0
- package/package.json +63 -4
package/README.md
CHANGED
|
@@ -1,3 +1,153 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @noego/lock
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cross-process locks and concurrency limits for Node and arbitrary commands. Install as a **dev dependency**. The core has no dependency on a test runner.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install --save-dev @noego/lock
|
|
7
|
+
./node_modules/.bin/lock --name integration --repo npm test
|
|
8
|
+
./node_modules/.bin/lock 5 node build-one.js
|
|
9
|
+
./node_modules/.bin/lock status
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Call `./node_modules/.bin/lock` directly from a shell for the lowest overhead. The launcher uses POSIX `exec`: after startup the same PID runs Rust, with no shell or Node launcher left alive. Inside an npm script, use `lock` directly; npm adds its bin directory to PATH. `npm run` and `npx` themselves leave a Node process alive while the command runs; `lock` adds no Node process of its own. No install scripts are needed.
|
|
13
|
+
|
|
14
|
+
Exactly one Rust daemon per OS user tracks **all** production locks. CLI and Node clients forward requests; only the daemon grants places and decides queue order, limits, wait deadlines and expiry. The CLI runs the user's command itself, so the command keeps the caller's cwd, environment, terminal and sandbox. The daemon never runs a user's command. The first acquisition starts the daemon if needed. The daemon detaches without retaining terminal or pipeline descriptors; it exits about one second after all holders and waiters are gone.
|
|
15
|
+
|
|
16
|
+
## CLI
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
lock [N] [--name X] [--dir P|--worktree|--repo|--machine]
|
|
20
|
+
[--limit N] [--wait D|--no-wait] [--max-hold D] [--report] [--] command [args...]
|
|
21
|
+
lock status [--name X] [--dir P|--worktree|--repo|--machine]
|
|
22
|
+
lock --version
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- Put lock options before the command. The first command word starts the command, and everything after it is passed through unchanged, including flags. For example, `lock 5 npm test -- --runInBand` sets a lock limit of five and passes `test -- --runInBand` to npm. Unknown leading lock options are errors.
|
|
26
|
+
- `lock status` is reserved for lock status. Use `lock -- status` to run an executable named `status`; use `--` also to force a numeric or dash-prefixed word to be the command.
|
|
27
|
+
- Defaults: name `default`, current directory, limit **1**, wait indefinitely, maximum hold **1 hour**. Durations are whole numbers in milliseconds or use `ms`, `s`, `m`, or `h`. `--no-wait` makes one attempt.
|
|
28
|
+
- `--dir` uses a canonical directory path. `--worktree` uses the Git top-level directory. `--repo` uses the Git common directory, shared by worktrees of one clone but not by independent clones. `--machine` shares the key for this **OS user** across all directories. Scope kinds are distinct.
|
|
29
|
+
- Places are FIFO per key in daemon arrival order. Set the same limit (1–4096) for all live users of a key. A mismatch fails, rather than starting a second queue. The next request may choose a new limit once the key has no holders or waiters.
|
|
30
|
+
- A wrapped command succeeds only if it exits 0 and the daemon acknowledges normal release. After the daemon acknowledges a queue request or grant, a disconnect fails the invocation; it never reruns or resumes the command.
|
|
31
|
+
- The Rust client receives INT, TERM, HUP and QUIT directly and relays them to the command group. It mirrors the wrapped command's exit code or terminating signal and starts the command in a separate process group. It stops remaining group members on normal command exit as well as on expiry or wrapper death. Processes that leave that group are not covered. Interactive Ctrl-Z may stop the command without returning control to the shell; suspend/resume job control is not supported.
|
|
32
|
+
- Missing binary, unavailable daemon, incompatible protocol, nesting under a process that already holds the key, and acquisition failures are errors. If a job intentionally does not need the lock, run the command without `lock`; no implicit opt-out exists.
|
|
33
|
+
|
|
34
|
+
### Timing reports
|
|
35
|
+
|
|
36
|
+
`lock --machine --name heavy --limit 2 --report npm test` adds lock lifecycle lines to stderr only. The command's stdout, stderr, and exit status are unchanged. Omit `--report` to suppress these lines.
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
lock: waiting name="heavy" limit=2
|
|
40
|
+
lock: acquired name="heavy" waited_ms=12345
|
|
41
|
+
lock: done name="heavy" waited_ms=12345 ran_ms=67890 exit=0
|
|
42
|
+
lock: failed name="heavy" waited_ms=12345 reason="wait expired"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The stable format is one line per event, in the shown key order. Parse `name` and `reason` as JSON strings (they may contain spaces or escaped characters); millisecond fields and `exit` are decimal integers. A signal uses `signal=SIGTERM` in place of `exit` (unmapped signals use `SIG` followed by the signal number). Wire v1 acknowledges even immediate requests as queued and provides neither held count nor queue position. The client reports `waiting` only if the request is still pending 30 ms after that acknowledgment, letting immediate grants and rejections pass without queue messages. `acquired` is emitted only after a reported wait. `done` follows a grant; `failed` instead describes acquisition failure. Times use the client's awake-time clock: wait includes acquisition setup, and runtime starts when the command gate opens, excluding normal release acknowledgment. An uncatchable signal such as SIGKILL directed at the lock client itself cannot produce a final line.
|
|
46
|
+
|
|
47
|
+
## Node
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { lock } from '@noego/lock'
|
|
51
|
+
|
|
52
|
+
const handle = await lock({
|
|
53
|
+
name: 'integration',
|
|
54
|
+
scope: 'repo', // 'machine', 'worktree', or { dir: '/some/path' } also work
|
|
55
|
+
limit: 1,
|
|
56
|
+
wait: '2m',
|
|
57
|
+
maxHold: '10m',
|
|
58
|
+
signal: AbortSignal.timeout(130_000), // cancels acquisition, not protected work
|
|
59
|
+
})
|
|
60
|
+
try {
|
|
61
|
+
handle.lost.throwIfAborted()
|
|
62
|
+
// Run the protected work. If listening for loss, stop the work on loss.
|
|
63
|
+
} finally {
|
|
64
|
+
await handle.release()
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Every `lock()` takes a distinct place, including concurrent calls in one process. There is no reentrancy. A child of a live holder cannot acquire the same key; a reparented process is checked by actual ancestry, not inherited environment markers. `release()` is idempotent and waits for daemon acknowledgement. If the client observes daemon connection loss before `release()` is requested, `lost` aborts and `release()` rejects with `LockLostError`. If the connection drops after the release request, the client instead asks a daemon to cancel the exact grant within a bounded window. An acknowledgement confirms release; without one, `release()` rejects with `LockReleaseUnconfirmedError` without aborting `lost`. An explicit daemon rejection is still an error. An acquired socket does not by itself keep Node alive. Accepted requests that disconnect reject with `LockLostError`. Silence on a connected socket does not imply lock loss: clients wait for an acknowledgement, a daemon error, or the connection closing. A daemon that stays connected but stops making progress can therefore leave work pending. When loss is observed before release, `lost.reason` and the later rejection share the same error. If a disconnect might have left an undelivered grant in the journal, the client asks the replacement daemon to cancel that exact request.
|
|
69
|
+
|
|
70
|
+
Use `await lock(options, async ({ lost }) => result)` to cover the whole operation with one promise. It resolves only after the callback succeeds and the daemon acknowledges release. On loss it rejects without waiting for the callback to settle. A callback error that occurs first takes precedence over release failure. Rejection cannot stop work that ignores `lost`. The place stays occupied until explicit release, process exit, or maxHold. Release after loss starts a replacement if needed and cancels the journaled grant, but still rejects with `LockLostError`. The callback form cancels once the callback settles; loss alone never releases while work is still running.
|
|
71
|
+
|
|
72
|
+
**Hard expiry kills the process.** The daemon measures elapsed awake time from the grant; laptop sleep is not counted. For Node, the daemon verifies the socket peer's PID and start time and sends SIGKILL to that Node process, not to its process group. Its children can survive: we verified that a child remained alive while the next holder acquired. Do not put work that must stop atomically in children of a Node holder; put the command under the CLI instead and keep its children in the command group. Neither path runs shutdown handlers after SIGKILL.
|
|
73
|
+
|
|
74
|
+
## Vitest 2.1
|
|
75
|
+
|
|
76
|
+
All three helpers require an explicit, positive `maxHold`. Loss fails the protected test or fork even if its body passes. Use the optional `@noego/lock/vitest` subpath with Vitest's **forks** pool. Do not wrap the whole command if only some tests are heavy:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { afterEach, describe, test } from 'vitest'
|
|
80
|
+
import { lockedTest, useLock } from '@noego/lock/vitest'
|
|
81
|
+
|
|
82
|
+
const database = { name: 'large-sqlite', scope: 'machine' as const, maxHold: '2m' as const }
|
|
83
|
+
|
|
84
|
+
describe('tests that open a database in beforeEach', () => {
|
|
85
|
+
useLock(database) // register before resource-acquisition hooks
|
|
86
|
+
// Register the user beforeEach and afterEach here.
|
|
87
|
+
afterEach(async () => { /* close the database */ })
|
|
88
|
+
test('ordinary test body', async () => { /* ... */ })
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
lockedTest.concurrent('another expensive test', { ...database, timeout: 2_000 }, async ctx => {
|
|
92
|
+
// Open the resource in the body; register its cleanup on ctx.onTestFinished.
|
|
93
|
+
})
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
- `useLock` waits in a per-test hook with no Vitest timeout, then the regular test timeout applies to the body. Register cleanup with `afterEach` or a later `ctx.onTestFinished` callback. The helper releases after those callbacks, even if acquisition failed. Do not use `onTestFailed` to clean up protected resources: Vitest runs it later.
|
|
97
|
+
- `lockedTest` and `lockedTest.concurrent` wait inside a wrapper with no Vitest timeout; their own body timer starts after acquisition (5 seconds by default, or pass `timeout`). If an asynchronous body outlives the timer, the lease remains until it settles and cleanup completes, the fork exits, or `maxHold` kills it. Use registration-time skips instead of `context.skip()`, which bypasses cleanup in Vitest 2.
|
|
98
|
+
- For a file gate, call `await lockFile(options)` in a setup file **before** heavy imports. In Vitest 2.1.9, `expect.getState().testPath` in setup identifies the test file. Call only for the files that need it. The fork cache only deduplicates identical acquisition calls; use consistent options for the same key within a fork. The daemon owns the actual lock. The fork retains the acquisition until it exits; if a fork is reused, it keeps the place across files. Do not combine a file lock and a per-test lock of the same key at limit 1. Light files that do not call it stay ungated.
|
|
99
|
+
|
|
100
|
+
In a bounded macOS arm64 probe, a fork inserting 120,000 1 KiB blobs into in-memory SQLite measured **76 → 279 → 279 MiB RSS** before insert, during the test, and immediately after `db.close()`. Close the database before releasing a per-test place, but do not assume that frees resident process memory. Prefer a file gate or a wrapped command when imports or retained RSS dominate; measure on your worker configuration.
|
|
101
|
+
|
|
102
|
+
## Daemon and crash recovery
|
|
103
|
+
|
|
104
|
+
The account's OS home (not `$HOME`) contains `~/.noego-lock/v1`. It must be private (0700), writable, and on a local filesystem that supports Unix sockets and `flock`. The stable, unversioned `~/.noego-lock/daemon.lock` inode must never be removed or replaced while a daemon might run. Wire v1 and the v1 journal are shared by installs in all worktrees; an incompatible peer fails instead of starting a parallel daemon. Do not delete or move the state directory while clients are live.
|
|
105
|
+
|
|
106
|
+
Only the singleton owner replaces a stale socket. A grant is journaled and synced before the daemon sends it. A client retries only before it receives any queue or grant acknowledgment, for startup and idle shutdown. An acknowledged waiter fails on daemon loss; a replacement treats live recorded Node peers as occupying their places and enforces their original deadlines. Acquired Node clients see loss, not an implicit reacquisition. If the CLI is killed, the caller can see its termination before cleanup finishes. The daemon stops the registered command group and confirms exit before granting the place again. If maxHold expires after the command is armed, the wrapper reports the expiry on stderr and preserves the command’s signal exit. If the daemon crashes, the CLI stops the group and exits non-zero. If the command has already stopped and its release was sent before the disconnect, the CLI reports `release unconfirmed`; command grants do not support cancellation from a replacement connection. If both die, the group may keep running until the next daemon starts; the replacement stops the recorded group and confirms exit before granting the place again. If no daemon is running after a crash, deadlines are enforced when the next client starts a replacement. If the daemon cannot confirm safe exit after a failed kill, it retains the place. On macOS identity uses PID and start time checked immediately before signalling; Linux uses a pidfd where the kernel supports it for individual peers.
|
|
107
|
+
|
|
108
|
+
The integration suite builds dedicated test binaries and clients with a separate, per-run singleton selected at build time. It never signals or connects to the production daemon.
|
|
109
|
+
|
|
110
|
+
## Build and pack
|
|
111
|
+
|
|
112
|
+
A fresh clone builds with `pnpm install` and `pnpm run build` after installing Node ≥20, pnpm 10.34.9, Git (for Git scopes), and Rust via rustup. CI uses Rust 1.99.1. On Linux, install `musl-tools` and run `rustup target add x86_64-unknown-linux-musl` or `rustup target add aarch64-unknown-linux-musl` to match the host. On macOS, install the Xcode Command Line Tools. Registry installs do not need Rust. The main npm package includes JavaScript and declarations; each optional platform package includes one native executable. Targets are macOS and Linux arm64/x64 (Linux builds use musl). Windows is not supported.
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
pnpm install --frozen-lockfile
|
|
116
|
+
pnpm run build
|
|
117
|
+
pnpm run typecheck
|
|
118
|
+
pnpm test
|
|
119
|
+
cargo test --locked --manifest-path rust/Cargo.toml
|
|
120
|
+
cargo clippy --locked --manifest-path rust/Cargo.toml --all-targets -- -D warnings
|
|
121
|
+
cargo fmt --manifest-path rust/Cargo.toml -- --check
|
|
122
|
+
|
|
123
|
+
pnpm run build:bin darwin-arm64
|
|
124
|
+
npm run release:pack -- --host-only
|
|
125
|
+
# After building the four platform artifacts on matching or cross-configured hosts:
|
|
126
|
+
npm run release:pack
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Packing only creates local tarballs in `release/`; it never publishes. When testing an unpublished version, install both the main tarball and your platform tarball into the scratch project.
|
|
130
|
+
|
|
131
|
+
## Releases
|
|
132
|
+
|
|
133
|
+
- **Dev:** From a commit with green main CI, run `pnpm run release:dev` to push it to `release-candidate`. Actions chooses the next `<version>-dev.N` (starting with 0) and publishes to the npm `dev` tag. Install with `npm install --save-dev @noego/lock@dev`.
|
|
134
|
+
- **Stable:** After the dev release and its macOS and Linux registry smoke tests pass, push the **same commit** to `release` with `git push origin <verified-commit>:release`. Actions publishes the exact version in `package.json` to `latest` or skips if it already exists. Install with `npm install --save-dev @noego/lock`.
|
|
135
|
+
- Both channels test and produce all four native binaries before publishing. GitHub Actions uses the `NPM_TOKEN` repository secret and publishes the platform packages before the main package. If publication stops partway through, **rerun the same workflow run** so it reuses the saved version and skips packages already published. Do not publish locally.
|
|
136
|
+
|
|
137
|
+
The release workflow signs both macOS executables with Developer ID Application, hardened runtime, a secure timestamp, and no entitlements. It submits each signed executable to Apple notarization in a ZIP and requires acceptance. A bare executable cannot be stapled. GitHub Actions verifies the executable extracted from each final npm tarball and runs both architectures before publishing. Local builds do not use the release signing identity.
|
|
138
|
+
|
|
139
|
+
When a connected daemon stops responding, Node acquisition abort gives
|
|
140
|
+
cancellation three seconds before returning the abort reason. Explicit
|
|
141
|
+
`wait` / `--wait` / `--no-wait` adds at most three seconds of client-side
|
|
142
|
+
grace to the daemon's acquisition budget. `lock status` allows three seconds.
|
|
143
|
+
Node release waits up to 30 seconds; `LockReleaseUnconfirmedError` means
|
|
144
|
+
the release outcome is unknown, not that the lock was lost. The CLI can be
|
|
145
|
+
interrupted before its command starts or after it exits, even while the
|
|
146
|
+
daemon is unresponsive. The daemon enforces `maxHold` only while it can
|
|
147
|
+
make progress; enforcement is suspended while the daemon is hung.
|
|
148
|
+
|
|
149
|
+
`LockLostError.cause` preserves EOF, a socket error (including its code),
|
|
150
|
+
or the protocol rejection; `elapsedHoldMs` measures from observed grant to
|
|
151
|
+
loss. The daemon leaves its latest journal failure or abnormal Rust exit
|
|
152
|
+
in a bounded private `daemon-failure.log` under its v1 root, when writable.
|
|
153
|
+
An external kill or a filesystem failure can prevent that record.
|
package/bin/lock
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Resolve npm/Yarn symlinks without GNU readlink -f. pnpm's launcher execs this
|
|
3
|
+
# file directly from the virtual store, where its dependencies are siblings.
|
|
4
|
+
unset CDPATH
|
|
5
|
+
entry=$0
|
|
6
|
+
case $entry in
|
|
7
|
+
/*) ;;
|
|
8
|
+
*/*) entry=$PWD/$entry ;;
|
|
9
|
+
*) if [ -f "./$entry" ] || [ -L "./$entry" ]; then
|
|
10
|
+
entry=$PWD/$entry
|
|
11
|
+
else
|
|
12
|
+
entry=$(command -v "$entry") || exit 1
|
|
13
|
+
case $entry in /*) ;; *) entry=$PWD/$entry ;; esac
|
|
14
|
+
fi ;;
|
|
15
|
+
esac
|
|
16
|
+
|
|
17
|
+
unsupported() {
|
|
18
|
+
printf '%s\n' 'lock: unsupported platform (macOS/Linux arm64/x64 only; Windows is not supported)' >&2
|
|
19
|
+
exit 1
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
os=$(uname -s) || unsupported
|
|
23
|
+
machine=$(uname -m) || unsupported
|
|
24
|
+
case $os in Darwin) platform=darwin ;; Linux) platform=linux ;; *) unsupported ;; esac
|
|
25
|
+
case $machine in arm64|aarch64) arch=arm64 ;; x86_64|amd64) arch=x64 ;; *) unsupported ;; esac
|
|
26
|
+
suffix=$platform-$arch
|
|
27
|
+
alternate=
|
|
28
|
+
# uname follows the shell architecture, which need not match the Node that
|
|
29
|
+
# installed this package. On Apple Silicon either Mach-O can be executed.
|
|
30
|
+
if [ "$platform" = darwin ] && { [ "$arch" = arm64 ] || [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = 1 ]; }; then
|
|
31
|
+
if [ "$arch" = arm64 ]; then alternate=darwin-x64; else alternate=darwin-arm64; fi
|
|
32
|
+
fi
|
|
33
|
+
|
|
34
|
+
missing() {
|
|
35
|
+
printf '%s\n' "lock: missing or non-executable native binary; install @noego/lock-$suffix (optional dependencies must be enabled), or run npm run build from source" >&2
|
|
36
|
+
exit 1
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
file=$entry
|
|
40
|
+
hops=0
|
|
41
|
+
while [ -L "$file" ]; do
|
|
42
|
+
hops=$((hops + 1))
|
|
43
|
+
[ "$hops" -le 40 ] || missing
|
|
44
|
+
target=$(readlink "$file") || missing
|
|
45
|
+
case $target in /*) file=$target ;; *) file=${file%/*}/$target ;; esac
|
|
46
|
+
done
|
|
47
|
+
bindir=$(cd -P "${file%/*}" && pwd -P) || missing
|
|
48
|
+
|
|
49
|
+
# Preserve the source-checkout binary lookup used by the Node API.
|
|
50
|
+
for candidate in "$suffix" ${alternate:+"$alternate"}; do
|
|
51
|
+
path=$bindir/lock-$candidate
|
|
52
|
+
if [ -e "$path" ] || [ -L "$path" ]; then
|
|
53
|
+
[ -f "$path" ] && [ -x "$path" ] || missing
|
|
54
|
+
exec "$path" "$@"
|
|
55
|
+
fi
|
|
56
|
+
done
|
|
57
|
+
|
|
58
|
+
# Resolve relative to our own package, never the caller's cwd or binary PATH.
|
|
59
|
+
# Physical parents cover hoisting, nested installs, and pnpm's virtual store.
|
|
60
|
+
dir=$bindir
|
|
61
|
+
while [ -n "$dir" ]; do
|
|
62
|
+
for candidate in "$suffix" ${alternate:+"$alternate"}; do
|
|
63
|
+
package=$dir/node_modules/@noego/lock-$candidate
|
|
64
|
+
if [ -e "$package" ] || [ -L "$package" ]; then
|
|
65
|
+
path=$package/lock-native
|
|
66
|
+
[ -f "$path" ] && [ -x "$path" ] || missing
|
|
67
|
+
exec "$path" "$@"
|
|
68
|
+
fi
|
|
69
|
+
done
|
|
70
|
+
dir=${dir%/*}
|
|
71
|
+
done
|
|
72
|
+
missing
|
package/dist/binary.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function binary(): Promise<string>;
|
package/dist/binary.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { access } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
export async function binary() {
|
|
6
|
+
const { platform, arch } = process;
|
|
7
|
+
if (!['darwin', 'linux'].includes(platform) || !['arm64', 'x64'].includes(arch)) {
|
|
8
|
+
throw new Error(`lock: unsupported platform ${platform}-${arch} (macOS/Linux arm64/x64 only)`);
|
|
9
|
+
}
|
|
10
|
+
const suffix = `${platform}-${arch}`;
|
|
11
|
+
const local = fileURLToPath(new URL(`../bin/lock-${suffix}`, import.meta.url));
|
|
12
|
+
try {
|
|
13
|
+
await access(local, constants.X_OK);
|
|
14
|
+
return local;
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
if (err.code !== 'ENOENT') {
|
|
18
|
+
throw new Error(`lock: local binary is not executable: ${local}`, { cause: err });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const pkg = createRequire(import.meta.url).resolve(`@noego/lock-${suffix}/lock-native`);
|
|
23
|
+
await access(pkg, constants.X_OK);
|
|
24
|
+
return pkg;
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
throw new Error(`lock: missing or non-executable native binary; install @noego/lock-${suffix} (optional dependencies must be enabled), or run npm run build from source`, { cause: err });
|
|
28
|
+
}
|
|
29
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type Duration = number | `${number}${'ms' | 's' | 'm' | 'h'}`;
|
|
2
|
+
export type Scope = 'machine' | 'repo' | 'worktree' | {
|
|
3
|
+
dir: string;
|
|
4
|
+
};
|
|
5
|
+
export interface LockOptions {
|
|
6
|
+
name?: string;
|
|
7
|
+
scope?: Scope;
|
|
8
|
+
limit?: number;
|
|
9
|
+
/** Maximum acquisition wait, in milliseconds or with an explicit suffix. Zero makes one attempt. */
|
|
10
|
+
wait?: Duration;
|
|
11
|
+
/** Hard lifetime, in milliseconds or with a suffix. Defaults to one hour. */
|
|
12
|
+
maxHold?: Duration;
|
|
13
|
+
/** Cancels acquisition only. After acquisition, call release when work is finished. */
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
}
|
|
16
|
+
export interface LockHandle {
|
|
17
|
+
/** Aborted if the grant is lost before release is requested. */
|
|
18
|
+
readonly lost: AbortSignal;
|
|
19
|
+
release(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export declare class LockLostError extends Error {
|
|
22
|
+
readonly elapsedHoldMs?: number | undefined;
|
|
23
|
+
constructor(message: string, options?: ErrorOptions, elapsedHoldMs?: number | undefined);
|
|
24
|
+
}
|
|
25
|
+
export declare class LockReleaseUnconfirmedError extends Error {
|
|
26
|
+
constructor(options?: ErrorOptions);
|
|
27
|
+
}
|
|
28
|
+
export declare function lock(options?: LockOptions): Promise<LockHandle>;
|
|
29
|
+
export declare function lock<T>(options: LockOptions, work: (handle: Pick<LockHandle, 'lost'>) => T | PromiseLike<T>): Promise<T>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { setTimeout, clearTimeout } from 'node:timers';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { keyFor, milliseconds } from './key.js';
|
|
5
|
+
import { binary } from './binary.js';
|
|
6
|
+
import { retryable, session } from './transport.js';
|
|
7
|
+
export class LockLostError extends Error {
|
|
8
|
+
elapsedHoldMs;
|
|
9
|
+
constructor(message, options, elapsedHoldMs) {
|
|
10
|
+
super(message, options);
|
|
11
|
+
this.elapsedHoldMs = elapsedHoldMs;
|
|
12
|
+
this.name = 'LockLostError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class LockReleaseUnconfirmedError extends Error {
|
|
16
|
+
constructor(options) {
|
|
17
|
+
super('lock: daemon did not confirm release; the grant may still be held', options);
|
|
18
|
+
this.name = 'LockReleaseUnconfirmedError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const DAEMON_GRACE_MS = 3000;
|
|
22
|
+
const RELEASE_CONFIRM_MS = 30_000;
|
|
23
|
+
function atDeadline(deadline, callback) {
|
|
24
|
+
let timer;
|
|
25
|
+
const check = () => {
|
|
26
|
+
const remaining = deadline - performance.now();
|
|
27
|
+
if (remaining <= 0)
|
|
28
|
+
callback();
|
|
29
|
+
else
|
|
30
|
+
timer = setTimeout(check, Math.min(Math.ceil(remaining), 2_147_483_647));
|
|
31
|
+
};
|
|
32
|
+
timer = setTimeout(check, Math.max(0, Math.min(Math.ceil(deadline - performance.now()), 2_147_483_647)));
|
|
33
|
+
return () => clearTimeout(timer);
|
|
34
|
+
}
|
|
35
|
+
export async function lock(options = {}, work) {
|
|
36
|
+
const handle = await acquireHandle(options);
|
|
37
|
+
if (!work)
|
|
38
|
+
return handle;
|
|
39
|
+
const { lost } = handle;
|
|
40
|
+
let rejectLoss;
|
|
41
|
+
const aborted = new Promise((_, reject) => { rejectLoss = reject; });
|
|
42
|
+
const onLost = () => rejectLoss(lost.reason);
|
|
43
|
+
lost.addEventListener('abort', onLost, { once: true });
|
|
44
|
+
if (lost.aborted)
|
|
45
|
+
onLost();
|
|
46
|
+
let settled = false;
|
|
47
|
+
const operation = Promise.resolve().then(() => {
|
|
48
|
+
lost.throwIfAborted();
|
|
49
|
+
return work({ lost });
|
|
50
|
+
});
|
|
51
|
+
void operation.then(() => { settled = true; }, () => { settled = true; });
|
|
52
|
+
try {
|
|
53
|
+
const result = await Promise.race([operation, aborted]);
|
|
54
|
+
await handle.release();
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
const dispose = () => handle.release().catch(() => { });
|
|
59
|
+
if (settled)
|
|
60
|
+
await dispose();
|
|
61
|
+
// Reject promptly on loss, but retain the grant while work is unresolved.
|
|
62
|
+
else
|
|
63
|
+
void operation.then(dispose, dispose);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
lost.removeEventListener('abort', onLost);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async function acquireHandle(options) {
|
|
71
|
+
const { name = 'default', scope, limit = 1, wait, maxHold = '1h', signal } = options;
|
|
72
|
+
signal?.throwIfAborted();
|
|
73
|
+
if (typeof name !== 'string' || Buffer.byteLength(name) < 1 || Buffer.byteLength(name) > 512) {
|
|
74
|
+
throw new Error('lock: name must contain 1..512 UTF-8 bytes');
|
|
75
|
+
}
|
|
76
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 4096)
|
|
77
|
+
throw new Error('lock: limit must be an integer in 1..4096');
|
|
78
|
+
const [native, key] = await Promise.all([binary(), keyFor(name, scope)]);
|
|
79
|
+
signal?.throwIfAborted();
|
|
80
|
+
const acquire = {
|
|
81
|
+
op: 'acquire', id: randomBytes(16).toString('hex'), kind: 'node', name, key, limit,
|
|
82
|
+
wait_ms: wait === undefined ? null : milliseconds(wait), max_ms: milliseconds(maxHold),
|
|
83
|
+
};
|
|
84
|
+
if (acquire.max_ms <= 0)
|
|
85
|
+
throw new Error('lock: maxHold must be positive');
|
|
86
|
+
const cancel = { op: 'cancel', id: acquire.id };
|
|
87
|
+
const cancelGrant = async () => {
|
|
88
|
+
const deadline = performance.now() + 3000;
|
|
89
|
+
while (performance.now() < deadline) {
|
|
90
|
+
try {
|
|
91
|
+
const released = await session(native, async (channel) => {
|
|
92
|
+
try {
|
|
93
|
+
channel.send(cancel);
|
|
94
|
+
return (await channel.next(Math.max(0, deadline - performance.now()))).event === 'released';
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
channel.socket.destroy();
|
|
98
|
+
}
|
|
99
|
+
}, () => performance.now() < deadline);
|
|
100
|
+
if (released)
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
catch { /* Preserve the original failure. */ }
|
|
104
|
+
await delay(Math.max(0, Math.min(50, deadline - performance.now())));
|
|
105
|
+
}
|
|
106
|
+
// If the daemon cannot be reached, owner exit and maxHold remain the
|
|
107
|
+
// fallbacks for the original durable record.
|
|
108
|
+
return false;
|
|
109
|
+
};
|
|
110
|
+
let accepted = false;
|
|
111
|
+
let submitted = false;
|
|
112
|
+
let cancelled = false;
|
|
113
|
+
const deadline = acquire.wait_ms === null ? Infinity : performance.now() + acquire.wait_ms + DAEMON_GRACE_MS;
|
|
114
|
+
const waitError = new Error('lock: acquisition wait expired; daemon did not answer within the grace period');
|
|
115
|
+
return session(native, async (channel) => {
|
|
116
|
+
const socket = channel.socket;
|
|
117
|
+
let abortTimer;
|
|
118
|
+
const abortError = new Cancelled(signal?.reason);
|
|
119
|
+
const onAbort = () => {
|
|
120
|
+
cancelled = true;
|
|
121
|
+
abortError.reason = signal?.reason;
|
|
122
|
+
channel.send(cancel);
|
|
123
|
+
abortTimer = setTimeout(() => socket.destroy(abortError), DAEMON_GRACE_MS);
|
|
124
|
+
};
|
|
125
|
+
const clearWait = Number.isFinite(deadline) ? atDeadline(deadline, () => {
|
|
126
|
+
if (!cancelled)
|
|
127
|
+
socket.destroy(waitError);
|
|
128
|
+
}) : undefined;
|
|
129
|
+
try {
|
|
130
|
+
if (signal?.aborted) {
|
|
131
|
+
if (!submitted)
|
|
132
|
+
signal.throwIfAborted();
|
|
133
|
+
onAbort();
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
137
|
+
channel.send(acquire);
|
|
138
|
+
submitted = true;
|
|
139
|
+
}
|
|
140
|
+
// A connected but silent daemon may be blocked on durable I/O. Only
|
|
141
|
+
// transport loss or a daemon response ends an accepted operation.
|
|
142
|
+
while (true) {
|
|
143
|
+
const frame = await channel.next();
|
|
144
|
+
if (!cancelled && performance.now() >= deadline)
|
|
145
|
+
throw waitError;
|
|
146
|
+
if (frame.event === 'error') {
|
|
147
|
+
submitted = false;
|
|
148
|
+
throw new Error(`lock: ${frame.message}`);
|
|
149
|
+
}
|
|
150
|
+
if (frame.event === 'released' && cancelled) {
|
|
151
|
+
// Stop retrying after acknowledgment, even if the abort reason happens
|
|
152
|
+
// to be an Error with a transport-like code.
|
|
153
|
+
submitted = false;
|
|
154
|
+
throw new Cancelled(signal?.reason);
|
|
155
|
+
}
|
|
156
|
+
if (frame.event === 'queued') {
|
|
157
|
+
accepted = true;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (frame.event === 'granted' && cancelled)
|
|
161
|
+
continue;
|
|
162
|
+
if (frame.event !== 'granted')
|
|
163
|
+
throw new Error('lock: unexpected daemon acquisition response');
|
|
164
|
+
clearWait?.();
|
|
165
|
+
signal?.removeEventListener('abort', onAbort);
|
|
166
|
+
socket.unref();
|
|
167
|
+
const grantedAt = performance.now();
|
|
168
|
+
const lost = new AbortController();
|
|
169
|
+
let release;
|
|
170
|
+
let releaseTimer;
|
|
171
|
+
const finished = (async () => {
|
|
172
|
+
try {
|
|
173
|
+
let response;
|
|
174
|
+
try {
|
|
175
|
+
response = await channel.next();
|
|
176
|
+
// The daemon may send Expired and Released together when it
|
|
177
|
+
// durably removes a grant at the maxHold boundary.
|
|
178
|
+
if (release && response.event === 'expired')
|
|
179
|
+
response = await channel.next();
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (release) {
|
|
183
|
+
if (error instanceof LockReleaseUnconfirmedError)
|
|
184
|
+
throw error;
|
|
185
|
+
if (retryable(error)) {
|
|
186
|
+
clearTimeout(releaseTimer);
|
|
187
|
+
socket.destroy();
|
|
188
|
+
if (await cancelGrant())
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
throw new LockReleaseUnconfirmedError({ cause: error });
|
|
192
|
+
}
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
if (response.event === 'released' && release)
|
|
196
|
+
return;
|
|
197
|
+
throw new Error(`lock: ${response.message ?? 'daemon ended the grant without acknowledging release'}`);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (release)
|
|
201
|
+
throw error;
|
|
202
|
+
const failure = new LockLostError('lock: daemon lost before release was requested', { cause: error }, Math.round(performance.now() - grantedAt));
|
|
203
|
+
lost.abort(failure);
|
|
204
|
+
throw failure;
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
clearTimeout(releaseTimer);
|
|
208
|
+
socket.destroy();
|
|
209
|
+
}
|
|
210
|
+
})();
|
|
211
|
+
void finished.catch(() => { });
|
|
212
|
+
return {
|
|
213
|
+
lost: lost.signal,
|
|
214
|
+
release() {
|
|
215
|
+
if (!release) {
|
|
216
|
+
socket.ref();
|
|
217
|
+
release = finished.catch(async (error) => {
|
|
218
|
+
// Preserve cleanup for known loss or an explicit release rejection.
|
|
219
|
+
// Neither can be converted to a successful release.
|
|
220
|
+
if (!(error instanceof LockReleaseUnconfirmedError))
|
|
221
|
+
await cancelGrant();
|
|
222
|
+
throw error;
|
|
223
|
+
});
|
|
224
|
+
if (!lost.signal.aborted) {
|
|
225
|
+
channel.send({ op: 'release' });
|
|
226
|
+
releaseTimer = setTimeout(() => socket.destroy(new LockReleaseUnconfirmedError()), RELEASE_CONFIRM_MS);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return release;
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
clearWait?.();
|
|
236
|
+
clearTimeout(abortTimer);
|
|
237
|
+
signal?.removeEventListener('abort', onAbort);
|
|
238
|
+
}
|
|
239
|
+
}, () => !accepted && !signal?.aborted && performance.now() < deadline).catch(error => {
|
|
240
|
+
if (signal?.aborted || error instanceof Cancelled) {
|
|
241
|
+
if (submitted)
|
|
242
|
+
void cancelGrant();
|
|
243
|
+
throw signal?.reason;
|
|
244
|
+
}
|
|
245
|
+
if (submitted) {
|
|
246
|
+
// The durable grant may have been written but not delivered. This peer
|
|
247
|
+
// never exposed a handle, so cancelling this exact request is safe.
|
|
248
|
+
void cancelGrant();
|
|
249
|
+
}
|
|
250
|
+
if (accepted && retryable(error))
|
|
251
|
+
throw new LockLostError('lock: daemon disconnected while waiting', { cause: error });
|
|
252
|
+
if (performance.now() >= deadline)
|
|
253
|
+
throw waitError;
|
|
254
|
+
throw error;
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
class Cancelled extends Error {
|
|
258
|
+
reason;
|
|
259
|
+
constructor(reason) {
|
|
260
|
+
super('lock acquisition cancelled');
|
|
261
|
+
this.reason = reason;
|
|
262
|
+
}
|
|
263
|
+
}
|
package/dist/key.d.ts
ADDED
package/dist/key.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
const git = promisify(execFile);
|
|
6
|
+
const zero = Buffer.from([0]);
|
|
7
|
+
export function milliseconds(value) {
|
|
8
|
+
const m = /^(\d+)(ms|s|m|h)?$/.exec(String(value));
|
|
9
|
+
if (!m)
|
|
10
|
+
throw new Error('lock: duration requires an integer with optional ms, s, m, or h');
|
|
11
|
+
const ms = Number(m[1]) * ({ ms: 1, s: 1_000, m: 60_000, h: 3_600_000 }[m[2]] ?? 1);
|
|
12
|
+
if (!Number.isSafeInteger(ms))
|
|
13
|
+
throw new Error('lock: duration overflow');
|
|
14
|
+
return ms;
|
|
15
|
+
}
|
|
16
|
+
export async function keyFor(name, scope) {
|
|
17
|
+
const kind = typeof scope === 'string' ? scope : 'dir';
|
|
18
|
+
let path = Buffer.alloc(0);
|
|
19
|
+
if (kind === 'dir') {
|
|
20
|
+
path = await realpath(typeof scope === 'object' ? scope.dir : '.', { encoding: 'buffer' });
|
|
21
|
+
if (!(await stat(path)).isDirectory())
|
|
22
|
+
throw new Error('lock: dir scope must be a directory');
|
|
23
|
+
}
|
|
24
|
+
else if (kind === 'repo' || kind === 'worktree') {
|
|
25
|
+
const { stdout } = await git('git', ['rev-parse', '--path-format=absolute', kind === 'repo' ? '--git-common-dir' : '--show-toplevel'], { encoding: 'buffer' });
|
|
26
|
+
path = await realpath(stdout.at(-1) === 10 ? stdout.subarray(0, -1) : stdout, { encoding: 'buffer' });
|
|
27
|
+
}
|
|
28
|
+
else if (kind !== 'machine')
|
|
29
|
+
throw new Error('lock: invalid scope');
|
|
30
|
+
return createHash('sha256').update(kind).update(zero).update(path).update(zero).update(name).digest('hex');
|
|
31
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Socket } from 'node:net';
|
|
2
|
+
interface Frame {
|
|
3
|
+
v: 1;
|
|
4
|
+
event: string;
|
|
5
|
+
message?: string;
|
|
6
|
+
}
|
|
7
|
+
declare class Channel {
|
|
8
|
+
readonly socket: Socket;
|
|
9
|
+
private buffer;
|
|
10
|
+
private frames;
|
|
11
|
+
private notify?;
|
|
12
|
+
private closed?;
|
|
13
|
+
constructor(socket: Socket);
|
|
14
|
+
send(body: object): void;
|
|
15
|
+
next(cleanupTimeoutMs?: number): Promise<Frame>;
|
|
16
|
+
}
|
|
17
|
+
export declare function retryable(error: unknown): boolean;
|
|
18
|
+
export declare function session<T>(binary: string, callback: (channel: Channel) => Promise<T>, canRetry?: () => boolean): Promise<T>;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { userInfo } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createConnection } from 'node:net';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
class Channel {
|
|
7
|
+
socket;
|
|
8
|
+
buffer = '';
|
|
9
|
+
frames = [];
|
|
10
|
+
notify;
|
|
11
|
+
closed;
|
|
12
|
+
constructor(socket) {
|
|
13
|
+
this.socket = socket;
|
|
14
|
+
socket.setEncoding('utf8');
|
|
15
|
+
socket.on('data', (chunk) => {
|
|
16
|
+
try {
|
|
17
|
+
this.buffer += chunk;
|
|
18
|
+
let end;
|
|
19
|
+
while ((end = this.buffer.indexOf('\n')) !== -1) {
|
|
20
|
+
if (end > 16_384)
|
|
21
|
+
throw new Error('lock: daemon frame exceeds limit');
|
|
22
|
+
const frame = JSON.parse(this.buffer.slice(0, end));
|
|
23
|
+
if (frame.v !== 1 || typeof frame.event !== 'string')
|
|
24
|
+
throw new Error('lock: incompatible daemon wire protocol; expected v1');
|
|
25
|
+
this.frames.push(frame);
|
|
26
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
27
|
+
}
|
|
28
|
+
if (this.buffer.length > 16_384)
|
|
29
|
+
throw new Error('lock: daemon frame exceeds limit');
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
this.closed = error;
|
|
33
|
+
socket.destroy();
|
|
34
|
+
}
|
|
35
|
+
this.notify?.();
|
|
36
|
+
});
|
|
37
|
+
socket.on('error', error => { this.closed ??= error; this.notify?.(); });
|
|
38
|
+
socket.on('end', () => { this.closed ??= new TransportError('lock: daemon connection reached EOF'); this.notify?.(); });
|
|
39
|
+
socket.on('close', () => { this.closed ??= new TransportError('lock: daemon disconnected'); this.notify?.(); });
|
|
40
|
+
}
|
|
41
|
+
send(body) {
|
|
42
|
+
this.socket.write(JSON.stringify({ v: 1, ...body }) + '\n');
|
|
43
|
+
}
|
|
44
|
+
async next(cleanupTimeoutMs) {
|
|
45
|
+
let timedOut = false;
|
|
46
|
+
const timer = cleanupTimeoutMs !== undefined ? setTimeout(() => { timedOut = true; this.notify?.(); }, cleanupTimeoutMs) : undefined;
|
|
47
|
+
try {
|
|
48
|
+
while (true) {
|
|
49
|
+
const frame = this.frames.shift();
|
|
50
|
+
if (frame)
|
|
51
|
+
return frame;
|
|
52
|
+
if (this.closed)
|
|
53
|
+
throw this.closed;
|
|
54
|
+
if (timedOut)
|
|
55
|
+
throw new Error('lock: daemon did not answer a cleanup request');
|
|
56
|
+
await new Promise(resolve => { this.notify = resolve; });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
this.notify = undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
class TransportError extends Error {
|
|
66
|
+
}
|
|
67
|
+
export function retryable(error) {
|
|
68
|
+
return error instanceof TransportError || ['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ECONNABORTED'].includes(error?.code ?? '');
|
|
69
|
+
}
|
|
70
|
+
function dial(path) {
|
|
71
|
+
const socket = createConnection(path);
|
|
72
|
+
const channel = new Channel(socket);
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
socket.once('connect', () => resolve(channel));
|
|
75
|
+
socket.once('error', reject);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export async function session(binary, callback, canRetry = () => true) {
|
|
79
|
+
const path = join(userInfo().homedir, '.noego-lock', 'v1', 'daemon.sock');
|
|
80
|
+
let retrySince = performance.now();
|
|
81
|
+
let lastSpawn = -Infinity;
|
|
82
|
+
let spawnError;
|
|
83
|
+
for (;;) {
|
|
84
|
+
let channel;
|
|
85
|
+
const at = performance.now();
|
|
86
|
+
try {
|
|
87
|
+
channel = await dial(path);
|
|
88
|
+
return await callback(channel);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
channel?.socket.destroy();
|
|
92
|
+
if (!canRetry() || !retryable(error)) {
|
|
93
|
+
if (!channel && error.code) {
|
|
94
|
+
throw new Error(`lock: cannot connect to daemon at ${path}: ${error.message}`, { cause: error });
|
|
95
|
+
}
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
if (channel && performance.now() - at >= 1000)
|
|
99
|
+
retrySince = performance.now();
|
|
100
|
+
if (performance.now() - retrySince >= 3000) {
|
|
101
|
+
throw new Error(`lock: daemon unreachable at ${path}; check directory permissions, socket path length, and v1 grant journal`, { cause: spawnError ?? error });
|
|
102
|
+
}
|
|
103
|
+
if (!channel && performance.now() - lastSpawn >= 100) {
|
|
104
|
+
const child = spawn(binary, ['__daemon'], { detached: true, cwd: '/', stdio: 'ignore' });
|
|
105
|
+
child.once('error', error => { spawnError = error; });
|
|
106
|
+
child.unref();
|
|
107
|
+
lastSpawn = performance.now();
|
|
108
|
+
}
|
|
109
|
+
await delay(15);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
package/dist/vitest.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type TestContext } from 'vitest';
|
|
2
|
+
import { type Duration, type LockOptions } from './index.js';
|
|
3
|
+
export type VitestLockOptions = LockOptions & {
|
|
4
|
+
maxHold: Duration;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Gate each test in the current suite. Register before expensive beforeEach
|
|
8
|
+
* hooks. Acquisition has no Vitest timer; wait/maxHold still apply.
|
|
9
|
+
*/
|
|
10
|
+
export declare function useLock(options: VitestLockOptions): void;
|
|
11
|
+
type Body = (context: TestContext) => unknown | Promise<unknown>;
|
|
12
|
+
export interface LockedTestOptions extends VitestLockOptions {
|
|
13
|
+
/** Body time limit (milliseconds), starting after acquisition. Defaults to 5 s. */
|
|
14
|
+
timeout?: number;
|
|
15
|
+
}
|
|
16
|
+
export declare function lockedTest(name: string, options: LockedTestOptions, body: Body): void;
|
|
17
|
+
export declare namespace lockedTest {
|
|
18
|
+
var concurrent: (name: string, options: LockedTestOptions, body: Body) => void;
|
|
19
|
+
}
|
|
20
|
+
/** Await in a setup file, before importing heavy code. Retained until the fork exits. */
|
|
21
|
+
export declare function lockFile(options: VitestLockOptions): Promise<void>;
|
|
22
|
+
export {};
|
package/dist/vitest.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { setTimeout, clearTimeout } from 'node:timers';
|
|
2
|
+
import { isMainThread } from 'node:worker_threads';
|
|
3
|
+
import { beforeEach, test } from 'vitest';
|
|
4
|
+
import { lock } from './index.js';
|
|
5
|
+
import { keyFor, milliseconds } from './key.js';
|
|
6
|
+
function requireMaxHold(options) {
|
|
7
|
+
if (options?.maxHold === undefined || milliseconds(options.maxHold) <= 0) {
|
|
8
|
+
throw new Error('@noego/lock/vitest requires a positive maxHold');
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function forkOnly() {
|
|
12
|
+
if (!isMainThread)
|
|
13
|
+
throw new Error('@noego/lock/vitest requires the Vitest forks pool: the watchdog targets processes, not threads');
|
|
14
|
+
}
|
|
15
|
+
function guardDynamicSkip(context) {
|
|
16
|
+
// Vitest 2 bypasses afterEach and onTestFinished for context.skip().
|
|
17
|
+
// Fail normally instead so resource cleanup and release will still run.
|
|
18
|
+
const runtime = context;
|
|
19
|
+
const previous = runtime.skip;
|
|
20
|
+
runtime.skip = () => {
|
|
21
|
+
throw new Error('@noego/lock/vitest: register locked tests with test.skip/skipIf instead of context.skip()');
|
|
22
|
+
};
|
|
23
|
+
return () => { runtime.skip = previous; };
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Gate each test in the current suite. Register before expensive beforeEach
|
|
27
|
+
* hooks. Acquisition has no Vitest timer; wait/maxHold still apply.
|
|
28
|
+
*/
|
|
29
|
+
export function useLock(options) {
|
|
30
|
+
forkOnly();
|
|
31
|
+
requireMaxHold(options);
|
|
32
|
+
beforeEach(async (context) => {
|
|
33
|
+
let handle;
|
|
34
|
+
const restoreSkip = guardDynamicSkip(context);
|
|
35
|
+
context.onTestFinished(async () => {
|
|
36
|
+
restoreSkip();
|
|
37
|
+
await handle?.release();
|
|
38
|
+
});
|
|
39
|
+
handle = await lock(options);
|
|
40
|
+
}, Infinity);
|
|
41
|
+
}
|
|
42
|
+
function register(method, name, options, body) {
|
|
43
|
+
forkOnly();
|
|
44
|
+
requireMaxHold(options);
|
|
45
|
+
const { timeout = 5_000, ...acquire } = options;
|
|
46
|
+
if (timeout !== Infinity && (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)) {
|
|
47
|
+
throw new Error('@noego/lock/vitest: timeout must be a positive integer <= 2147483647 or Infinity');
|
|
48
|
+
}
|
|
49
|
+
method(name, { timeout: Infinity }, async (context) => {
|
|
50
|
+
let handle;
|
|
51
|
+
let running;
|
|
52
|
+
let settled = false;
|
|
53
|
+
const restoreSkip = guardDynamicSkip(context);
|
|
54
|
+
context.onTestFinished(async () => {
|
|
55
|
+
restoreSkip();
|
|
56
|
+
if (!running || settled)
|
|
57
|
+
await handle?.release();
|
|
58
|
+
// Timed out asynchronous code may still use the protected resource.
|
|
59
|
+
// Keep its place until it settles, the worker exits, or maxHold kills it.
|
|
60
|
+
else
|
|
61
|
+
void running.then(() => handle?.release(), () => handle?.release()).catch(() => { });
|
|
62
|
+
});
|
|
63
|
+
handle = await lock(acquire);
|
|
64
|
+
running = Promise.resolve().then(() => body(context));
|
|
65
|
+
void running.then(() => { settled = true; }, () => { settled = true; });
|
|
66
|
+
if (timeout === Infinity) {
|
|
67
|
+
await running;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
let timer;
|
|
71
|
+
try {
|
|
72
|
+
await Promise.race([
|
|
73
|
+
running,
|
|
74
|
+
new Promise((_, reject) => {
|
|
75
|
+
timer = setTimeout(() => reject(new Error(`Locked test body timed out after ${timeout}ms`)), timeout);
|
|
76
|
+
}),
|
|
77
|
+
]);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
clearTimeout(timer);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
export function lockedTest(name, options, body) {
|
|
85
|
+
register(test, name, options, body);
|
|
86
|
+
}
|
|
87
|
+
lockedTest.concurrent = (name, options, body) => {
|
|
88
|
+
register(test.concurrent, name, options, body);
|
|
89
|
+
};
|
|
90
|
+
const workerKey = Symbol.for('@noego/lock/vitest/worker-v1');
|
|
91
|
+
const worker = process;
|
|
92
|
+
/** Await in a setup file, before importing heavy code. Retained until the fork exits. */
|
|
93
|
+
export async function lockFile(options) {
|
|
94
|
+
forkOnly();
|
|
95
|
+
requireMaxHold(options);
|
|
96
|
+
const key = await keyFor(options.name ?? 'default', options.scope);
|
|
97
|
+
const cache = worker[workerKey] ??= new Map();
|
|
98
|
+
const signature = JSON.stringify([
|
|
99
|
+
options.limit ?? 1,
|
|
100
|
+
milliseconds(options.maxHold),
|
|
101
|
+
options.wait === undefined ? null : milliseconds(options.wait),
|
|
102
|
+
]);
|
|
103
|
+
const entries = cache.get(key) ?? [];
|
|
104
|
+
const existing = entries.find(entry => entry.signature === signature && entry.signal === options.signal);
|
|
105
|
+
if (existing)
|
|
106
|
+
return existing.promise;
|
|
107
|
+
const promise = lock(options).then(handle => {
|
|
108
|
+
const fail = () => { queueMicrotask(() => { throw handle.lost.reason; }); };
|
|
109
|
+
if (handle.lost.aborted)
|
|
110
|
+
fail();
|
|
111
|
+
else
|
|
112
|
+
handle.lost.addEventListener('abort', fail, { once: true });
|
|
113
|
+
}).catch(error => {
|
|
114
|
+
const index = entries.findIndex(entry => entry.promise === promise);
|
|
115
|
+
if (index >= 0)
|
|
116
|
+
entries.splice(index, 1);
|
|
117
|
+
if (entries.length === 0)
|
|
118
|
+
cache.delete(key);
|
|
119
|
+
throw error;
|
|
120
|
+
});
|
|
121
|
+
entries.push({ promise, signature, signal: options.signal });
|
|
122
|
+
cache.set(key, entries);
|
|
123
|
+
return promise;
|
|
124
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/lock",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2-dev.0",
|
|
4
|
+
"description": "Cross-process named locks and concurrency limits for commands and Node.js",
|
|
5
|
+
"author": "Shavauhn Gabay",
|
|
6
|
+
"license": "ISC",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/shavyg2/noego_lock.git"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"lock": "bin/lock"
|
|
20
|
+
},
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./vitest": {
|
|
27
|
+
"types": "./dist/vitest.d.ts",
|
|
28
|
+
"import": "./dist/vitest.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"bin/lock",
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"optionalDependencies": {
|
|
36
|
+
"@noego/lock-darwin-arm64": "0.0.2-dev.0",
|
|
37
|
+
"@noego/lock-darwin-x64": "0.0.2-dev.0",
|
|
38
|
+
"@noego/lock-linux-arm64": "0.0.2-dev.0",
|
|
39
|
+
"@noego/lock-linux-x64": "0.0.2-dev.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"vitest": "^2.1.9"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"vitest": {
|
|
46
|
+
"optional": true
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/node": "^22.0.0",
|
|
51
|
+
"typescript": "~5.9.3",
|
|
52
|
+
"vitest": "2.1.9",
|
|
53
|
+
"better-sqlite3": "12.6.2"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "pnpm run build:lib && pnpm run build:bin",
|
|
57
|
+
"build:lib": "tsc -p tsconfig.json",
|
|
58
|
+
"build:bin": "node scripts/build.mjs",
|
|
59
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
60
|
+
"test": "node scripts/test.mjs",
|
|
61
|
+
"release:dev": "git push origin HEAD:release-candidate",
|
|
62
|
+
"release:pack": "node scripts/release.mjs"
|
|
63
|
+
},
|
|
64
|
+
"packageManager": "pnpm@10.34.9"
|
|
65
|
+
}
|