@noego/lock 0.0.0-stage → 0.0.1-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
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # @noego/lock
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ npx lock --name integration --repo -- npm test
8
+ npx lock 5 -- node build-one.js
9
+ npx lock status
10
+ ```
11
+
12
+ 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
+
14
+ ## CLI
15
+
16
+ ```text
17
+ lock [N] [--name X] [--dir P|--worktree|--repo|--machine]
18
+ [--limit N] [--wait D|--no-wait] [--max-hold D] -- command [args...]
19
+ lock status [--name X] [--dir P|--worktree|--repo|--machine]
20
+ lock --version
21
+ ```
22
+
23
+ - 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
+ - `--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
+ - 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
+ - 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.
28
+ - 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
+
30
+ ## Node
31
+
32
+ ```ts
33
+ import { lock } from '@noego/lock'
34
+
35
+ const handle = await lock({
36
+ name: 'integration',
37
+ scope: 'repo', // 'machine', 'worktree', or { dir: '/some/path' } also work
38
+ limit: 1,
39
+ wait: '2m',
40
+ maxHold: '10m',
41
+ signal: AbortSignal.timeout(130_000), // cancels acquisition, not protected work
42
+ })
43
+ try {
44
+ handle.lost.throwIfAborted()
45
+ // Run the protected work. If listening for loss, stop the work on loss.
46
+ } finally {
47
+ await handle.release()
48
+ }
49
+ ```
50
+
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.
52
+
53
+ 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
+
55
+ **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.
56
+
57
+ ## Vitest 2.1
58
+
59
+ 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:
60
+
61
+ ```ts
62
+ import { afterEach, describe, test } from 'vitest'
63
+ import { lockedTest, useLock } from '@noego/lock/vitest'
64
+
65
+ const database = { name: 'large-sqlite', scope: 'machine' as const, maxHold: '2m' as const }
66
+
67
+ describe('tests that open a database in beforeEach', () => {
68
+ useLock(database) // register before resource-acquisition hooks
69
+ // Register the user beforeEach and afterEach here.
70
+ afterEach(async () => { /* close the database */ })
71
+ test('ordinary test body', async () => { /* ... */ })
72
+ })
73
+
74
+ lockedTest.concurrent('another expensive test', { ...database, timeout: 2_000 }, async ctx => {
75
+ // Open the resource in the body; register its cleanup on ctx.onTestFinished.
76
+ })
77
+ ```
78
+
79
+ - `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.
80
+ - `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.
81
+ - 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.
82
+
83
+ 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.
84
+
85
+ ## Daemon and crash recovery
86
+
87
+ 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
+
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.
90
+
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.
92
+
93
+ ## Build and pack
94
+
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.
96
+
97
+ ```sh
98
+ npm ci
99
+ npm run build
100
+ npm run typecheck
101
+ npm test
102
+ cargo test --locked --manifest-path rust/Cargo.toml
103
+ cargo clippy --locked --manifest-path rust/Cargo.toml --all-targets -- -D warnings
104
+ cargo fmt --manifest-path rust/Cargo.toml -- --check
105
+
106
+ npm run build:bin -- darwin-arm64
107
+ npm run release:pack -- --host-only
108
+ # After building the four platform artifacts on matching or cross-configured hosts:
109
+ npm run release:pack
110
+ ```
111
+
112
+ 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.
113
+
114
+ ## Releases
115
+
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`.
117
+ - **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
+ - 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
+
120
+ 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.
package/bin/lock.cjs ADDED
@@ -0,0 +1,52 @@
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
+ })
@@ -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
+ }
@@ -0,0 +1,25 @@
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 daemon connection is lost before release is acknowledged. */
18
+ readonly lost: AbortSignal;
19
+ release(): Promise<void>;
20
+ }
21
+ export declare class LockLostError extends Error {
22
+ constructor(message: string, options?: ErrorOptions);
23
+ }
24
+ export declare function lock(options?: LockOptions): Promise<LockHandle>;
25
+ 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,192 @@
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
+ constructor(message, options) {
9
+ super(message, options);
10
+ this.name = 'LockLostError';
11
+ }
12
+ }
13
+ export async function lock(options = {}, work) {
14
+ const handle = await acquireHandle(options);
15
+ if (!work)
16
+ return handle;
17
+ const { lost } = handle;
18
+ let rejectLoss;
19
+ const aborted = new Promise((_, reject) => { rejectLoss = reject; });
20
+ const onLost = () => rejectLoss(lost.reason);
21
+ lost.addEventListener('abort', onLost, { once: true });
22
+ if (lost.aborted)
23
+ onLost();
24
+ let settled = false;
25
+ const operation = Promise.resolve().then(() => {
26
+ lost.throwIfAborted();
27
+ return work({ lost });
28
+ });
29
+ void operation.then(() => { settled = true; }, () => { settled = true; });
30
+ try {
31
+ const result = await Promise.race([operation, aborted]);
32
+ await handle.release();
33
+ return result;
34
+ }
35
+ catch (error) {
36
+ const dispose = () => handle.release().catch(() => { });
37
+ if (settled)
38
+ await dispose();
39
+ // Reject promptly on loss, but retain the grant while work is unresolved.
40
+ else
41
+ void operation.then(dispose, dispose);
42
+ throw error;
43
+ }
44
+ finally {
45
+ lost.removeEventListener('abort', onLost);
46
+ }
47
+ }
48
+ async function acquireHandle(options) {
49
+ const { name = 'default', scope, limit = 1, wait, maxHold = '1h', signal } = options;
50
+ signal?.throwIfAborted();
51
+ if (typeof name !== 'string' || Buffer.byteLength(name) < 1 || Buffer.byteLength(name) > 512) {
52
+ throw new Error('lock: name must contain 1..512 UTF-8 bytes');
53
+ }
54
+ if (!Number.isInteger(limit) || limit < 1 || limit > 4096)
55
+ throw new Error('lock: limit must be an integer in 1..4096');
56
+ const [native, key] = await Promise.all([binary(), keyFor(name, scope)]);
57
+ signal?.throwIfAborted();
58
+ const acquire = {
59
+ op: 'acquire', id: randomBytes(16).toString('hex'), kind: 'node', name, key, limit,
60
+ wait_ms: wait === undefined ? null : milliseconds(wait), max_ms: milliseconds(maxHold),
61
+ };
62
+ if (acquire.max_ms <= 0)
63
+ throw new Error('lock: maxHold must be positive');
64
+ const cancel = { op: 'cancel', id: acquire.id };
65
+ const cancelGrant = async () => {
66
+ const deadline = performance.now() + 3000;
67
+ while (performance.now() < deadline) {
68
+ try {
69
+ const released = await session(native, async (channel) => {
70
+ try {
71
+ channel.send(cancel);
72
+ return (await channel.next(true)).event === 'released';
73
+ }
74
+ finally {
75
+ channel.socket.destroy();
76
+ }
77
+ }, () => performance.now() < deadline);
78
+ if (released)
79
+ return;
80
+ }
81
+ catch { /* Preserve the original failure. */ }
82
+ await delay(50);
83
+ }
84
+ // If the daemon cannot be reached, owner exit and maxHold remain the
85
+ // fallbacks for the original durable record.
86
+ };
87
+ let accepted = false;
88
+ let submitted = false;
89
+ let cancelled = false;
90
+ return session(native, async (channel) => {
91
+ 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
+ }
103
+ try {
104
+ let first = true;
105
+ while (true) {
106
+ const frame = await channel.next(first);
107
+ first = false;
108
+ if (frame.event === 'error') {
109
+ submitted = false;
110
+ throw new Error(`lock: ${frame.message}`);
111
+ }
112
+ if (frame.event === 'released' && cancelled) {
113
+ // Stop retrying after acknowledgment, even if the abort reason happens
114
+ // to be an Error with a transport-like code.
115
+ submitted = false;
116
+ throw new Cancelled(signal?.reason);
117
+ }
118
+ if (frame.event === 'queued') {
119
+ accepted = true;
120
+ continue;
121
+ }
122
+ if (frame.event === 'granted' && cancelled)
123
+ continue;
124
+ if (frame.event !== 'granted')
125
+ throw new Error('lock: unexpected daemon acquisition response');
126
+ signal?.removeEventListener('abort', onAbort);
127
+ socket.unref();
128
+ const lost = new AbortController();
129
+ let release;
130
+ let releaseTimer;
131
+ const finished = (async () => {
132
+ try {
133
+ const response = await channel.next();
134
+ if (response.event === 'released' && release)
135
+ return;
136
+ throw new Error(`lock: ${response.message ?? 'daemon ended the grant without acknowledging release'}`);
137
+ }
138
+ catch (error) {
139
+ const failure = new LockLostError('lock: daemon lost before release was acknowledged', { cause: error });
140
+ lost.abort(failure);
141
+ throw failure;
142
+ }
143
+ finally {
144
+ clearTimeout(releaseTimer);
145
+ socket.destroy();
146
+ }
147
+ })();
148
+ void finished.catch(() => { });
149
+ return {
150
+ lost: lost.signal,
151
+ release() {
152
+ if (!release) {
153
+ socket.ref();
154
+ release = finished.catch(async (error) => {
155
+ await cancelGrant();
156
+ throw error;
157
+ });
158
+ if (!lost.signal.aborted) {
159
+ channel.send({ op: 'release' });
160
+ releaseTimer = setTimeout(() => socket.destroy(new Error('lock: daemon did not acknowledge release')), 3000);
161
+ }
162
+ }
163
+ return release;
164
+ },
165
+ };
166
+ }
167
+ }
168
+ finally {
169
+ signal?.removeEventListener('abort', onAbort);
170
+ }
171
+ }, () => !accepted && (submitted || !signal?.aborted)).catch(error => {
172
+ if (error instanceof Cancelled)
173
+ throw error.reason;
174
+ if (submitted) {
175
+ // The durable grant may have been written but not delivered. This peer
176
+ // never exposed a handle, so cancelling this exact request is safe.
177
+ void cancelGrant();
178
+ }
179
+ if (accepted && retryable(error))
180
+ throw new LockLostError('lock: daemon disconnected while waiting', { cause: error });
181
+ if (signal?.aborted && !submitted)
182
+ throw signal?.reason;
183
+ throw error;
184
+ });
185
+ }
186
+ class Cancelled extends Error {
187
+ reason;
188
+ constructor(reason) {
189
+ super('lock acquisition cancelled');
190
+ this.reason = reason;
191
+ }
192
+ }
package/dist/key.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { Duration, Scope } from './index.js';
2
+ export declare function milliseconds(value: Duration): number;
3
+ export declare function keyFor(name: string, scope: Scope | undefined): Promise<string>;
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(handshake?: boolean): 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,111 @@
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('close', () => { this.closed ??= new TransportError('lock: daemon disconnected'); this.notify?.(); });
39
+ }
40
+ send(body) {
41
+ this.socket.write(JSON.stringify({ v: 1, ...body }) + '\n');
42
+ }
43
+ async next(handshake = false) {
44
+ let timedOut = false;
45
+ const timer = handshake ? setTimeout(() => { timedOut = true; this.notify?.(); }, 3000) : undefined;
46
+ try {
47
+ while (true) {
48
+ const frame = this.frames.shift();
49
+ if (frame)
50
+ return frame;
51
+ if (this.closed)
52
+ throw this.closed;
53
+ if (timedOut)
54
+ throw new Error('lock: daemon did not answer wire v1 handshake');
55
+ await new Promise(resolve => { this.notify = resolve; });
56
+ }
57
+ }
58
+ finally {
59
+ clearTimeout(timer);
60
+ this.notify = undefined;
61
+ }
62
+ }
63
+ }
64
+ class TransportError extends Error {
65
+ }
66
+ export function retryable(error) {
67
+ return error instanceof TransportError || ['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ECONNABORTED'].includes(error?.code ?? '');
68
+ }
69
+ function dial(path) {
70
+ const socket = createConnection(path);
71
+ const channel = new Channel(socket);
72
+ return new Promise((resolve, reject) => {
73
+ socket.once('connect', () => resolve(channel));
74
+ socket.once('error', reject);
75
+ });
76
+ }
77
+ export async function session(binary, callback, canRetry = () => true) {
78
+ const path = join(userInfo().homedir, '.noego-lock', 'v1', 'daemon.sock');
79
+ let retrySince = performance.now();
80
+ let lastSpawn = -Infinity;
81
+ let spawnError;
82
+ for (;;) {
83
+ let channel;
84
+ const at = performance.now();
85
+ try {
86
+ channel = await dial(path);
87
+ return await callback(channel);
88
+ }
89
+ catch (error) {
90
+ channel?.socket.destroy();
91
+ if (!canRetry() || !retryable(error)) {
92
+ if (!channel && error.code) {
93
+ throw new Error(`lock: cannot connect to daemon at ${path}: ${error.message}`, { cause: error });
94
+ }
95
+ throw error;
96
+ }
97
+ if (channel && performance.now() - at >= 1000)
98
+ retrySince = performance.now();
99
+ if (performance.now() - retrySince >= 3000) {
100
+ throw new Error(`lock: daemon unreachable at ${path}; check directory permissions, socket path length, and v1 grant journal`, { cause: spawnError ?? error });
101
+ }
102
+ if (!channel && performance.now() - lastSpawn >= 100) {
103
+ const child = spawn(binary, ['__daemon'], { detached: true, cwd: '/', stdio: 'ignore' });
104
+ child.once('error', error => { spawnError = error; });
105
+ child.unref();
106
+ lastSpawn = performance.now();
107
+ }
108
+ await delay(15);
109
+ }
110
+ }
111
+ }
@@ -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,64 @@
1
1
  {
2
2
  "name": "@noego/lock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-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.cjs"
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.cjs",
33
+ "dist"
34
+ ],
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"
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": "npm run build:lib && npm 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": "npm run build:lib && node scripts/build.mjs --test-build && node --test --test-concurrency=1 test/*.test.mjs",
61
+ "release:dev": "git push origin HEAD:release-candidate",
62
+ "release:pack": "node scripts/release.mjs"
63
+ }
64
+ }