@jonmilner/local-ci 0.12.0 → 0.14.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
@@ -26,6 +26,7 @@ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci
26
26
  - `local-ci post <ref>`: resolves `<ref>` (a full or short sha, `HEAD`, a branch) to a local commit's full sha, failing with `<ref> is not a commit in this repo` when it names none, and with `<sha> has no passing check` when that commit never passed. When started by `pre-push`, first waits for the pushing `git` to exit (polling each second, up to 60 minutes, logging if it gives up), since git sends the push only after the whole hook exits, so a slow step after local-ci in the hook can't run out the clock; run by hand, it skips that wait. It then waits up to 3 minutes for GitHub to have the commit, posts status `check` = `success` (`<command> passed on <hostname>`), then posts `pr-title` on it for an open PR that contains it (waiting up to 30s for GitHub to link them). A PR opened after the push, or a retitled one, needs `local-ci pr-title` run by hand.
27
27
  - `local-ci pr-title [<pr>]`: lints the PR title (the current branch's PR by default) with `@jonmilner/commitlint-config` and posts status `pr-title` on its head commit, `failure` with the first error when the title does not pass.
28
28
  - `local-ci status [<sha>]`: posts `check` for a commit (default `HEAD`) that already passed, or runs the check first. When the check command fails, it posts `check` = `failure` (`<command> failed on <hostname>`) and exits non-zero; a later passing run posts `success` over it. A dirty tree, a commit that is not `HEAD`, or a `gh` error posts nothing. Use it after a push that skipped hooks (`--no-verify`) or a lost background poster.
29
+ - `local-ci run -- <command>`: runs `<command>` under the machine-wide check lock (see [State](#state)), for a full check started by hand or from a script: `local-ci run -- pnpm check`. It waits its turn with every other check, and they wait for it; like any check, it runs beside a background job rather than waiting for one (see [State](#state)). The arguments after `--` go to the program as they are, with no shell (`local-ci run -- sh -c 'a && b'` for a shell line). Stdin is `/dev/null` and the command has no controlling terminal, so anything that prompts on `/dev/tty` fails; output goes straight through. It exits with the command's status, 128 plus the signal number if a signal killed the command, or 1 if the command can't start. It works outside a git repo, needs no `gh` login, posts no status and records no pass. Inside a check that already holds the lock it runs at once, so a repo's `check` script can wrap itself in `local-ci run` without deadlocking its own pre-push.
29
30
  - `local-ci release`: publishes the repo's packages from this machine. Off unless `package.json` has `"local-ci": { "release": true }`; otherwise it prints `release not enabled` and exits 0. It needs a clean working tree, then fetches `origin` and takes a lock, so a second run exits with `release in progress`. In a temporary worktree at `origin`'s default branch:
30
31
  1. With pending changesets, it creates `release/<short-sha>`, runs the root `version-packages` script if `package.json` has one (for steps such as a size-history entry that belong in the version PR) or `pnpm changeset version` otherwise, commits `chore: version packages`, pushes (the hook runs the check and posts `check`), opens the PR, posts `pr-title`, waits for both statuses, and squash-merges it.
31
32
  2. At the merge commit (or the default branch, with no changesets pending), it runs `local-ci status`, then `pnpm release` with the npm token, then pushes the tags `changeset publish` created.
@@ -60,7 +61,7 @@ A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example on the hook
60
61
 
61
62
  Logs, the record of passed commits and the release lock live in `~/.local/state/local-ci/<repo>.log`, `<repo>.passed` and `<repo>.release.lock` (`$XDG_STATE_HOME` if set). A lock whose process has died is taken over.
62
63
 
63
- One check command runs at a time on the machine, across every repo, so overlapping checks can't starve each other's tests: `pre-push`, `status`, and the `status` runs `renovate` starts each take `check.lock` in the same directory around the check command (not the status posts). A run that finds it held prints `local-ci: waiting for the check lock, held by pid <pid> (<repo> <short-sha>)`, again whenever another run takes it first, and polls every second until the holder exits or dies; Ctrl-C stops the wait. After the wait it skips a commit that passed meanwhile and re-applies the clean-tree rule. The lock goes when the check passes, fails or is killed by a signal. Ctrl-C, SIGTERM or SIGHUP to local-ci passes the signal to the check's whole process group (so a check script's children get it too), waits for the check to exit, then releases the lock and dies of the signal, so a check never outlives its lock. A lock whose holder died (SIGKILL, a crash) or that predates the last boot is taken over by the next run. A local-ci check nested inside a check (one that pushes, say) sees its ancestor holds the lock and runs without waiting. A check that finds a background job's lock (see below) runs beside the job instead of waiting and leaves that lock alone, printing `local-ci: running beside background job pid <pid> (<holder>), without the check lock`; it holds `check.lock.beside` meanwhile, so another check waits for it rather than overlapping, and signals still stop it and release that lock as above. Each check run appends its duration and outcome to the log when it ends, e.g. `[<end time>] abc1234: pnpm check passed in 71.2s` (or `failed in`, or `did not finish after` when the check is killed by a signal or can't start); a commit that already passed is skipped and logs nothing. Ctrl-C stops the check, which logs `did not finish after`.
64
+ One check command runs at a time on the machine, across every repo, so overlapping checks can't starve each other's tests: `pre-push`, `status`, the `status` runs `renovate` starts, and `local-ci run` each take `check.lock` in the same directory around the command they run (not the status posts). Nothing else takes it: a bare `pnpm check` or `pnpm test` runs beside every other check, so start a full check by hand with `local-ci run -- pnpm check`. The lock only runs checks one at a time; it does not wait for memory pressure or swap to clear. A run that finds it held prints `local-ci: waiting for the check lock, held by pid <pid> (<repo> <short-sha>)` (`<repo> <command>` for `local-ci run`, with the command cut to 60 characters), again whenever another run takes it first, and polls every second until the holder exits or dies; Ctrl-C stops the wait. Checks don't queue, so the next one to poll after a release goes first; background jobs wait in arrival order (see [below](#taking-the-check-lock-from-your-own-scripts)). After the wait it skips a commit that passed meanwhile and re-applies the clean-tree rule. The lock goes when the check passes, fails or is killed by a signal. Ctrl-C, SIGTERM, SIGHUP or SIGQUIT (Ctrl-\\) to local-ci passes the signal to the check's whole process group (so a check script's children get it too), waits for the check to exit, then releases the lock and dies of the signal, so a check never outlives its lock. A lock whose holder died (SIGKILL, a crash) or that predates the last boot is taken over by the next run. A local-ci check nested inside a check (one that pushes, say) sees its ancestor holds the lock and runs without waiting. A check that finds a background job's lock (see below) runs beside the job instead of waiting and leaves that lock alone, printing `local-ci: running beside background job pid <pid> (<holder>), without the check lock`; it holds `check.lock.beside` meanwhile, so another check waits for it rather than overlapping, and signals still stop it and release that lock as above. Each check run appends its duration and outcome to the log when it ends, e.g. `[<end time>] abc1234: pnpm check passed in 71.2s` (or `failed in`, or `did not finish after` when the check is killed by a signal or can't start); a commit that already passed is skipped and logs nothing. Ctrl-C stops the check, which logs `did not finish after`.
64
65
 
65
66
  ### Taking the check lock from your own scripts
66
67
 
@@ -74,6 +75,6 @@ await withCheckLock("my-repo browser", async () => {
74
75
  });
75
76
  ```
76
77
 
77
- `withCheckLock(holder, fn, options?)` waits while another holder has the lock, logging `local-ci: waiting for the check lock, held by pid <pid> (<holder>)` to stderr as the CLI does, runs `fn`, and releases the lock when `fn` returns or throws. `holder` is the label other waiters see. `lockCheck(holder, options?)` does the take and returns the release function, for callers that can't wrap their work in a function. `options.file` overrides the lock path and `options.onWait` replaces the wait message. The path is `check.lock` in the state directory above, so no repo config is needed. A call nested under an ancestor process that holds the lock runs without waiting and leaves the lock alone. Pass `options.background: true` for a long job run after a push, such as a browser suite: it still waits for a running check, but `local-ci` checks (and other non-background callers) run beside it instead of waiting, so a push never sits in its hook behind its run. Background jobs still queue behind each other. A check run beside a background job takes `check.lock.beside` instead, so checks still run one at a time: a second check started during the job waits for the first, and whoever takes `check.lock` after the background job ends (another background job or a check) waits for a check still running beside it. A background job waiting that way holds `check.lock` as a check would, without the `background` line, until the beside check ends, so checks arriving meanwhile wait in turn rather than run beside a job that has not started. A check nested in a beside check runs under its lock without waiting. A beside lock whose holder died is taken over, as `check.lock` is. Versions before the beside lock ignore it, so a check from such a version (another repo pinned to an older local-ci) can still run beside a newer beside check. The lock file marks such a lock with a third line, `background`; a file without it (as older versions wrote) is waited on as before. SIGINT, SIGTERM or SIGHUP releases the lock and ends the process, so a job that needs its own signal cleanup should run it before calling the release itself. The package has an `exports` map, so deep imports other than `./lock` no longer resolve.
78
+ `withCheckLock(holder, fn, options?)` waits while another holder has the lock, logging `local-ci: waiting for the check lock, held by pid <pid> (<holder>)` to stderr as the CLI does, runs `fn`, and releases the lock when `fn` returns or throws. `holder` is the label other waiters see. `lockCheck(holder, options?)` does the take and returns the release function, for callers that can't wrap their work in a function. `options.file` overrides the lock path and `options.onWait` replaces the wait message. The path is `check.lock` in the state directory above, so no repo config is needed. A call nested under an ancestor process that holds the lock runs without waiting and leaves the lock alone. Pass `options.background: true` for a long job run after a push, such as a browser suite: it still waits for a running check, but `local-ci` checks (and other non-background callers) run beside it instead of waiting, so a push never sits in its hook behind its run. Background jobs queue behind each other in arrival order: each waiter writes a ticket file to `check.lock.queue/` with its pid, arrival time and head start, and takes the lock only when no live ticket sorts before its own. `options.headStartMs` (milliseconds, default 0) moves a background job up by that much: it sorts by arrival minus head start, so it passes jobs that arrived less than that long before it, and no others. A ticket whose process died, that predates the last boot, or that can't be parsed is removed by the next waiter that finds it, so a killed waiter can't wedge the queue. A job held back only by a ticket, with the lock free, says so: `local-ci: waiting for the check lock, held by pid <pid> (queued ahead)`. Checks take no ticket and never wait behind queued background jobs; when the lock is free, whichever polls first takes it. Versions before the queue ignore tickets, so a waiter from such a version (another repo pinned to an older local-ci) can still take the lock out of turn. A check run beside a background job takes `check.lock.beside` instead, so checks still run one at a time: a second check started during the job waits for the first, and whoever takes `check.lock` after the background job ends (another background job or a check) waits for a check still running beside it. A background job waiting that way holds `check.lock` as a check would, without the `background` line, until the beside check ends, so checks arriving meanwhile wait in turn rather than run beside a job that has not started. A check nested in a beside check runs under its lock without waiting. A beside lock whose holder died is taken over, as `check.lock` is. Versions before the beside lock ignore it, so a check from such a version (another repo pinned to an older local-ci) can still run beside a newer beside check. The lock file marks such a lock with a third line, `background`; a file without it (as older versions wrote) is waited on as before. SIGINT, SIGTERM or SIGHUP releases the lock and ends the process, so a job that needs its own signal cleanup should run it before calling the release itself. The package has an `exports` map, so deep imports other than `./lock` no longer resolve.
78
79
 
79
80
  Part of [jonmilner/config](https://github.com/jonmilner/config#readme).
@@ -16,6 +16,11 @@ export interface LockCheckOptions {
16
16
  * waits for a running check, but checks run beside it instead of waiting for it to finish.
17
17
  */
18
18
  background?: boolean;
19
+ /**
20
+ * With `background`, how many milliseconds earlier than its arrival this job counts as having
21
+ * arrived when queueing behind other background jobs. Default 0. Ignored for a check.
22
+ */
23
+ headStartMs?: number;
19
24
  }
20
25
  /** The machine-wide check lock's path, in `$XDG_STATE_HOME/local-ci` (default `~/.local/state`). */
21
26
  export declare function checkLockPath(env?: NodeJS.ProcessEnv): string;
@@ -25,8 +30,10 @@ export declare function checkLockPath(env?: NodeJS.ProcessEnv): string;
25
30
  * that holds the lock runs without waiting, and its release leaves the lock alone. A check (not
26
31
  * `background`) that finds a background job holding it runs beside the job under a second lock,
27
32
  * `<file>.beside`, instead: a second such check waits for it, and whoever takes the check lock
28
- * next waits for it to clear. SIGINT, SIGTERM and SIGHUP release the lock and end the process.
33
+ * next waits for it to clear. Background jobs take the lock in arrival order, less any
34
+ * `headStartMs`; a check doesn't queue. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
35
+ * process.
29
36
  */
30
- export declare function lockCheck(holder: string, { file, onWait, background }?: LockCheckOptions): Promise<() => void>;
37
+ export declare function lockCheck(holder: string, { file, onWait, background, headStartMs }?: LockCheckOptions): Promise<() => void>;
31
38
  /** Runs `fn` under the machine-wide check lock, so it queues behind `local-ci` checks and vice versa. */
32
39
  export declare function withCheckLock<T>(holder: string, fn: () => Promise<T>, options?: LockCheckOptions): Promise<T>;
@@ -8,7 +8,7 @@ import { ancestorsFrom } from "./push.js";
8
8
  function ancestors() {
9
9
  return new Set(ancestorsFrom(processTable(), process.ppid));
10
10
  }
11
- const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
11
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
12
12
  /** The check lock this process holds, the check running under it, and a signal it deferred. */
13
13
  let held;
14
14
  /** The check lock this process holds through `lockCheck`, if any, for the CLI to attach its check to. */
@@ -43,7 +43,7 @@ function onSignal(signal) {
43
43
  held = undefined;
44
44
  reraise(signal);
45
45
  }
46
- /** Holds `unlock` until the returned release, releasing it on SIGINT, SIGTERM or SIGHUP too. */
46
+ /** Holds `unlock` until the returned release, releasing it on SIGINT, SIGTERM, SIGHUP or SIGQUIT too. */
47
47
  function releaseOnSignal(unlock) {
48
48
  if (!process.listenerCount("SIGINT", onSignal)) {
49
49
  for (const name of SIGNALS)
@@ -75,9 +75,11 @@ function besideLockPath(file) {
75
75
  * that holds the lock runs without waiting, and its release leaves the lock alone. A check (not
76
76
  * `background`) that finds a background job holding it runs beside the job under a second lock,
77
77
  * `<file>.beside`, instead: a second such check waits for it, and whoever takes the check lock
78
- * next waits for it to clear. SIGINT, SIGTERM and SIGHUP release the lock and end the process.
78
+ * next waits for it to clear. Background jobs take the lock in arrival order, less any
79
+ * `headStartMs`; a check doesn't queue. SIGINT, SIGTERM, SIGHUP and SIGQUIT release the lock and end the
80
+ * process.
79
81
  */
80
- export async function lockCheck(holder, { file = checkLockPath(), onWait, background = false } = {}) {
82
+ export async function lockCheck(holder, { file = checkLockPath(), onWait, background = false, headStartMs = 0 } = {}) {
81
83
  const sidecar = besideLockPath(file);
82
84
  let mine;
83
85
  // A check nested in a check (one that pushes, say) runs under its ancestor's lock rather than
@@ -97,9 +99,10 @@ export async function lockCheck(holder, { file = checkLockPath(), onWait, backgr
97
99
  for (;;) {
98
100
  let beside = false;
99
101
  const skip = (held) => nested(held) || (beside = besides(held));
102
+ const queue = background ? { headStartMs } : undefined;
100
103
  // Taken as a check's lock even for a background job, so checks wait for it rather than run
101
104
  // beside it until it starts its run.
102
- const unlock = await waitForLock(file, { ...options, skip });
105
+ const unlock = await waitForLock(file, { ...options, skip, queue });
103
106
  if (unlock) {
104
107
  const release = releaseOnSignal(unlock);
105
108
  try {
package/dist/cli.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn, spawnSync } from "node:child_process";
3
3
  import { closeSync, openSync, readFileSync } from "node:fs";
4
- import { hostname } from "node:os";
4
+ import { constants, hostname } from "node:os";
5
5
  import { basename, dirname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { heldCheckLock, lockCheck } from "./check-lock.js";
7
+ import { heldCheckLock, lockCheck, withCheckLock } from "./check-lock.js";
8
8
  import { commitMsg } from "./commit-msg.js";
9
9
  import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, shimCommand, statePaths, } from "./config.js";
10
10
  import { exec, run } from "./exec.js";
@@ -25,6 +25,8 @@ const USAGE = `Usage:
25
25
  lint a commit message file (git commit-msg hook) or stdin (-)
26
26
  local-ci hooks install write the repo's pre-push and commit-msg hook shims
27
27
  local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
28
+ local-ci run -- <command>
29
+ run a command under the machine-wide check lock
28
30
  local-ci release version pending changesets through a PR, publish to npm and push tags
29
31
  local-ci release --check say whether release has anything to do, changing nothing
30
32
  local-ci renovate check each open Renovate PR in your repos and post check and pr-title
@@ -91,29 +93,34 @@ async function runCheck(current, sha) {
91
93
  unlock();
92
94
  }
93
95
  }
94
- /** Runs the check command under the check lock, logging its duration and recording a pass. */
95
- async function runLocked({ root, passed, log: logFile }, sha) {
96
+ /** Runs a program under the check lock, attached to it so a signal to local-ci reaches it. */
97
+ async function runHeld(file, args, cwd) {
96
98
  const held = heldCheckLock();
97
- const command = resolveCommand(root);
98
- err(`local-ci: running ${command} on ${sha.slice(0, 7)}`);
99
- const started = performance.now();
100
- const child = spawn("sh", ["-c", command], {
101
- cwd: root,
102
- // Its own process group, so onSignal can stop everything the check started. A nested check
103
- // has no handler and stays in its parent check's group, which that check's signal reaches.
99
+ const child = spawn(file, args, {
100
+ cwd,
101
+ // Its own process group, so onSignal can stop everything it started. A nested check has no
102
+ // handler and stays in its parent check's group, which that check's signal reaches.
104
103
  detached: held !== undefined,
105
104
  stdio: ["ignore", "inherit", "inherit"],
106
105
  });
107
106
  if (held)
108
107
  held.child = child;
109
108
  const result = await new Promise((resolve) => {
110
- child.on("error", (error) => resolve({ status: null, cause: error.message }));
111
- child.on("close", (status, signal) => resolve({ status, cause: signal ?? undefined }));
109
+ child.on("error", (error) => resolve({ status: null, error: error.message }));
110
+ child.on("close", (status, signal) => resolve({ status, signal }));
112
111
  });
113
112
  if (held)
114
113
  held.child = undefined;
114
+ return { ...result, interrupted: held?.signal };
115
+ }
116
+ /** Runs the check command under the check lock, logging its duration and recording a pass. */
117
+ async function runLocked({ root, passed, log: logFile }, sha) {
118
+ const command = resolveCommand(root);
119
+ err(`local-ci: running ${command} on ${sha.slice(0, 7)}`);
120
+ const started = performance.now();
121
+ const result = await runHeld("sh", ["-c", command], root);
115
122
  // A check local-ci was told to stop never finished, whatever it exited with.
116
- const interrupted = held?.signal;
123
+ const { interrupted } = result;
117
124
  const status = interrupted ? null : result.status;
118
125
  // Every run's duration goes in the log, so a faster check can be measured against a slower one.
119
126
  // A log that can't be written must not change the check's outcome.
@@ -125,13 +132,32 @@ async function runLocked({ root, passed, log: logFile }, sha) {
125
132
  }
126
133
  // A spawn error or a signal means the check never finished, so it is not a failure to post.
127
134
  if (status === null) {
128
- const cause = interrupted ?? result.cause;
135
+ const cause = interrupted ?? result.error ?? result.signal;
129
136
  throw new Error(`${command} did not finish on ${sha.slice(0, 7)}: ${cause}`);
130
137
  }
131
138
  if (status !== 0)
132
139
  throw new CheckFailed(command, sha);
133
140
  recordPass(passed, sha, command);
134
141
  }
142
+ /**
143
+ * Runs `-- <command>` under the check lock, so a full check started by hand waits its turn with
144
+ * the checks `pre-push` runs. Exits with the command's status, or 128 plus the signal that ended it.
145
+ */
146
+ async function runUnderLock(args) {
147
+ const [separator, file, ...rest] = args;
148
+ if (separator !== "--" || !file)
149
+ throw new Error(`run: expected -- <command>\n${USAGE}`);
150
+ // Outside a git repo there is no repo name, and nothing else here needs one.
151
+ const name = (await repo().catch(() => undefined))?.name ?? basename(process.cwd());
152
+ // Other sessions print this while they wait, so a long script mustn't fill their output.
153
+ const command = [file, ...rest].join(" ");
154
+ const label = command.length > 60 ? `${command.slice(0, 57)}...` : command;
155
+ // After a signal the release dies of it, so a command told to stop never reports a status.
156
+ const result = await withCheckLock(`${name} ${label}`, () => runHeld(file, rest));
157
+ if (result.error)
158
+ throw new Error(`could not run ${file}: ${result.error}`);
159
+ process.exitCode = result.status ?? 128 + constants.signals[result.signal];
160
+ }
135
161
  /** The repo root, its hooks directory, and the command its hook shims run local-ci with. */
136
162
  async function hooksTarget(root) {
137
163
  // `git config --get` exits 1 when the key is unset.
@@ -308,6 +334,8 @@ async function main([command, ...args]) {
308
334
  }
309
335
  if (command === "hooks")
310
336
  return runHooks(args);
337
+ if (command === "run")
338
+ return runUnderLock(args);
311
339
  if (command === "release")
312
340
  return runRelease(args);
313
341
  if (command === "renovate")
package/dist/lock.d.ts CHANGED
@@ -38,8 +38,18 @@ export interface WaitForLockOptions extends TakeLockOptions {
38
38
  holder?: string;
39
39
  /** A holder this caller need not wait behind: the wait ends, returning `undefined`, untaken. */
40
40
  skip?: (held: LockHeld) => boolean;
41
- /** Called when the wait starts, and again whenever another process takes the lock first. */
41
+ /**
42
+ * Called when the wait starts, and again whenever another process takes the lock first. A queued
43
+ * waiter held back only by another waiter's ticket gets that waiter, with the holder `queued ahead`.
44
+ */
42
45
  onWait?: (held: LockHeld) => void;
46
+ /**
47
+ * Waits in line for the lock: this caller takes it only when no live waiter's arrival minus head
48
+ * start sorts before its own. Waiters without this option don't queue and aren't held back.
49
+ */
50
+ queue?: {
51
+ headStartMs: number;
52
+ };
43
53
  intervalMs?: number;
44
54
  sleep?: (ms: number) => Promise<void>;
45
55
  }
package/dist/lock.js CHANGED
@@ -1,5 +1,7 @@
1
- import { linkSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
3
  import { uptime } from "node:os";
4
+ import { join } from "node:path";
3
5
  import { defaultSleep } from "./github.js";
4
6
  /** Whether a process with this pid is running. */
5
7
  export function alive(pid) {
@@ -131,27 +133,115 @@ export function takeLock(file, what = "release", holder, options = {}) {
131
133
  rmSync(mine, { force: true });
132
134
  }
133
135
  }
136
+ const queueDir = (file) => `${file}.queue`;
137
+ /** Earliest arrival minus head start first; arrival, then name, settle a tie the same for everyone. */
138
+ function ticketOrder(a, b) {
139
+ return (a.arrival - a.headStartMs - (b.arrival - b.headStartMs) ||
140
+ a.arrival - b.arrival ||
141
+ (a.name < b.name ? -1 : 1));
142
+ }
143
+ /** Joins the queue for `file`, arriving now. */
144
+ function takeTicket(file, headStartMs) {
145
+ if (!Number.isFinite(headStartMs) || headStartMs < 0) {
146
+ throw new RangeError(`headStartMs must be a finite number of 0 or more, got ${headStartMs}`);
147
+ }
148
+ const dir = queueDir(file);
149
+ mkdirSync(dir, { recursive: true });
150
+ const ticket = {
151
+ name: `${process.pid}-${randomUUID()}`,
152
+ pid: process.pid,
153
+ arrival: Date.now(),
154
+ headStartMs,
155
+ };
156
+ // Renaming publishes it whole; the temporary name is beside the queue so nobody lists it.
157
+ const unpublished = `${dir}.${ticket.name}`;
158
+ writeFileSync(unpublished, `${ticket.pid}\n${ticket.arrival}\n${ticket.headStartMs}`);
159
+ renameSync(unpublished, join(dir, ticket.name));
160
+ return ticket;
161
+ }
162
+ /** The ticket stored at `path`, or `undefined` for one that is gone or can't be read. */
163
+ function readTicket(path, name) {
164
+ let content;
165
+ try {
166
+ content = readFileSync(path, "utf8");
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ const [pid = NaN, arrival = NaN, headStartMs = NaN] = content
172
+ .split("\n")
173
+ .map((field) => (field === "" ? NaN : Number(field)));
174
+ return { name, pid, arrival, headStartMs };
175
+ }
176
+ /** The live ticket that goes next before `mine`, if any, removing dead and pre-boot ones it finds. */
177
+ function ticketAhead(file, mine) {
178
+ const dir = queueDir(file);
179
+ let names;
180
+ try {
181
+ names = readdirSync(dir);
182
+ }
183
+ catch (error) {
184
+ if (error.code === "ENOENT")
185
+ return undefined;
186
+ throw error;
187
+ }
188
+ let ahead;
189
+ for (const name of names) {
190
+ if (name === mine.name)
191
+ continue;
192
+ const path = join(dir, name);
193
+ const ticket = readTicket(path, name);
194
+ if (!ticket)
195
+ continue;
196
+ if (!alive(ticket.pid) ||
197
+ beforeBoot(path) ||
198
+ !Number.isFinite(ticket.arrival) ||
199
+ !Number.isFinite(ticket.headStartMs)) {
200
+ rmSync(path, { force: true });
201
+ }
202
+ else if (ticketOrder(ticket, ahead ?? mine) < 0) {
203
+ ahead = ticket;
204
+ }
205
+ }
206
+ return ahead;
207
+ }
134
208
  /**
135
209
  * Takes the lock, polling while a live process holds it, and returns its release, or `undefined`
136
210
  * once it finds a holder `skip` accepts.
137
211
  */
138
212
  export async function waitForLock(file, options) {
139
- const { what, holder, skip, onWait, intervalMs = 1_000, sleep = defaultSleep } = options;
213
+ const { what, holder, skip, onWait, queue, intervalMs = 1_000, sleep = defaultSleep } = options;
214
+ const ticket = queue && takeTicket(file, queue.headStartMs);
140
215
  let last;
141
- for (;;) {
142
- try {
143
- return takeLock(file, what, holder, { background: options.background });
144
- }
145
- catch (error) {
146
- if (!(error instanceof LockHeld))
147
- throw error;
148
- if (skip?.(error))
216
+ try {
217
+ for (;;) {
218
+ const ahead = ticket && ticketAhead(file, ticket);
219
+ let held;
220
+ if (ahead) {
221
+ held = lockHolder(file, what);
222
+ }
223
+ else {
224
+ try {
225
+ return takeLock(file, what, holder, { background: options.background });
226
+ }
227
+ catch (error) {
228
+ if (!(error instanceof LockHeld))
229
+ throw error;
230
+ held = error;
231
+ }
232
+ }
233
+ if (held && skip?.(held))
149
234
  return undefined;
150
- const seen = `${error.pid}\n${error.holder}`;
235
+ const blocker = held ?? new LockHeld(what, file, ahead.pid, "queued ahead");
236
+ const seen = `${blocker.pid}\n${blocker.holder}`;
151
237
  if (seen !== last)
152
- onWait?.(error);
238
+ onWait?.(blocker);
153
239
  last = seen;
154
240
  await sleep(intervalMs);
155
241
  }
156
242
  }
243
+ finally {
244
+ if (ticket)
245
+ rmSync(join(queueDir(file), ticket.name), { force: true });
246
+ }
157
247
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Run a repo's check in a pre-push hook and post the result as GitHub commit statuses",
5
5
  "license": "MIT",
6
6
  "repository": {