@noego/lock 0.0.1-dev.0 → 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 CHANGED
@@ -4,29 +4,46 @@ Cross-process locks and concurrency limits for Node and arbitrary commands. Inst
4
4
 
5
5
  ```sh
6
6
  npm install --save-dev @noego/lock
7
- npx lock --name integration --repo -- npm test
8
- npx lock 5 -- node build-one.js
9
- npx lock status
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
10
  ```
11
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
+
12
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.
13
15
 
14
16
  ## CLI
15
17
 
16
18
  ```text
17
19
  lock [N] [--name X] [--dir P|--worktree|--repo|--machine]
18
- [--limit N] [--wait D|--no-wait] [--max-hold D] -- command [args...]
20
+ [--limit N] [--wait D|--no-wait] [--max-hold D] [--report] [--] command [args...]
19
21
  lock status [--name X] [--dir P|--worktree|--repo|--machine]
20
22
  lock --version
21
23
  ```
22
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.
23
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.
24
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.
25
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.
26
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.
27
- - The launcher forwards INT, TERM, HUP and QUIT; it mirrors the wrapped command's exit code or terminating signal. The native wrapper 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.
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.
28
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.
29
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
+
30
47
  ## Node
31
48
 
32
49
  ```ts
@@ -48,7 +65,7 @@ try {
48
65
  }
49
66
  ```
50
67
 
51
- 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 daemon connection is lost, `lost` aborts and `release()` rejects. An acquired socket does not by itself keep Node alive. Accepted requests that disconnect reject with `LockLostError`. A held handle's `lost.reason` and failed release use the same type. If a disconnect might have left an undelivered grant in the journal, the client asks the replacement daemon to cancel that exact request.
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.
52
69
 
53
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.
54
71
 
@@ -86,24 +103,24 @@ In a bounded macOS arm64 probe, a fork inserting 120,000 1 KiB blobs into in-mem
86
103
 
87
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.
88
105
 
89
- 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. The replacement stops any registered command group whose wrapper disconnected and waits for its members to exit. 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.
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.
90
107
 
91
- The integration suite builds dedicated test binaries and clients with a separate, build-time-selected singleton. It never signals or connects to the production daemon.
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.
92
109
 
93
110
  ## Build and pack
94
111
 
95
- A fresh clone builds with `npm install` and `npm run build` after installing Node ≥20, 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.
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.
96
113
 
