next-issue 6.6.7 → 6.6.8

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
@@ -558,8 +558,9 @@ affect another. The worker:
558
558
  A lock without a start time, from an older version, is stale too. A worker
559
559
  that cannot read its own start time exits with an error and takes no lock.
560
560
  When several workers start at once, one takes the lock and the others exit
561
- with `another worker is running`. A worker that stops removes the socket
562
- and lock files only while it still holds the lock;
561
+ with `another worker is running`. A worker that stops removes the lock file
562
+ only while it still holds the lock, and the socket file only while it is
563
+ still the socket it bound;
563
564
  - refuses a `start`, `stop` or `questions` message whose `root` is not
564
565
  the exact path of its repository with an `error` message, and starts or
565
566
  stops nothing;
package/dist/lock.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { readFileSync, statSync } from 'node:fs';
4
- import { link, rm, writeFile } from 'node:fs/promises';
4
+ import { link, open, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { basename, dirname, join } from 'node:path';
5
6
  import { setTimeout as delay } from 'node:timers/promises';
6
7
  import { promisify } from 'node:util';
7
8
  import { hasCode } from './errors.mjs';
8
- import { readTextIfPresent, readTextOrEmpty } from './files.mjs';
9
+ import { readTextOrEmpty, unlessMissing } from './files.mjs';
9
10
  const LOCK_POLL_MS = 100;
10
11
  const worktreeQueues = new Map();
11
12
  export function oneAtATime(root, work) {
@@ -40,84 +41,153 @@ async function holderOf(text) {
40
41
  async function holder(lockPath) {
41
42
  return holderOf(await readTextOrEmpty(lockPath));
42
43
  }
43
- async function isStale(lockPath) {
44
- const text = await readTextIfPresent(lockPath);
45
- return text !== undefined && (await holderOf(text)) === undefined;
44
+ function idOf(found) {
45
+ return `${found.dev}:${found.ino}`;
46
46
  }
47
- export async function stopWorker(lockPath) {
48
- const pid = await holder(lockPath);
49
- if (pid !== undefined) {
50
- process.kill(pid, 'SIGTERM');
51
- }
52
- return pid;
47
+ function draftPath(path) {
48
+ return `${path}.${process.pid}.${randomUUID()}`;
53
49
  }
54
- function inode(path) {
55
- return statSync(path, { throwIfNoEntry: false })?.ino;
50
+ async function lockState(path) {
51
+ const read = await unlessMissing(async () => {
52
+ const file = await open(path, 'r');
53
+ try {
54
+ return { id: idOf(await file.stat()), text: await file.readFile('utf8') };
55
+ }
56
+ finally {
57
+ await file.close();
58
+ }
59
+ });
60
+ if (read === undefined) {
61
+ return { state: 'missing' };
62
+ }
63
+ return { state: (await holderOf(read.text)) === undefined ? 'stale' : 'held', id: read.id };
56
64
  }
57
- function textOf(path) {
65
+ async function take(path, text) {
66
+ const draft = draftPath(path);
67
+ await writeFile(draft, text, { flag: 'wx', mode: 0o600 });
58
68
  try {
59
- return readFileSync(path, 'utf8');
69
+ await link(draft, path);
70
+ return idOf(await stat(draft));
60
71
  }
61
- catch {
72
+ catch (error) {
73
+ if (!hasCode(error, 'EEXIST')) {
74
+ throw error;
75
+ }
62
76
  return undefined;
63
77
  }
78
+ finally {
79
+ await rm(draft, { force: true });
80
+ }
64
81
  }
65
- async function linked(source, target) {
82
+ async function removeIfSame(path, id) {
83
+ const moved = draftPath(path);
66
84
  try {
67
- await link(source, target);
68
- return true;
85
+ await rename(path, moved);
69
86
  }
70
87
  catch (error) {
71
- if (hasCode(error, 'EEXIST')) {
72
- return false;
88
+ if (hasCode(error, 'ENOENT')) {
89
+ return;
73
90
  }
74
91
  throw error;
75
92
  }
93
+ try {
94
+ if (idOf(await stat(moved)) !== id) {
95
+ await link(moved, path).catch((error) => {
96
+ if (!hasCode(error, 'EEXIST')) {
97
+ throw error;
98
+ }
99
+ });
100
+ }
101
+ }
102
+ finally {
103
+ await rm(moved, { force: true });
104
+ }
76
105
  }
77
- async function removeStale(path, filled) {
78
- const breakPath = `${path}.break`;
79
- if (!(await linked(filled, breakPath))) {
80
- if (await isStale(breakPath)) {
81
- await rm(breakPath, { force: true });
106
+ async function removeStale(path, text) {
107
+ const guard = `${path}.break`;
108
+ if ((await take(guard, text)) === undefined) {
109
+ const found = await lockState(guard);
110
+ if (found.state === 'stale') {
111
+ await removeIfSame(guard, found.id);
112
+ }
113
+ else if (found.state === 'held') {
114
+ await delay(LOCK_POLL_MS);
82
115
  }
83
116
  return;
84
117
  }
85
118
  try {
86
- if (await isStale(path)) {
87
- await rm(path, { force: true });
119
+ const found = await lockState(path);
120
+ if (found.state === 'stale') {
121
+ await removeIfSame(path, found.id);
88
122
  }
89
123
  }
90
124
  finally {
91
- await rm(breakPath, { force: true });
125
+ await rm(guard, { force: true });
126
+ }
127
+ }
128
+ function isAlive(pid) {
129
+ try {
130
+ process.kill(pid, 0);
131
+ return true;
92
132
  }
133
+ catch (error) {
134
+ return !hasCode(error, 'ESRCH');
135
+ }
136
+ }
137
+ async function removeDeadDrafts(path) {
138
+ const name = basename(path);
139
+ for (const entry of await readdir(dirname(path))) {
140
+ const pid = /^\.(?:break\.)?(\d+)\.[0-9a-f-]{36}$/.exec(entry.slice(name.length))?.[1];
141
+ if (entry.startsWith(name) && pid !== undefined && !isAlive(Number(pid))) {
142
+ await rm(join(dirname(path), entry), { force: true });
143
+ }
144
+ }
145
+ }
146
+ export async function stopWorker(lockPath) {
147
+ const pid = await holder(lockPath);
148
+ if (pid !== undefined) {
149
+ process.kill(pid, 'SIGTERM');
150
+ }
151
+ return pid;
152
+ }
153
+ function textOf(path) {
154
+ try {
155
+ return readFileSync(path, 'utf8');
156
+ }
157
+ catch {
158
+ return undefined;
159
+ }
160
+ }
161
+ function heldLock(path, id, text) {
162
+ return {
163
+ owns: () => {
164
+ const found = statSync(path, { throwIfNoEntry: false });
165
+ return found !== undefined && idOf(found) === id && textOf(path) === text;
166
+ },
167
+ };
93
168
  }
94
169
  export async function lock(path, waitMs, readStart = processStart) {
95
170
  const started = await readStart(process.pid);
96
171
  if (started === undefined) {
97
172
  throw new Error('next-issue: cannot read the start time of the worker process');
98
173
  }
99
- const filled = `${path}.${randomUUID()}`;
100
174
  const text = `${process.pid} ${started}\n`;
101
- await writeFile(filled, text, { flag: 'wx', mode: 0o600 });
102
- try {
103
- const deadline = Date.now() + waitMs;
104
- for (;;) {
105
- if (await linked(filled, path)) {
106
- const held = inode(path);
107
- return {
108
- owns: () => held !== undefined && inode(path) === held && textOf(path) === text,
109
- };
110
- }
111
- if ((await holder(path)) === undefined) {
112
- await removeStale(path, filled);
113
- }
114
- else if (Date.now() >= deadline) {
175
+ const deadline = Date.now() + waitMs;
176
+ for (;;) {
177
+ const id = await take(path, text);
178
+ if (id !== undefined) {
179
+ await removeDeadDrafts(path);
180
+ return heldLock(path, id, text);
181
+ }
182
+ const found = await lockState(path);
183
+ if (found.state === 'stale') {
184
+ await removeStale(path, text);
185
+ }
186
+ else if (found.state === 'held') {
187
+ if (Date.now() >= deadline) {
115
188
  return undefined;
116
189
  }
117
190
  await delay(LOCK_POLL_MS);
118
191
  }
119
192
  }
120
- finally {
121
- await rm(filled, { force: true });
122
- }
123
193
  }
package/dist/serve.mjs CHANGED
@@ -1,12 +1,10 @@
1
- import { rmSync } from 'node:fs';
2
1
  import { mkdir, rename, rm } from 'node:fs/promises';
3
2
  import { createServer } from 'node:http';
4
- import { dirname, join } from 'node:path';
3
+ import { basename, dirname, join } from 'node:path';
5
4
  import { WebSocketServer } from 'ws';
6
5
  import { parseStartArgs } from './args.mjs';
7
6
  import { stopChildren, withRunChildren } from './children.mjs';
8
7
  import { message } from './errors.mjs';
9
- import { listOrEmpty } from './files.mjs';
10
8
  import { lock } from './lock.mjs';
11
9
  import { startProgress } from './progress.mjs';
12
10
  import { isNewer } from './protocol.mjs';
@@ -15,7 +13,7 @@ import { runRepo } from './run.mjs';
15
13
  import { packageVersion } from './version.mjs';
16
14
  import { checkSocketPath, workerPaths } from './worker-paths.mjs';
17
15
  import { active, endStatus, newRun, requestStop, runControls, runsMessage, startRefusal, stopPoint, } from './worker-run.mjs';
18
- import { broadcast, closer, listen, parseMessage, shutdown, } from './worker-server.mjs';
16
+ import { broadcast, closer, fileId, listen, parseMessage, removeOwned, shutdown, } from './worker-server.mjs';
19
17
  const LOCK_WAIT_MS = 5_000;
20
18
  const IDLE_MS = 30_000;
21
19
  export async function startWorker(options) {
@@ -25,13 +23,12 @@ export async function startWorker(options) {
25
23
  if (held === undefined) {
26
24
  return undefined;
27
25
  }
28
- const stateDir = dirname(options.socketPath);
29
- const bindPath = join(stateDir, `s${process.pid}`);
30
- for (const name of await listOrEmpty(stateDir)) {
31
- if (/^s\d+$/.test(name)) {
32
- await rm(join(stateDir, name), { force: true });
33
- }
34
- }
26
+ const owned = {
27
+ socketPath: options.socketPath,
28
+ lockPath: options.lockPath,
29
+ lock: held,
30
+ socket: '',
31
+ };
35
32
  const runs = new Map();
36
33
  let restart = false;
37
34
  const server = createServer();
@@ -41,7 +38,7 @@ export async function startWorker(options) {
41
38
  let idleTimer;
42
39
  const { closed, close } = closer(async () => {
43
40
  clearTimeout(idleTimer);
44
- await shutdown(server, sockets, options, held);
41
+ await shutdown(server, sockets, owned);
45
42
  });
46
43
  const closeWhenIdle = () => {
47
44
  if ((restart || sockets.clients.size === 0) && !busy()) {
@@ -128,10 +125,13 @@ export async function startWorker(options) {
128
125
  }
129
126
  });
130
127
  });
131
- await listen(server, bindPath);
132
- await rename(bindPath, options.socketPath);
128
+ const draft = join(dirname(options.socketPath), `~${basename(options.socketPath).slice(1)}`);
129
+ await rm(draft, { force: true });
130
+ await listen(server, draft);
131
+ await rename(draft, options.socketPath);
132
+ owned.socket = fileId(options.socketPath);
133
133
  idleTimer = setTimeout(closeWhenIdle, options.idleMs ?? IDLE_MS);
134
- return { closed, close, lock: held };
134
+ return { closed, close, release: () => removeOwned(owned) };
135
135
  }
136
136
  export async function serve(root) {
137
137
  const paths = workerPaths(root);
@@ -149,10 +149,7 @@ export async function serve(root) {
149
149
  const end = (signal) => {
150
150
  process.off('SIGTERM', onTerminate);
151
151
  process.off('SIGINT', onInterrupt);
152
- if (worker.lock.owns()) {
153
- rmSync(paths.socketPath, { force: true });
154
- rmSync(paths.lockPath, { force: true });
155
- }
152
+ worker.release();
156
153
  stopChildren(signal);
157
154
  };
158
155
  const onTerminate = () => end('SIGTERM');
@@ -1,4 +1,4 @@
1
- import { rm } from 'node:fs/promises';
1
+ import { rmSync, statSync } from 'node:fs';
2
2
  import { send } from './questions.mjs';
3
3
  import { runsMessage } from './worker-run.mjs';
4
4
  function isRecord(value) {
@@ -56,16 +56,25 @@ export function listen(server, path) {
56
56
  function whenClosed(close) {
57
57
  return new Promise((resolve) => close(() => resolve()));
58
58
  }
59
- export async function shutdown(server, sockets, paths, held) {
59
+ export function fileId(path) {
60
+ const found = statSync(path, { throwIfNoEntry: false });
61
+ return found?.isSocket() === true ? `${found.dev}:${found.ino}` : '';
62
+ }
63
+ export function removeOwned(owned) {
64
+ if (owned.socket !== '' && fileId(owned.socketPath) === owned.socket) {
65
+ rmSync(owned.socketPath, { force: true });
66
+ }
67
+ if (owned.lock.owns()) {
68
+ rmSync(owned.lockPath, { force: true });
69
+ }
70
+ }
71
+ export async function shutdown(server, sockets, owned) {
60
72
  for (const socket of sockets.clients) {
61
73
  socket.terminate();
62
74
  }
63
75
  await whenClosed((done) => sockets.close(done));
64
76
  await whenClosed((done) => server.close(done));
65
- if (held.owns()) {
66
- await rm(paths.socketPath, { force: true });
67
- await rm(paths.lockPath, { force: true });
68
- }
77
+ removeOwned(owned);
69
78
  }
70
79
  export function closer(stop) {
71
80
  let finish = () => undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-issue",
3
- "version": "6.6.7",
3
+ "version": "6.6.8",
4
4
  "description": "Autonomous issue harness driven by the pi SDK",
5
5
  "keywords": [
6
6
  "github",