peerband 0.1.3 → 0.1.6
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 +53 -14
- package/dist/peerband.mjs +2686 -919
- package/herdr/README.md +18 -18
- package/herdr/control.mjs +2 -1
- package/herdr/launch.mjs +87 -87
- package/herdr/lifecycle.mjs +141 -55
- package/herdr/pane.mjs +124 -46
- package/herdr/relay-tab.mjs +17 -0
- package/herdr/stale-lock.mjs +200 -0
- package/herdr-plugin.toml +1 -1
- package/install/install.ps1 +119 -118
- package/install/install.sh +12 -11
- package/package.json +2 -2
- package/protocol/README.md +8 -3
- package/protocol/relay-messages.schema.json +134 -78
- package/skills/peerband/SKILL.md +94 -0
package/herdr/pane.mjs
CHANGED
|
@@ -33,31 +33,54 @@ let busyError = false;
|
|
|
33
33
|
let snapshot = { state: "stopping", connectionState: "disabled", activity: [] };
|
|
34
34
|
let errorText = "";
|
|
35
35
|
let timer;
|
|
36
|
+
let reconnectTimer;
|
|
36
37
|
let control;
|
|
37
38
|
let controlBuffer = "";
|
|
38
39
|
const replies = [];
|
|
39
40
|
let ownsUi = false;
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
// Resolves when the current control socket has closed (replaced for every new socket).
|
|
42
|
+
let closed = Promise.resolve();
|
|
43
|
+
// While the helper is gone, the pane keeps trying to re-attach (without starting a helper itself), so a relay started
|
|
44
|
+
// another way (the plugin's Start action, `peerband relay`) is picked up and the tab label follows the real state.
|
|
45
|
+
const RECONNECT_MS = 2000;
|
|
46
|
+
const UNAVAILABLE = "Relay helper is not running. Press Space to start it, or run `peerband relay`.";
|
|
47
|
+
|
|
42
48
|
function draw() {
|
|
43
49
|
if (closing || !stdout.isTTY) return;
|
|
44
50
|
stdout.write("\x1b[2J\x1b[H" + renderPane({ snapshot, identity, email, messages, error: errorText, columns: stdout.columns, rows: stdout.rows }));
|
|
45
51
|
}
|
|
46
52
|
async function runLifecycle(command) {
|
|
47
|
-
|
|
53
|
+
// start-ui starts Node twice (lifecycle, then the helper); on a loaded machine that alone can take 10+ seconds.
|
|
54
|
+
const { stdout: result } = await exec(process.execPath, [lifecycle, command], { timeout: 45_000, windowsHide: true, maxBuffer: 65_536 });
|
|
48
55
|
return JSON.parse(result.trim());
|
|
49
56
|
}
|
|
57
|
+
const controlAlive = () => Boolean(control && !control.destroyed);
|
|
58
|
+
// Renaming the tab runs the herdr CLI (several processes). Do it when the On/Off state changes, not on every refresh.
|
|
59
|
+
let tabState;
|
|
60
|
+
function syncTab(enabled) {
|
|
61
|
+
if (tabState === enabled) return;
|
|
62
|
+
tabState = enabled;
|
|
63
|
+
// Retry on the next refresh when the rename did not happen (it returns false without running herdr when this pane
|
|
64
|
+
// is not the recorded Relay tab).
|
|
65
|
+
const retry = () => { if (tabState === enabled) tabState = undefined; };
|
|
66
|
+
void syncRelayTab(enabled).then((renamed) => { if (!renamed) retry(); }, retry);
|
|
67
|
+
}
|
|
68
|
+
function showUnavailable(message = UNAVAILABLE) {
|
|
69
|
+
snapshot = { state: "stopping", connectionState: "helper-unavailable", activity: snapshot?.activity ?? [] };
|
|
70
|
+
errorText = message;
|
|
71
|
+
syncTab(false);
|
|
72
|
+
}
|
|
50
73
|
async function refresh() {
|
|
51
74
|
if (closing || pending || refreshInFlight) return;
|
|
75
|
+
if (!controlAlive()) { scheduleReconnect(); return; }
|
|
52
76
|
refreshInFlight = true;
|
|
53
77
|
const generation = refreshGeneration;
|
|
54
78
|
try {
|
|
55
79
|
const next = await sendUi("ui-status");
|
|
56
|
-
if (generation === refreshGeneration) { snapshot = next; if (!busyError) errorText = "";
|
|
80
|
+
if (generation === refreshGeneration) { snapshot = next; if (!busyError) errorText = ""; syncTab(next.state === "running"); }
|
|
57
81
|
} catch {
|
|
58
82
|
if (generation !== refreshGeneration) return;
|
|
59
|
-
|
|
60
|
-
errorText = "Helper control channel unavailable. Reopen peerband relay to reconnect.";
|
|
83
|
+
showUnavailable();
|
|
61
84
|
} finally { refreshInFlight = false; }
|
|
62
85
|
draw();
|
|
63
86
|
}
|
|
@@ -70,10 +93,17 @@ async function toggle() {
|
|
|
70
93
|
closeArmed = false;
|
|
71
94
|
draw();
|
|
72
95
|
try {
|
|
96
|
+
if (!controlAlive()) {
|
|
97
|
+
// No helper: Space starts one, like opening the tab does. That can take a while on a busy machine.
|
|
98
|
+
errorText = "Starting the PeerBand relay…";
|
|
99
|
+
draw();
|
|
100
|
+
await attach({ start: true });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
73
103
|
const next = await sendUi(snapshot?.state === "running" ? "ui-disable" : "ui-enable");
|
|
74
104
|
if (next.error === "busy") throw new Error("The relay is still stopping. Try On again in a moment.");
|
|
75
105
|
snapshot = next;
|
|
76
|
-
|
|
106
|
+
syncTab(next.state === "running");
|
|
77
107
|
} catch (error) {
|
|
78
108
|
errorText = error.message || "Could not change the connection. Check enrollment and the helper owner.";
|
|
79
109
|
busyError = error.message === "The relay is still stopping. Try On again in a moment.";
|
|
@@ -86,6 +116,7 @@ async function close() {
|
|
|
86
116
|
if (closing) return;
|
|
87
117
|
closing = true;
|
|
88
118
|
clearInterval(timer);
|
|
119
|
+
clearTimeout(reconnectTimer);
|
|
89
120
|
stopInput();
|
|
90
121
|
process.stdin.off("end", onInputEnd);
|
|
91
122
|
process.stdin.off("close", onInputEnd);
|
|
@@ -93,7 +124,7 @@ async function close() {
|
|
|
93
124
|
process.off("SIGTERM", onSignal);
|
|
94
125
|
process.off("SIGHUP", onSignal);
|
|
95
126
|
stdout.write("\x1b[2J\x1b[HDisconnecting PeerBand relay…\n");
|
|
96
|
-
if (ownsUi) {
|
|
127
|
+
if (ownsUi && controlAlive()) {
|
|
97
128
|
try { await sendUi("ui-close"); } catch { /* socket closure also owns final cleanup */ }
|
|
98
129
|
control?.end();
|
|
99
130
|
} else control?.destroy();
|
|
@@ -113,6 +144,83 @@ const stopInput = startPaneInput({ boxRows: controlBoxRows(email), onToggle: tog
|
|
|
113
144
|
errorText = "Closing disconnects the relay. Press q again to close; reopen with `peerband relay`.";
|
|
114
145
|
draw();
|
|
115
146
|
} });
|
|
147
|
+
|
|
148
|
+
function wireControl(socket) {
|
|
149
|
+
let resolveClosed;
|
|
150
|
+
closed = new Promise((resolve) => { resolveClosed = resolve; });
|
|
151
|
+
controlBuffer = "";
|
|
152
|
+
socket.on("data", (chunk) => {
|
|
153
|
+
if (control !== socket) return;
|
|
154
|
+
controlBuffer += chunk.toString();
|
|
155
|
+
if (controlBuffer.length > 65_536) { failControl(new Error("Invalid relay control response")); return; }
|
|
156
|
+
let newline;
|
|
157
|
+
while ((newline = controlBuffer.indexOf("\n")) >= 0) {
|
|
158
|
+
const line = controlBuffer.slice(0, newline);
|
|
159
|
+
controlBuffer = controlBuffer.slice(newline + 1);
|
|
160
|
+
let value;
|
|
161
|
+
try { value = JSON.parse(line); } catch { failControl(new Error("Invalid relay control response")); return; }
|
|
162
|
+
const request = replies.shift();
|
|
163
|
+
if (request) { clearTimeout(request.timer); request.resolve(value); }
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
let lost = false;
|
|
167
|
+
const onLost = (message) => {
|
|
168
|
+
if (lost) return;
|
|
169
|
+
lost = true;
|
|
170
|
+
resolveClosed();
|
|
171
|
+
if (control !== socket) return;
|
|
172
|
+
rejectReplies(new Error(message));
|
|
173
|
+
if (closing) return;
|
|
174
|
+
ownsUi = false;
|
|
175
|
+
showUnavailable(errorText || UNAVAILABLE);
|
|
176
|
+
draw();
|
|
177
|
+
scheduleReconnect();
|
|
178
|
+
};
|
|
179
|
+
socket.on("close", () => onLost("Relay owner channel closed"));
|
|
180
|
+
socket.on("error", () => onLost("Relay owner channel failed"));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Connects to the helper and takes UI ownership. `start`: start a helper if none answers and turn the relay on.
|
|
184
|
+
async function attach({ start }) {
|
|
185
|
+
let socket;
|
|
186
|
+
try { socket = await connectControl(); }
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (!start) throw error;
|
|
189
|
+
await runLifecycle("start-ui");
|
|
190
|
+
socket = await connectControl();
|
|
191
|
+
}
|
|
192
|
+
if (closing) { socket.destroy(); return; }
|
|
193
|
+
control = socket;
|
|
194
|
+
wireControl(socket);
|
|
195
|
+
const attached = await sendUi("attach-ui");
|
|
196
|
+
if (attached.error === "ui-owned") throw new Error("Another relay pane already owns this installation. Close it before reopening.");
|
|
197
|
+
ownsUi = true;
|
|
198
|
+
snapshot = start ? await sendUi("ui-enable") : attached;
|
|
199
|
+
errorText = "";
|
|
200
|
+
syncTab(snapshot.state === "running");
|
|
201
|
+
draw();
|
|
202
|
+
if (!timer) {
|
|
203
|
+
timer = setInterval(refresh, 1000);
|
|
204
|
+
timer.unref();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// `start` (used once, after the first attempt failed, e.g. a slow first start right after an update) may start a
|
|
209
|
+
// helper; later retries only re-attach to one that something else started.
|
|
210
|
+
function scheduleReconnect(start = false) {
|
|
211
|
+
if (closing || reconnectTimer || controlAlive()) return;
|
|
212
|
+
reconnectTimer = setTimeout(async () => {
|
|
213
|
+
reconnectTimer = undefined;
|
|
214
|
+
if (closing || controlAlive() || pending) { if (!controlAlive()) scheduleReconnect(); return; }
|
|
215
|
+
try { await attach({ start }); }
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (control && !control.destroyed) control.destroy();
|
|
218
|
+
if (/already owns/.test(error.message || "")) { errorText = error.message; draw(); }
|
|
219
|
+
scheduleReconnect();
|
|
220
|
+
}
|
|
221
|
+
}, RECONNECT_MS);
|
|
222
|
+
}
|
|
223
|
+
|
|
116
224
|
if (stdinIsInteractive()) {
|
|
117
225
|
process.stdin.once("end", onInputEnd);
|
|
118
226
|
process.stdin.once("close", onInputEnd);
|
|
@@ -124,46 +232,16 @@ if (!stdinIsInteractive()) {
|
|
|
124
232
|
console.log(renderPane({ snapshot, identity, email, messages, error: "Interactive terminal controls are required in this pane." }));
|
|
125
233
|
} else {
|
|
126
234
|
try {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
if (closing) { control.destroy(); }
|
|
133
|
-
else {
|
|
134
|
-
control.on("data", (chunk) => {
|
|
135
|
-
controlBuffer += chunk.toString();
|
|
136
|
-
if (controlBuffer.length > 65_536) { failControl(new Error("Invalid relay control response")); return; }
|
|
137
|
-
let newline;
|
|
138
|
-
while ((newline = controlBuffer.indexOf("\n")) >= 0) {
|
|
139
|
-
const line = controlBuffer.slice(0, newline);
|
|
140
|
-
controlBuffer = controlBuffer.slice(newline + 1);
|
|
141
|
-
let value;
|
|
142
|
-
try { value = JSON.parse(line); } catch { failControl(new Error("Invalid relay control response")); return; }
|
|
143
|
-
const request = replies.shift();
|
|
144
|
-
if (request) { clearTimeout(request.timer); request.resolve(value); }
|
|
145
|
-
}
|
|
146
|
-
});
|
|
147
|
-
control.on("close", () => { controlClosed(); rejectReplies(new Error("Relay owner channel closed")); });
|
|
148
|
-
control.on("error", () => { controlClosed(); rejectReplies(new Error("Relay owner channel failed")); });
|
|
149
|
-
const attached = await sendUi("attach-ui");
|
|
150
|
-
if (attached.error === "ui-owned") throw new Error("Another relay pane already owns this installation. Close it before reopening.");
|
|
151
|
-
ownsUi = true;
|
|
152
|
-
snapshot = attached;
|
|
153
|
-
const enabled = await sendUi("ui-enable");
|
|
154
|
-
snapshot = enabled;
|
|
155
|
-
void syncRelayTab(enabled.state === "running").catch(() => {});
|
|
156
|
-
draw();
|
|
157
|
-
await refresh();
|
|
158
|
-
timer = setInterval(refresh, 1000);
|
|
159
|
-
timer.unref();
|
|
160
|
-
}
|
|
235
|
+
errorText = "Starting the PeerBand relay…";
|
|
236
|
+
draw();
|
|
237
|
+
await attach({ start: true });
|
|
238
|
+
await refresh();
|
|
161
239
|
} catch (error) {
|
|
162
240
|
if (!closing) {
|
|
163
|
-
|
|
164
|
-
|
|
241
|
+
if (control && !control.destroyed) control.destroy();
|
|
242
|
+
showUnavailable(error.message);
|
|
165
243
|
draw();
|
|
166
|
-
|
|
244
|
+
scheduleReconnect(!/already owns/.test(error.message || ""));
|
|
167
245
|
}
|
|
168
246
|
}
|
|
169
247
|
}
|
|
@@ -173,7 +251,7 @@ function sendUi(command) {
|
|
|
173
251
|
return new Promise((resolve, reject) => {
|
|
174
252
|
if (!control || control.destroyed) { reject(new Error("Relay owner channel is closed")); return; }
|
|
175
253
|
const request = { resolve, reject, timer: undefined };
|
|
176
|
-
request.timer = setTimeout(() => failControl(new Error("Relay owner request timed out")),
|
|
254
|
+
request.timer = setTimeout(() => failControl(new Error("Relay owner request timed out")), 10_000);
|
|
177
255
|
replies.push(request);
|
|
178
256
|
control.write(JSON.stringify({ command }) + "\n");
|
|
179
257
|
});
|
package/herdr/relay-tab.mjs
CHANGED
|
@@ -122,6 +122,15 @@ async function inspectOwned(run, record) {
|
|
|
122
122
|
return pane;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
// A pane carrying our ownership marker token, i.e. one opened (and verified) by a Relay tab controller.
|
|
126
|
+
async function findMarkedPane(run) {
|
|
127
|
+
let listed;
|
|
128
|
+
try { listed = (await run(["pane", "list"])).panes; }
|
|
129
|
+
catch { return undefined; }
|
|
130
|
+
if (!Array.isArray(listed)) return undefined;
|
|
131
|
+
return listed.find((item) => typeof item?.pane_id === "string" && typeof item.tokens?.[markerName] === "string" && item.tokens[markerName]);
|
|
132
|
+
}
|
|
133
|
+
|
|
125
134
|
async function renameOwnedSinglePaneTab(run, pane, label) {
|
|
126
135
|
if (!pane?.workspace_id || !pane?.tab_id || !pane?.pane_id) return false;
|
|
127
136
|
let listed;
|
|
@@ -174,6 +183,14 @@ export function createRelayTabController({ run, statePath, pluginPaneId = "", ne
|
|
|
174
183
|
await run(["plugin", "pane", "focus", pane.pane_id]);
|
|
175
184
|
return pane.pane_id;
|
|
176
185
|
}
|
|
186
|
+
// The record is missing or stale (another config, a crash, Herdr restarted), but a Relay pane this
|
|
187
|
+
// controller marked earlier may still be open: adopt and focus it instead of opening a duplicate.
|
|
188
|
+
const existing = await findMarkedPane(run);
|
|
189
|
+
if (existing) {
|
|
190
|
+
await writeRecord(statePath, { version: 1, paneId: existing.pane_id, marker: existing.tokens[markerName] });
|
|
191
|
+
await run(["plugin", "pane", "focus", existing.pane_id]);
|
|
192
|
+
return existing.pane_id;
|
|
193
|
+
}
|
|
177
194
|
|
|
178
195
|
// A stale state file never authorizes closing or renaming its old pane. Replace it with a
|
|
179
196
|
// fresh random ownership marker only after Herdr returns a validated plugin pane.
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Stale-lock detection and reclaim, shared by the plugin (lifecycle.mjs) and the CLI (bundled).
|
|
2
|
+
// A lock is a directory created with mkdir (atomic). Its owner file records who holds it:
|
|
3
|
+
// relay-helper.lock/owner.json {"token","pid","hostname","startedAt"} (written by the supervisor)
|
|
4
|
+
// state/receipts.json.lock/owner {"owner","pid","hostname","startedAt"} (written by the connector)
|
|
5
|
+
// Locks written by PeerBand 0.1.3 and older have no pid ("legacy"). A lock is only reclaimed when its owner is
|
|
6
|
+
// provably gone: a recorded pid on this host that is not alive (or alive but clearly another program), or, for a
|
|
7
|
+
// legacy lock, nobody answering on the helper control channel (helper lock) / no matching process running (receipts).
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
11
|
+
import { createConnection } from "node:net";
|
|
12
|
+
import { hostname } from "node:os";
|
|
13
|
+
import { join, relative } from "node:path";
|
|
14
|
+
|
|
15
|
+
// A lock directory without an owner file may be one that is being created right now.
|
|
16
|
+
const CREATION_GRACE_MS = 10_000;
|
|
17
|
+
|
|
18
|
+
export const SUPERVISOR_PATTERN = /lifecycle\.mjs["']?\s+supervise\b/i;
|
|
19
|
+
export const CONNECTOR_PATTERN = /peerband(?:\.mjs|\.cmd|\.ps1)?["']?\s+connect\b/i;
|
|
20
|
+
|
|
21
|
+
/** Fields recorded in every new owner file. */
|
|
22
|
+
export function ownerIdentity() {
|
|
23
|
+
return { pid: process.pid, hostname: hostname(), startedAt: new Date().toISOString() };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** True when a process with this pid exists (EPERM means it exists but belongs to someone else). */
|
|
27
|
+
export function pidAlive(pid) {
|
|
28
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
29
|
+
try {
|
|
30
|
+
process.kill(pid, 0);
|
|
31
|
+
return true;
|
|
32
|
+
} catch (error) {
|
|
33
|
+
return Boolean(error && error.code === "EPERM");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** "listening" when something accepts connections on the channel, "absent" when nothing does, "unknown" otherwise. */
|
|
38
|
+
export function probeChannel(channel, timeout = 1500) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
let settled = false;
|
|
41
|
+
const socket = createConnection(channel);
|
|
42
|
+
const finish = (value) => {
|
|
43
|
+
if (settled) return;
|
|
44
|
+
settled = true;
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
socket.destroy();
|
|
47
|
+
resolve(value);
|
|
48
|
+
};
|
|
49
|
+
const timer = setTimeout(() => finish("unknown"), timeout);
|
|
50
|
+
socket.once("connect", () => finish("listening"));
|
|
51
|
+
socket.once("error", (error) => finish(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function run(file, args, timeout) {
|
|
56
|
+
return new Promise((resolve) => {
|
|
57
|
+
execFile(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve(error ? null : String(stdout)));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Best-effort list of running processes with their command lines, or null when it cannot be read. */
|
|
62
|
+
export async function listProcesses(platform = process.platform) {
|
|
63
|
+
if (platform === "linux") {
|
|
64
|
+
let entries;
|
|
65
|
+
try { entries = await readdir("/proc"); } catch { return null; }
|
|
66
|
+
const result = [];
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
if (!/^\d+$/.test(entry)) continue;
|
|
69
|
+
try {
|
|
70
|
+
const command = (await readFile(`/proc/${entry}/cmdline`, "utf8")).split("\0").join(" ").trim();
|
|
71
|
+
if (command) result.push({ pid: Number(entry), command });
|
|
72
|
+
} catch { /* exited meanwhile */ }
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
if (platform === "win32") {
|
|
77
|
+
const script = "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }";
|
|
78
|
+
const text = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 15_000);
|
|
79
|
+
if (text === null) return null;
|
|
80
|
+
return parseProcessLines(text, "\t");
|
|
81
|
+
}
|
|
82
|
+
const text = await run("ps", ["-axo", "pid=,command="], 10_000);
|
|
83
|
+
return text === null ? null : parseProcessLines(text, " ");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseProcessLines(text, separator) {
|
|
87
|
+
const result = [];
|
|
88
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
89
|
+
const line = raw.trim();
|
|
90
|
+
if (!line) continue;
|
|
91
|
+
const at = line.indexOf(separator);
|
|
92
|
+
const pid = Number(at < 0 ? line : line.slice(0, at));
|
|
93
|
+
if (Number.isSafeInteger(pid) && pid > 0) result.push({ pid, command: at < 0 ? "" : line.slice(at + 1).trim() });
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function readOwner(ownerFile) {
|
|
99
|
+
let text;
|
|
100
|
+
try { text = await readFile(ownerFile, "utf8"); } catch { return { text: null, owner: null }; }
|
|
101
|
+
try {
|
|
102
|
+
const value = JSON.parse(text);
|
|
103
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return { text, owner: value };
|
|
104
|
+
} catch { /* a legacy receipt lock holds a bare uuid */ }
|
|
105
|
+
return { text, owner: {} };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Decides whether a lock is held by a live owner.
|
|
110
|
+
* Returns { state: "absent" | "live" | "stale", reason, ownerText, pid? }.
|
|
111
|
+
* `channel`: the helper control channel that a live owner answers on (optional).
|
|
112
|
+
* `processPattern`: command-line pattern of a process that could own the lock (optional).
|
|
113
|
+
* `listProcesses`, `probe`, `alive`, `host`: test seams.
|
|
114
|
+
*/
|
|
115
|
+
export async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list = listProcesses, probe = probeChannel, alive = pidAlive, host = hostname(), now = Date.now() }) {
|
|
116
|
+
let info;
|
|
117
|
+
try { info = await stat(lockDir); } catch (error) {
|
|
118
|
+
if (error && error.code === "ENOENT") return { state: "absent", reason: "no lock", ownerText: null };
|
|
119
|
+
return { state: "live", reason: `the lock could not be read (${error && error.code})`, ownerText: null };
|
|
120
|
+
}
|
|
121
|
+
const { text, owner } = await readOwner(ownerFile);
|
|
122
|
+
const ignore = new Set([process.pid, ...excludePids]);
|
|
123
|
+
// Processes whose command line matches the owner pattern (null when unknown). `keep` is never filtered out.
|
|
124
|
+
const matching = async (keep) => {
|
|
125
|
+
if (!processPattern) return null;
|
|
126
|
+
const processes = await list();
|
|
127
|
+
if (!processes) return null;
|
|
128
|
+
return processes.filter((item) => (item.pid === keep || !ignore.has(item.pid)) && processPattern.test(item.command));
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
if (owner && Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
132
|
+
const pid = owner.pid;
|
|
133
|
+
if (typeof owner.hostname === "string" && owner.hostname && owner.hostname !== host) {
|
|
134
|
+
return { state: "live", reason: `the owner runs on another host (${owner.hostname})`, ownerText: text, pid };
|
|
135
|
+
}
|
|
136
|
+
if (!alive(pid)) return { state: "stale", reason: `owner process ${pid} is not running`, ownerText: text, pid };
|
|
137
|
+
// The pid is alive. It may have been reused by an unrelated program after the owner died.
|
|
138
|
+
if (channel && (await probe(channel)) !== "absent") return { state: "live", reason: `owner process ${pid} is running`, ownerText: text, pid };
|
|
139
|
+
const candidates = await matching(pid);
|
|
140
|
+
if (candidates && !candidates.some((item) => item.pid === pid)) {
|
|
141
|
+
return { state: "stale", reason: `process ${pid} is running but is not a PeerBand ${channel ? "helper" : "connector"}`, ownerText: text, pid };
|
|
142
|
+
}
|
|
143
|
+
return { state: "live", reason: `owner process ${pid} is running`, ownerText: text, pid };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Legacy lock (no pid), or a lock whose owner file is missing.
|
|
147
|
+
if (text === null && now - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
|
|
148
|
+
if (channel) {
|
|
149
|
+
// The channel name is derived from the config folder and a helper listens on it before it writes its owner
|
|
150
|
+
// file, for as long as it lives. Nothing listening therefore means the helper of *this* config is gone, which a
|
|
151
|
+
// process list cannot tell (it cannot see which config folder another helper serves).
|
|
152
|
+
const probed = await probe(channel);
|
|
153
|
+
if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text };
|
|
154
|
+
if (probed === "unknown") return { state: "live", reason: "the control channel could not be checked", ownerText: text };
|
|
155
|
+
return { state: "stale", reason: "no helper answers on the control channel", ownerText: text };
|
|
156
|
+
}
|
|
157
|
+
const candidates = await matching();
|
|
158
|
+
if (candidates && candidates.length > 0) {
|
|
159
|
+
return { state: "live", reason: `a matching process is running (pid ${candidates.map((item) => item.pid).join(", ")})`, ownerText: text };
|
|
160
|
+
}
|
|
161
|
+
if (!candidates) return { state: "live", reason: "running processes could not be listed", ownerText: text };
|
|
162
|
+
return { state: "stale", reason: "no matching process is running", ownerText: text };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Atomically removes a stale lock: rename it aside (only one reclaimer can win), check that the moved lock is
|
|
167
|
+
* still the one that was inspected, then delete it. If the owner changed meanwhile, it is put back.
|
|
168
|
+
*/
|
|
169
|
+
export async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
|
|
170
|
+
const quarantine = `${lockDir}.stale-${randomUUID()}`;
|
|
171
|
+
try { await rename(lockDir, quarantine); } catch (error) { return Boolean(error && error.code === "ENOENT"); }
|
|
172
|
+
const moved = await readOwner(join(quarantine, relative(lockDir, ownerFile)));
|
|
173
|
+
if (expectedOwnerText !== undefined && moved.text !== expectedOwnerText) {
|
|
174
|
+
await rename(quarantine, lockDir).catch(() => {});
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
await rm(quarantine, { recursive: true, force: true }).catch(() => {});
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** inspectLock + reclaimLock. Returns { reclaimed, verdict }. `log` receives one line when a lock is reclaimed. */
|
|
182
|
+
export async function reclaimIfStale(options) {
|
|
183
|
+
const verdict = await inspectLock(options);
|
|
184
|
+
if (verdict.state !== "stale") return { reclaimed: false, verdict };
|
|
185
|
+
const reclaimed = await reclaimLock({ lockDir: options.lockDir, ownerFile: options.ownerFile, expectedOwnerText: verdict.ownerText ?? undefined });
|
|
186
|
+
if (reclaimed && options.log) options.log(`Reclaimed a stale lock ${options.lockDir} (${verdict.reason}).`);
|
|
187
|
+
return { reclaimed, verdict };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Marks a saved relay snapshot as stopped (keeps the activity list), so nothing reads it as still running. */
|
|
191
|
+
export async function resetRelayState(path) {
|
|
192
|
+
let previous = {};
|
|
193
|
+
try { previous = JSON.parse(await readFile(path, "utf8")) || {}; } catch (error) {
|
|
194
|
+
if (error && error.code === "ENOENT") return false;
|
|
195
|
+
}
|
|
196
|
+
const activity = Array.isArray(previous.activity) ? previous.activity : [];
|
|
197
|
+
if (previous.state === "stopping" && previous.connectionState === "disabled") return false;
|
|
198
|
+
await writeFile(path, `${JSON.stringify({ state: "stopping", connectionState: "disabled", activity })}\n`, { mode: 0o600 });
|
|
199
|
+
return true;
|
|
200
|
+
}
|
package/herdr-plugin.toml
CHANGED