next-issue 6.6.6 → 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
@@ -556,7 +556,11 @@ affect another. The worker:
556
556
  with that id started at another time, for example because the system gave
557
557
  the id of a worker that was killed or lost in a reboot to another process.
558
558
  A lock without a start time, from an older version, is stale too. A worker
559
- that cannot read its own start time exits with an error and takes no lock;
559
+ that cannot read its own start time exits with an error and takes no lock.
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 lock file
562
+ only while it still holds the lock, and the socket file only while it is
563
+ still the socket it bound;
560
564
  - refuses a `start`, `stop` or `questions` message whose `root` is not
561
565
  the exact path of its repository with an `error` message, and starts or
562
566
  stops nothing;
package/dist/lock.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { rm, writeFile } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFileSync, statSync } from 'node:fs';
4
+ import { link, open, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { basename, dirname, join } from 'node:path';
3
6
  import { setTimeout as delay } from 'node:timers/promises';
4
7
  import { promisify } from 'node:util';
5
8
  import { hasCode } from './errors.mjs';
6
- import { readTextOrEmpty } from './files.mjs';
9
+ import { readTextOrEmpty, unlessMissing } from './files.mjs';
7
10
  const LOCK_POLL_MS = 100;
8
11
  const worktreeQueues = new Map();
9
12
  export function oneAtATime(root, work) {
@@ -26,8 +29,8 @@ export async function processStart(pid) {
26
29
  return undefined;
27
30
  }
28
31
  }
29
- async function holder(lockPath) {
30
- const [first = '', ...rest] = (await readTextOrEmpty(lockPath)).trim().split(' ');
32
+ async function holderOf(text) {
33
+ const [first = '', ...rest] = text.trim().split(' ');
31
34
  const pid = Number(first);
32
35
  const started = rest.join(' ');
33
36
  if (!(pid > 0) || started === '') {
@@ -35,6 +38,111 @@ async function holder(lockPath) {
35
38
  }
36
39
  return (await processStart(pid)) === started ? pid : undefined;
37
40
  }
41
+ async function holder(lockPath) {
42
+ return holderOf(await readTextOrEmpty(lockPath));
43
+ }
44
+ function idOf(found) {
45
+ return `${found.dev}:${found.ino}`;
46
+ }
47
+ function draftPath(path) {
48
+ return `${path}.${process.pid}.${randomUUID()}`;
49
+ }
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 };
64
+ }
65
+ async function take(path, text) {
66
+ const draft = draftPath(path);
67
+ await writeFile(draft, text, { flag: 'wx', mode: 0o600 });
68
+ try {
69
+ await link(draft, path);
70
+ return idOf(await stat(draft));
71
+ }
72
+ catch (error) {
73
+ if (!hasCode(error, 'EEXIST')) {
74
+ throw error;
75
+ }
76
+ return undefined;
77
+ }
78
+ finally {
79
+ await rm(draft, { force: true });
80
+ }
81
+ }
82
+ async function removeIfSame(path, id) {
83
+ const moved = draftPath(path);
84
+ try {
85
+ await rename(path, moved);
86
+ }
87
+ catch (error) {
88
+ if (hasCode(error, 'ENOENT')) {
89
+ return;
90
+ }
91
+ throw error;
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
+ }
105
+ }
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);
115
+ }
116
+ return;
117
+ }
118
+ try {
119
+ const found = await lockState(path);
120
+ if (found.state === 'stale') {
121
+ await removeIfSame(path, found.id);
122
+ }
123
+ }
124
+ finally {
125
+ await rm(guard, { force: true });
126
+ }
127
+ }
128
+ function isAlive(pid) {
129
+ try {
130
+ process.kill(pid, 0);
131
+ return true;
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
+ }
38
146
  export async function stopWorker(lockPath) {
39
147
  const pid = await holder(lockPath);
40
148
  if (pid !== undefined) {
@@ -42,32 +150,43 @@ export async function stopWorker(lockPath) {
42
150
  }
43
151
  return pid;
44
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
+ };
168
+ }
45
169
  export async function lock(path, waitMs, readStart = processStart) {
46
170
  const started = await readStart(process.pid);
47
171
  if (started === undefined) {
48
172
  throw new Error('next-issue: cannot read the start time of the worker process');
49
173
  }
174
+ const text = `${process.pid} ${started}\n`;
50
175
  const deadline = Date.now() + waitMs;
51
176
  for (;;) {
52
- try {
53
- await writeFile(path, `${process.pid} ${started}\n`, {
54
- flag: 'wx',
55
- mode: 0o600,
56
- });
57
- return true;
177
+ const id = await take(path, text);
178
+ if (id !== undefined) {
179
+ await removeDeadDrafts(path);
180
+ return heldLock(path, id, text);
58
181
  }
59
- catch (error) {
60
- if (!hasCode(error, 'EEXIST')) {
61
- throw error;
62
- }
182
+ const found = await lockState(path);
183
+ if (found.state === 'stale') {
184
+ await removeStale(path, text);
63
185
  }
64
- if ((await holder(path)) === undefined) {
65
- await rm(path, { force: true });
66
- }
67
- else if (Date.now() >= deadline) {
68
- return false;
69
- }
70
- else {
186
+ else if (found.state === 'held') {
187
+ if (Date.now() >= deadline) {
188
+ return undefined;
189
+ }
71
190
  await delay(LOCK_POLL_MS);
72
191
  }
73
192
  }
package/dist/serve.mjs CHANGED
@@ -1,7 +1,6 @@
1
- import { rmSync } from 'node:fs';
2
- import { mkdir, rm } from 'node:fs/promises';
1
+ import { mkdir, rename, rm } from 'node:fs/promises';
3
2
  import { createServer } from 'node:http';
4
- import { dirname } 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';
@@ -14,16 +13,22 @@ import { runRepo } from './run.mjs';
14
13
  import { packageVersion } from './version.mjs';
15
14
  import { checkSocketPath, workerPaths } from './worker-paths.mjs';
16
15
  import { active, endStatus, newRun, requestStop, runControls, runsMessage, startRefusal, stopPoint, } from './worker-run.mjs';
17
- import { broadcast, closer, listen, parseMessage, shutdown, } from './worker-server.mjs';
16
+ import { broadcast, closer, fileId, listen, parseMessage, removeOwned, shutdown, } from './worker-server.mjs';
18
17
  const LOCK_WAIT_MS = 5_000;
19
18
  const IDLE_MS = 30_000;
20
19
  export async function startWorker(options) {
21
20
  checkSocketPath(options.socketPath);
22
21
  await mkdir(dirname(options.lockPath), { recursive: true });
23
- if (!(await lock(options.lockPath, options.lockWaitMs ?? LOCK_WAIT_MS))) {
22
+ const held = await lock(options.lockPath, options.lockWaitMs ?? LOCK_WAIT_MS);
23
+ if (held === undefined) {
24
24
  return undefined;
25
25
  }
26
- await rm(options.socketPath, { force: true });
26
+ const owned = {
27
+ socketPath: options.socketPath,
28
+ lockPath: options.lockPath,
29
+ lock: held,
30
+ socket: '',
31
+ };
27
32
  const runs = new Map();
28
33
  let restart = false;
29
34
  const server = createServer();
@@ -33,7 +38,7 @@ export async function startWorker(options) {
33
38
  let idleTimer;
34
39
  const { closed, close } = closer(async () => {
35
40
  clearTimeout(idleTimer);
36
- await shutdown(server, sockets, options);
41
+ await shutdown(server, sockets, owned);
37
42
  });
38
43
  const closeWhenIdle = () => {
39
44
  if ((restart || sockets.clients.size === 0) && !busy()) {
@@ -120,9 +125,13 @@ export async function startWorker(options) {
120
125
  }
121
126
  });
122
127
  });
123
- await listen(server, 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);
124
133
  idleTimer = setTimeout(closeWhenIdle, options.idleMs ?? IDLE_MS);
125
- return { closed, close };
134
+ return { closed, close, release: () => removeOwned(owned) };
126
135
  }
127
136
  export async function serve(root) {
128
137
  const paths = workerPaths(root);
@@ -140,8 +149,7 @@ export async function serve(root) {
140
149
  const end = (signal) => {
141
150
  process.off('SIGTERM', onTerminate);
142
151
  process.off('SIGINT', onInterrupt);
143
- rmSync(paths.socketPath, { force: true });
144
- rmSync(paths.lockPath, { force: true });
152
+ worker.release();
145
153
  stopChildren(signal);
146
154
  };
147
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,14 +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) {
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
- await rm(paths.socketPath, { force: true });
66
- await rm(paths.lockPath, { force: true });
77
+ removeOwned(owned);
67
78
  }
68
79
  export function closer(stop) {
69
80
  let finish = () => undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-issue",
3
- "version": "6.6.6",
3
+ "version": "6.6.8",
4
4
  "description": "Autonomous issue harness driven by the pi SDK",
5
5
  "keywords": [
6
6
  "github",