97
114
  ```sh
98
- npm ci
99
- npm run build
100
- npm run typecheck
101
- npm test
115
+ pnpm install --frozen-lockfile
116
+ pnpm run build
117
+ pnpm run typecheck
118
+ pnpm test
102
119
  cargo test --locked --manifest-path rust/Cargo.toml
103
120
  cargo clippy --locked --manifest-path rust/Cargo.toml --all-targets -- -D warnings
104
121
  cargo fmt --manifest-path rust/Cargo.toml -- --check
105
122
 
106
- npm run build:bin -- darwin-arm64
123
+ pnpm run build:bin darwin-arm64
107
124
  npm run release:pack -- --host-only
108
125
  # After building the four platform artifacts on matching or cross-configured hosts:
109
126
  npm run release:pack
@@ -113,8 +130,24 @@ Packing only creates local tarballs in `release/`; it never publishes. When test
113
130
 
114
131
  ## Releases
115
132
 
116
- - **Dev:** From a commit with green main CI, run `npm 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`.
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`.
117
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`.
118
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.
119
136
 
120
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/index.d.ts CHANGED
@@ -14,12 +14,16 @@ export interface LockOptions {
14
14
  signal?: AbortSignal;
15
15
  }
16
16
  export interface LockHandle {
17
- /** Aborted if the daemon connection is lost before release is acknowledged. */
17
+ /** Aborted if the grant is lost before release is requested. */
18
18
  readonly lost: AbortSignal;
19
19
  release(): Promise<void>;
20
20
  }
21
21
  export declare class LockLostError extends Error {
22
- constructor(message: string, options?: ErrorOptions);
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);
23
27
  }
24
28
  export declare function lock(options?: LockOptions): Promise<LockHandle>;
25
29
  export declare function lock<T>(options: LockOptions, work: (handle: Pick<LockHandle, 'lost'>) => T | PromiseLike<T>): Promise<T>;
package/dist/index.js CHANGED
@@ -5,11 +5,33 @@ import { keyFor, milliseconds } from './key.js';
5
5
  import { binary } from './binary.js';
6
6
  import { retryable, session } from './transport.js';
7
7
  export class LockLostError extends Error {
8
- constructor(message, options) {
8
+ elapsedHoldMs;
9
+ constructor(message, options, elapsedHoldMs) {
9
10
  super(message, options);
11
+ this.elapsedHoldMs = elapsedHoldMs;
10
12
  this.name = 'LockLostError';
11
13
  }
12
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
+ }
13
35
  export async function lock(options = {}, work) {
14
36
  const handle = await acquireHandle(options);
15
37
  if (!work)
@@ -69,42 +91,58 @@ async function acquireHandle(options) {
69
91
  const released = await session(native, async (channel) => {
70
92
  try {
71
93
  channel.send(cancel);
72
- return (await channel.next(true)).event === 'released';
94
+ return (await channel.next(Math.max(0, deadline - performance.now()))).event === 'released';
73
95
  }
74
96
  finally {
75
97
  channel.socket.destroy();
76
98
  }
77
99
  }, () => performance.now() < deadline);
78
100
  if (released)
79
- return;
101
+ return true;
80
102
  }
81
103
  catch { /* Preserve the original failure. */ }
82
- await delay(50);
104
+ await delay(Math.max(0, Math.min(50, deadline - performance.now())));
83
105
  }
84
106
  // If the daemon cannot be reached, owner exit and maxHold remain the
85
107
  // fallbacks for the original durable record.
108
+ return false;
86
109
  };
87
110
  let accepted = false;
88
111
  let submitted = false;
89
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');
90
115
  return session(native, async (channel) => {
91
116
  const socket = channel.socket;
92
- const onAbort = () => { cancelled = true; channel.send(cancel); };
93
- if (signal?.aborted) {
94
- if (!submitted)
95
- signal.throwIfAborted();
96
- onAbort();
97
- }
98
- else {
99
- signal?.addEventListener('abort', onAbort, { once: true });
100
- channel.send(acquire);
101
- submitted = true;
102
- }
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;
103
129
  try {
104
- let first = true;
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.
105
142
  while (true) {
106
- const frame = await channel.next(first);
107
- first = false;
143
+ const frame = await channel.next();
144
+ if (!cancelled && performance.now() >= deadline)
145
+ throw waitError;
108
146
  if (frame.event === 'error') {
109
147
  submitted = false;
110
148
  throw new Error(`lock: ${frame.message}`);
@@ -123,20 +161,45 @@ async function acquireHandle(options) {
123
161
  continue;
124
162
  if (frame.event !== 'granted')
125
163
  throw new Error('lock: unexpected daemon acquisition response');
164
+ clearWait?.();
126
165
  signal?.removeEventListener('abort', onAbort);
127
166
  socket.unref();
167
+ const grantedAt = performance.now();
128
168
  const lost = new AbortController();
129
169
  let release;
130
170
  let releaseTimer;
131
171
  const finished = (async () => {
132
172
  try {
133
- const response = await channel.next();
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
+ }
134
195
  if (response.event === 'released' && release)
135
196
  return;
136
197
  throw new Error(`lock: ${response.message ?? 'daemon ended the grant without acknowledging release'}`);
137
198
  }
138
199
  catch (error) {
139
- const failure = new LockLostError('lock: daemon lost before release was acknowledged', { cause: 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));
140
203
  lost.abort(failure);
141
204
  throw failure;
142
205
  }
@@ -152,12 +215,15 @@ async function acquireHandle(options) {
152
215
  if (!release) {
153
216
  socket.ref();
154
217
  release = finished.catch(async (error) => {
155
- await cancelGrant();
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();
156
222
  throw error;
157
223
  });
158
224
  if (!lost.signal.aborted) {
159
225
  channel.send({ op: 'release' });
160
- releaseTimer = setTimeout(() => socket.destroy(new Error('lock: daemon did not acknowledge release')), 3000);
226
+ releaseTimer = setTimeout(() => socket.destroy(new LockReleaseUnconfirmedError()), RELEASE_CONFIRM_MS);
161
227
  }
162
228
  }
163
229
  return release;
@@ -166,11 +232,16 @@ async function acquireHandle(options) {
166
232
  }
167
233
  }
168
234
  finally {
235
+ clearWait?.();
236
+ clearTimeout(abortTimer);
169
237
  signal?.removeEventListener('abort', onAbort);
170
238
  }
171
- }, () => !accepted && (submitted || !signal?.aborted)).catch(error => {
172
- if (error instanceof Cancelled)
173
- throw error.reason;
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
+ }
174
245
  if (submitted) {
175
246
  // The durable grant may have been written but not delivered. This peer
176
247
  // never exposed a handle, so cancelling this exact request is safe.
@@ -178,8 +249,8 @@ async function acquireHandle(options) {
178
249
  }
179
250
  if (accepted && retryable(error))
180
251
  throw new LockLostError('lock: daemon disconnected while waiting', { cause: error });
181
- if (signal?.aborted && !submitted)
182
- throw signal?.reason;
252
+ if (performance.now() >= deadline)
253
+ throw waitError;
183
254
  throw error;
184
255
  });
185
256
  }
@@ -12,7 +12,7 @@ declare class Channel {
12
12
  private closed?;
13
13
  constructor(socket: Socket);
14
14
  send(body: object): void;
15
- next(handshake?: boolean): Promise<Frame>;
15
+ next(cleanupTimeoutMs?: number): Promise<Frame>;
16
16
  }
17
17
  export declare function retryable(error: unknown): boolean;
18
18
  export declare function session<T>(binary: string, callback: (channel: Channel) => Promise<T>, canRetry?: () => boolean): Promise<T>;
package/dist/transport.js CHANGED
@@ -35,14 +35,15 @@ class Channel {
35
35
  this.notify?.();
36
36
  });
37
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?.(); });
38
39
  socket.on('close', () => { this.closed ??= new TransportError('lock: daemon disconnected'); this.notify?.(); });
39
40
  }
40
41
  send(body) {
41
42
  this.socket.write(JSON.stringify({ v: 1, ...body }) + '\n');
42
43
  }
43
- async next(handshake = false) {
44
+ async next(cleanupTimeoutMs) {
44
45
  let timedOut = false;
45
- const timer = handshake ? setTimeout(() => { timedOut = true; this.notify?.(); }, 3000) : undefined;
46
+ const timer = cleanupTimeoutMs !== undefined ? setTimeout(() => { timedOut = true; this.notify?.(); }, cleanupTimeoutMs) : undefined;
46
47
  try {
47
48
  while (true) {
48
49
  const frame = this.frames.shift();
@@ -51,7 +52,7 @@ class Channel {
51
52
  if (this.closed)
52
53
  throw this.closed;
53
54
  if (timedOut)
54
- throw new Error('lock: daemon did not answer wire v1 handshake');
55
+ throw new Error('lock: daemon did not answer a cleanup request');
55
56
  await new Promise(resolve => { this.notify = resolve; });
56
57
  }
57
58
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/lock",
3
- "version": "0.0.1-dev.0",
3
+ "version": "0.0.2-dev.0",
4
4
  "description": "Cross-process named locks and concurrency limits for commands and Node.js",
5
5
  "author": "Shavauhn Gabay",
6
6
  "license": "ISC",
@@ -16,7 +16,7 @@
16
16
  "node": ">=20"
17
17
  },
18
18
  "bin": {
19
- "lock": "bin/lock.cjs"
19
+ "lock": "bin/lock"
20
20
  },
21
21
  "exports": {
22
22
  ".": {
@@ -29,14 +29,14 @@
29
29
  }
30
30
  },
31
31
  "files": [
32
- "bin/lock.cjs",
32
+ "bin/lock",
33
33
  "dist"
34
34
  ],
35
35
  "optionalDependencies": {
36
- "@noego/lock-darwin-arm64": "0.0.1-dev.0",
37
- "@noego/lock-darwin-x64": "0.0.1-dev.0",
38
- "@noego/lock-linux-arm64": "0.0.1-dev.0",
39
- "@noego/lock-linux-x64": "0.0.1-dev.0"
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
40
  },
41
41
  "peerDependencies": {
42
42
  "vitest": "^2.1.9"
@@ -53,12 +53,13 @@
53
53
  "better-sqlite3": "12.6.2"
54
54
  },
55
55
  "scripts": {
56
- "build": "npm run build:lib && npm run build:bin",
56
+ "build": "pnpm run build:lib && pnpm run build:bin",
57
57
  "build:lib": "tsc -p tsconfig.json",
58
58
  "build:bin": "node scripts/build.mjs",
59
59
  "typecheck": "tsc --noEmit -p tsconfig.json",
60
- "test": "npm run build:lib && node scripts/build.mjs --test-build && node --test --test-concurrency=1 test/*.test.mjs",
60
+ "test": "node scripts/test.mjs",
61
61
  "release:dev": "git push origin HEAD:release-candidate",
62
62
  "release:pack": "node scripts/release.mjs"
63
- }
63
+ },
64
+ "packageManager": "pnpm@10.34.9"
64
65
  }
package/bin/lock.cjs DELETED
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict'
3
-
4
- async function main() {
5
- const { spawn } = require('node:child_process')
6
- const { constants } = require('node:os')
7
- const { binary } = await import('../dist/binary.js')
8
- const path = await binary()
9
- const child = spawn(path, process.argv.slice(2), { stdio: ['inherit', 'inherit', 'inherit', 'pipe'], env: { ...process.env, NOEGO_LOCK_LAUNCHER_PID_V1: String(process.pid) } })
10
- let group = ''
11
- child.stdio[3].setEncoding('utf8').on('data', chunk => { group = (group + chunk).slice(0, 128) })
12
- child.stdio[3].on('error', () => {})
13
- const handlers = new Map()
14
- for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {
15
- const forward = () => { child.kill(signal) }
16
- handlers.set(signal, forward)
17
- process.on(signal, forward)
18
- }
19
- const cleanup = () => {
20
- for (const [signal, handler] of handlers) process.removeListener(signal, handler)
21
- }
22
- child.once('error', error => {
23
- cleanup()
24
- console.error(`lock: cannot launch native binary: ${error.message}`)
25
- process.exitCode = 1
26
- })
27
- child.once('close', async (code, signal) => {
28
- if (signal && /^\d+:\d+:\d+\n$/.test(group)) {
29
- // On an abrupt wrapper death, do not return while its command can still
30
- // be running. The native helper uses the same birth-checked group cleanup
31
- // as the wrapper and works even if the daemon died too.
32
- try {
33
- const { once } = require('node:events')
34
- const reaper = spawn(path, ['__cleanup-group', group.trim()], { stdio: 'inherit' })
35
- const [result] = await once(reaper, 'exit')
36
- if (result !== 0) console.error('lock: could not confirm command group cleanup')
37
- } catch (error) {
38
- console.error(`lock: could not clean up command group: ${error.message}`)
39
- }
40
- }
41
- cleanup()
42
- if (signal) {
43
- // Some Node builds have default handlers for particular signals.
44
- process.exitCode = 128 + constants.signals[signal]
45
- process.kill(process.pid, signal)
46
- } else process.exitCode = code ?? 1
47
- })
48
- }
49
- main().catch(error => {
50
- console.error(error.message)
51
- process.exitCode = 1
52
- })