pi-better-server 0.2.4 → 0.3.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/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { isTerminalStatus } from "./types.mjs";
|
|
6
|
+
let seq = 0;
|
|
7
|
+
const metaCache = new Map();
|
|
8
|
+
// Owned snapshots are process-resident. A cheap directory signature catches
|
|
9
|
+
// cross-process index changes before any cached IDs are reused.
|
|
10
|
+
const indexIdsCache = new Map();
|
|
11
|
+
const initializedIndexes = new Set();
|
|
12
|
+
const metaChangedListeners = new Set();
|
|
13
|
+
const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
|
|
14
|
+
export function getRegistryIoMetrics() {
|
|
15
|
+
return { ...registryIo };
|
|
16
|
+
}
|
|
17
|
+
export function resetRegistryIoMetrics() {
|
|
18
|
+
registryIo.fullDirectoryReads = 0;
|
|
19
|
+
registryIo.indexDirectoryReads = 0;
|
|
20
|
+
registryIo.metadataFileReads = 0;
|
|
21
|
+
registryIo.indexRevisionChecks = 0;
|
|
22
|
+
}
|
|
23
|
+
export function baseDir() {
|
|
24
|
+
const vitestPoolId = process.env.VITEST_POOL_ID;
|
|
25
|
+
const directory = vitestPoolId && /^\d+$/.test(vitestPoolId)
|
|
26
|
+
? `pi-better-background-tasks-vitest-${vitestPoolId}`
|
|
27
|
+
: "pi-better-background-tasks";
|
|
28
|
+
return join(tmpdir(), directory);
|
|
29
|
+
}
|
|
30
|
+
export function tasksDir() {
|
|
31
|
+
return join(baseDir(), "tasks");
|
|
32
|
+
}
|
|
33
|
+
export function taskDir(id) {
|
|
34
|
+
return join(tasksDir(), id);
|
|
35
|
+
}
|
|
36
|
+
export function metaPathFor(id) {
|
|
37
|
+
return join(taskDir(id), "meta.json");
|
|
38
|
+
}
|
|
39
|
+
export function logPathFor(id) {
|
|
40
|
+
return join(taskDir(id), "output.log");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Where a task keeps the generated sandbox profile it launched under.
|
|
44
|
+
*
|
|
45
|
+
* It lives beside the task's own log and metadata so it survives exactly as long
|
|
46
|
+
* as the task does: a watch resumed in a later Pi session re-reads the profile it
|
|
47
|
+
* started with instead of a profile some other session has since rewritten.
|
|
48
|
+
*/
|
|
49
|
+
export function sandboxProfilePathFor(id) {
|
|
50
|
+
return join(taskDir(id), "sandbox.sb");
|
|
51
|
+
}
|
|
52
|
+
export function nextTaskId() {
|
|
53
|
+
seq += 1;
|
|
54
|
+
return `bg_${process.pid.toString(36)}_${Date.now().toString(36)}_${seq}`;
|
|
55
|
+
}
|
|
56
|
+
export function ensureTaskDir(id) {
|
|
57
|
+
mkdirSync(taskDir(id), { recursive: true });
|
|
58
|
+
}
|
|
59
|
+
export function writeMeta(meta) {
|
|
60
|
+
ensureTaskDir(meta.id);
|
|
61
|
+
writeFileSync(metaPathFor(meta.id), JSON.stringify(meta, null, 2));
|
|
62
|
+
metaCache.set(meta.id, meta);
|
|
63
|
+
indexMeta(meta);
|
|
64
|
+
for (const listener of metaChangedListeners) {
|
|
65
|
+
try {
|
|
66
|
+
listener();
|
|
67
|
+
}
|
|
68
|
+
catch { /* best effort */ }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export function onMetaChanged(listener) {
|
|
72
|
+
metaChangedListeners.add(listener);
|
|
73
|
+
return () => metaChangedListeners.delete(listener);
|
|
74
|
+
}
|
|
75
|
+
export function readMeta(id) {
|
|
76
|
+
return inspectMeta(id).meta;
|
|
77
|
+
}
|
|
78
|
+
function errorText(error) {
|
|
79
|
+
return error instanceof Error ? error.message : String(error);
|
|
80
|
+
}
|
|
81
|
+
/** Parsed JSON that lacks the identifying fields is corrupt, not a task. */
|
|
82
|
+
function metaShapeProblem(meta, id) {
|
|
83
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta))
|
|
84
|
+
return "not an object";
|
|
85
|
+
const value = meta;
|
|
86
|
+
if (value.id !== id)
|
|
87
|
+
return `id ${JSON.stringify(value.id ?? null)} does not match ${JSON.stringify(id)}`;
|
|
88
|
+
if (typeof value.status !== "string" || !value.status)
|
|
89
|
+
return "missing status";
|
|
90
|
+
if (typeof value.logPath !== "string" || !value.logPath)
|
|
91
|
+
return "missing logPath";
|
|
92
|
+
if (typeof value.startedAt !== "number" || !Number.isFinite(value.startedAt))
|
|
93
|
+
return "missing startedAt";
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Distinguish missing, unreadable, and healthy metadata. Callers must not treat
|
|
98
|
+
* an unreadable file as proof that a task does not exist.
|
|
99
|
+
*/
|
|
100
|
+
export function inspectMeta(id) {
|
|
101
|
+
const path = metaPathFor(id);
|
|
102
|
+
try {
|
|
103
|
+
registryIo.metadataFileReads += 1;
|
|
104
|
+
const raw = readFileSync(path, "utf8");
|
|
105
|
+
try {
|
|
106
|
+
const meta = JSON.parse(raw);
|
|
107
|
+
const invalid = metaShapeProblem(meta, id);
|
|
108
|
+
if (invalid) {
|
|
109
|
+
metaCache.delete(id);
|
|
110
|
+
return { id, found: true, readable: false, error: `invalid metadata: ${invalid}` };
|
|
111
|
+
}
|
|
112
|
+
metaCache.set(id, meta);
|
|
113
|
+
return { id, meta, found: true, readable: true };
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
metaCache.delete(id);
|
|
117
|
+
return { id, found: true, readable: false, error: `invalid JSON: ${errorText(error)}` };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
metaCache.delete(id);
|
|
122
|
+
const code = error.code;
|
|
123
|
+
if (code === "ENOENT") {
|
|
124
|
+
try {
|
|
125
|
+
statSync(taskDir(id));
|
|
126
|
+
return { id, found: true, readable: false, error: "metadata file is missing" };
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return { id, found: false, readable: false };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { id, found: true, readable: false, error: errorText(error) };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** List every task directory, including unreadable metadata. */
|
|
136
|
+
export function listTaskRecords() {
|
|
137
|
+
let ids;
|
|
138
|
+
try {
|
|
139
|
+
registryIo.fullDirectoryReads += 1;
|
|
140
|
+
ids = readdirSync(tasksDir());
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
const code = error.code;
|
|
144
|
+
if (code === "ENOENT")
|
|
145
|
+
return { records: [] };
|
|
146
|
+
return { records: [], indexError: errorText(error) };
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
records: ids.map((id) => inspectMeta(id)).sort((a, b) => {
|
|
150
|
+
const aTime = a.meta?.startedAt ?? 0;
|
|
151
|
+
const bTime = b.meta?.startedAt ?? 0;
|
|
152
|
+
return bTime - aTime;
|
|
153
|
+
}),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
export function removeMeta(meta) {
|
|
157
|
+
try {
|
|
158
|
+
rmSync(taskDir(meta.id), { recursive: true, force: true });
|
|
159
|
+
metaCache.delete(meta.id);
|
|
160
|
+
removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
|
|
161
|
+
removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
|
|
162
|
+
for (const listener of metaChangedListeners) {
|
|
163
|
+
try {
|
|
164
|
+
listener();
|
|
165
|
+
}
|
|
166
|
+
catch { /* best effort */ }
|
|
167
|
+
}
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export function listMetas() {
|
|
175
|
+
let ids;
|
|
176
|
+
try {
|
|
177
|
+
registryIo.fullDirectoryReads += 1;
|
|
178
|
+
ids = readdirSync(tasksDir());
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return [];
|
|
182
|
+
}
|
|
183
|
+
const liveIds = new Set(ids);
|
|
184
|
+
for (const cachedId of metaCache.keys()) {
|
|
185
|
+
if (!liveIds.has(cachedId))
|
|
186
|
+
metaCache.delete(cachedId);
|
|
187
|
+
}
|
|
188
|
+
return ids
|
|
189
|
+
.map(readMetaForSweep)
|
|
190
|
+
.filter((meta) => meta !== undefined)
|
|
191
|
+
.sort((a, b) => b.startedAt - a.startedAt);
|
|
192
|
+
}
|
|
193
|
+
export function listMetasForOrigin(origin) {
|
|
194
|
+
const directory = originIndexDir(origin);
|
|
195
|
+
ensureOriginIndex(origin, directory);
|
|
196
|
+
return readIndexIds(directory)
|
|
197
|
+
.map(readOwnedMeta)
|
|
198
|
+
.filter((meta) => meta !== undefined && belongsToOrigin(meta, origin))
|
|
199
|
+
.sort((a, b) => b.startedAt - a.startedAt);
|
|
200
|
+
}
|
|
201
|
+
export function listActiveMetasForOrigin(origin) {
|
|
202
|
+
const directory = originActiveIndexDir(origin);
|
|
203
|
+
ensureOriginActiveIndex(origin, directory);
|
|
204
|
+
return readIndexIds(directory)
|
|
205
|
+
.map(readOwnedMeta)
|
|
206
|
+
.filter((meta) => meta !== undefined && meta.status === "running" && belongsToOrigin(meta, origin))
|
|
207
|
+
.sort((a, b) => b.startedAt - a.startedAt);
|
|
208
|
+
}
|
|
209
|
+
/** Passive shared-runtime query: no backfill, cache repair, or completed-history scan. */
|
|
210
|
+
export function observeMetasForOrigin(origin, activeOnly = true) {
|
|
211
|
+
const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
|
|
212
|
+
let ids;
|
|
213
|
+
try {
|
|
214
|
+
ids = readdirSync(directory).filter(id => id !== ".initialized");
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (error.code === "ENOENT")
|
|
218
|
+
return [];
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
return ids.map(id => {
|
|
222
|
+
const record = inspectMeta(id);
|
|
223
|
+
if (record.found && !record.meta)
|
|
224
|
+
throw new Error(`Unverified background task ${id}: ${record.error}`);
|
|
225
|
+
return record.meta;
|
|
226
|
+
}).filter((meta) => !!meta && !!meta.callbackOrigin && belongsToOrigin(meta, origin)
|
|
227
|
+
&& (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
|
|
228
|
+
}
|
|
229
|
+
function readMetaForSweep(id) {
|
|
230
|
+
const cached = metaCache.get(id);
|
|
231
|
+
if (cached && isTerminalStatus(cached.status))
|
|
232
|
+
return cached;
|
|
233
|
+
return readMeta(id);
|
|
234
|
+
}
|
|
235
|
+
function readOwnedMeta(id) {
|
|
236
|
+
return metaCache.get(id) ?? readMeta(id);
|
|
237
|
+
}
|
|
238
|
+
export function originOf(meta) {
|
|
239
|
+
return meta.callbackOrigin ?? { cwd: meta.cwd };
|
|
240
|
+
}
|
|
241
|
+
export function belongsToOrigin(meta, origin) {
|
|
242
|
+
const candidate = originOf(meta);
|
|
243
|
+
if (candidate.cwd !== origin.cwd)
|
|
244
|
+
return false;
|
|
245
|
+
if (candidate.sessionId || origin.sessionId)
|
|
246
|
+
return candidate.sessionId === origin.sessionId;
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
function originIndexDir(origin) {
|
|
250
|
+
return join(baseDir(), "by-origin", originKey(origin));
|
|
251
|
+
}
|
|
252
|
+
function originActiveIndexDir(origin) {
|
|
253
|
+
return join(baseDir(), "by-origin-active", originKey(origin));
|
|
254
|
+
}
|
|
255
|
+
function originKey(origin) {
|
|
256
|
+
return createHash("sha256")
|
|
257
|
+
.update(origin.cwd)
|
|
258
|
+
.update("\0")
|
|
259
|
+
.update(origin.sessionId ?? "")
|
|
260
|
+
.digest("hex")
|
|
261
|
+
.slice(0, 24);
|
|
262
|
+
}
|
|
263
|
+
function indexMeta(meta) {
|
|
264
|
+
try {
|
|
265
|
+
const directory = originIndexDir(originOf(meta));
|
|
266
|
+
writeIndexEntry(directory, meta.id);
|
|
267
|
+
const activeDirectory = originActiveIndexDir(originOf(meta));
|
|
268
|
+
if (meta.status === "running")
|
|
269
|
+
writeIndexEntry(activeDirectory, meta.id);
|
|
270
|
+
else
|
|
271
|
+
removeIndexEntry(activeDirectory, meta.id);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
// Indexes are accelerators; meta.json remains authoritative.
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function ensureOriginIndex(origin, directory) {
|
|
278
|
+
if (initializedIndexes.has(directory))
|
|
279
|
+
return;
|
|
280
|
+
try {
|
|
281
|
+
readFileSync(join(directory, ".initialized"));
|
|
282
|
+
initializedIndexes.add(directory);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
// Existing registries are backfilled once for each session origin.
|
|
287
|
+
}
|
|
288
|
+
indexIdsCache.delete(directory);
|
|
289
|
+
const owned = listMetas().filter((meta) => belongsToOrigin(meta, origin));
|
|
290
|
+
mkdirSync(directory, { recursive: true });
|
|
291
|
+
for (const meta of owned)
|
|
292
|
+
writeIndexEntry(directory, meta.id);
|
|
293
|
+
writeFileSync(join(directory, ".initialized"), "1");
|
|
294
|
+
initializedIndexes.add(directory);
|
|
295
|
+
}
|
|
296
|
+
function ensureOriginActiveIndex(origin, directory) {
|
|
297
|
+
if (initializedIndexes.has(directory))
|
|
298
|
+
return;
|
|
299
|
+
try {
|
|
300
|
+
readFileSync(join(directory, ".initialized"));
|
|
301
|
+
initializedIndexes.add(directory);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
// Existing registries are backfilled once for this origin's active set.
|
|
306
|
+
}
|
|
307
|
+
indexIdsCache.delete(directory);
|
|
308
|
+
const owned = listMetasForOrigin(origin).filter((meta) => meta.status === "running");
|
|
309
|
+
mkdirSync(directory, { recursive: true });
|
|
310
|
+
for (const meta of owned)
|
|
311
|
+
writeIndexEntry(directory, meta.id);
|
|
312
|
+
writeFileSync(join(directory, ".initialized"), "1");
|
|
313
|
+
initializedIndexes.add(directory);
|
|
314
|
+
}
|
|
315
|
+
function readIndexIds(directory) {
|
|
316
|
+
const signature = indexDirectorySignature(directory);
|
|
317
|
+
const cached = indexIdsCache.get(directory);
|
|
318
|
+
if (cached && cached.signature === signature)
|
|
319
|
+
return [...cached.ids];
|
|
320
|
+
try {
|
|
321
|
+
registryIo.indexDirectoryReads += 1;
|
|
322
|
+
const ids = new Set(readdirSync(directory).filter((id) => id !== ".initialized"));
|
|
323
|
+
indexIdsCache.set(directory, { ids, signature: indexDirectorySignature(directory) });
|
|
324
|
+
return [...ids];
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
indexIdsCache.delete(directory);
|
|
328
|
+
return [];
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
function writeIndexEntry(directory, id) {
|
|
332
|
+
mkdirSync(directory, { recursive: true });
|
|
333
|
+
const cached = indexIdsCache.get(directory);
|
|
334
|
+
const cacheWasCurrent = cached ? cached.signature === indexDirectorySignature(directory) : false;
|
|
335
|
+
try {
|
|
336
|
+
writeFileSync(join(directory, id), "", { flag: "wx" });
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
if (error.code !== "EEXIST")
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
if (cached && cacheWasCurrent) {
|
|
343
|
+
cached.ids.add(id);
|
|
344
|
+
cached.signature = indexDirectorySignature(directory);
|
|
345
|
+
}
|
|
346
|
+
else if (cached) {
|
|
347
|
+
indexIdsCache.delete(directory);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function removeIndexEntry(directory, id) {
|
|
351
|
+
const cached = indexIdsCache.get(directory);
|
|
352
|
+
const cacheWasCurrent = cached ? cached.signature === indexDirectorySignature(directory) : false;
|
|
353
|
+
try {
|
|
354
|
+
unlinkSync(join(directory, id));
|
|
355
|
+
}
|
|
356
|
+
catch { /* stale index entries are harmless */ }
|
|
357
|
+
if (cached && cacheWasCurrent) {
|
|
358
|
+
cached.ids.delete(id);
|
|
359
|
+
cached.signature = indexDirectorySignature(directory);
|
|
360
|
+
}
|
|
361
|
+
else if (cached) {
|
|
362
|
+
indexIdsCache.delete(directory);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function indexDirectorySignature(directory) {
|
|
366
|
+
registryIo.indexRevisionChecks += 1;
|
|
367
|
+
try {
|
|
368
|
+
const stat = statSync(directory);
|
|
369
|
+
return `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}`;
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
return "missing";
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { supervisorPaths, readLaunchRecord, readTerminalRecord, readLostRecord, readClaimRecord, readCommandRecord, readStopRequest, readCleanupRecord } from "./supervisor/store.mjs";
|
|
2
|
+
function launchSummary(record) {
|
|
3
|
+
return {
|
|
4
|
+
taskId: record.taskId,
|
|
5
|
+
token: record.token,
|
|
6
|
+
kind: record.kind,
|
|
7
|
+
...(record.name === undefined ? {} : { name: record.name }),
|
|
8
|
+
...(record.operationId === undefined ? {} : { operationId: record.operationId }),
|
|
9
|
+
createdAt: record.createdAt,
|
|
10
|
+
argv: record.command.argv,
|
|
11
|
+
cwd: record.command.cwd,
|
|
12
|
+
...(record.commandTimeoutMs === undefined ? {} : { commandTimeoutSeconds: record.commandTimeoutMs / 1000 }),
|
|
13
|
+
...(record.taskTimeoutMs === undefined ? {} : { timeoutSeconds: record.taskTimeoutMs / 1000 }),
|
|
14
|
+
...(record.intervalMs === undefined ? {} : { intervalSeconds: record.intervalMs / 1000 }),
|
|
15
|
+
...(record.successWhen === undefined ? {} : { successWhen: record.successWhen }),
|
|
16
|
+
...(record.failureWhen === undefined ? {} : { failureWhen: record.failureWhen }),
|
|
17
|
+
requestHash: record.requestHash,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function snapshot(directory, taskId) {
|
|
21
|
+
const launchRead = readLaunchRecord(directory, taskId);
|
|
22
|
+
if (launchRead.missing)
|
|
23
|
+
return undefined;
|
|
24
|
+
if (!launchRead.value) {
|
|
25
|
+
throw new Error(`Unreadable supervisor launch record for ${taskId}: ${launchRead.error}`);
|
|
26
|
+
}
|
|
27
|
+
const launch = launchRead.value;
|
|
28
|
+
const paths = supervisorPaths(directory, taskId);
|
|
29
|
+
const result = readTerminalRecord(directory, taskId).value;
|
|
30
|
+
const lostRecord = readLostRecord(directory, taskId).value;
|
|
31
|
+
const claim = readClaimRecord(directory, taskId).value;
|
|
32
|
+
const command = readCommandRecord(directory, taskId).value;
|
|
33
|
+
const stop = readStopRequest(directory, taskId);
|
|
34
|
+
const cleanup = readCleanupRecord(directory, taskId);
|
|
35
|
+
const status = result
|
|
36
|
+
? result.status
|
|
37
|
+
: lostRecord
|
|
38
|
+
? "lost"
|
|
39
|
+
: claim
|
|
40
|
+
? "running"
|
|
41
|
+
: "starting";
|
|
42
|
+
return {
|
|
43
|
+
taskId,
|
|
44
|
+
token: launch.token,
|
|
45
|
+
kind: launch.kind,
|
|
46
|
+
status,
|
|
47
|
+
terminal: result !== undefined || lostRecord !== undefined,
|
|
48
|
+
launch: launchSummary(launch),
|
|
49
|
+
// Liveness is deliberately not asserted here: a snapshot never spawns `ps`.
|
|
50
|
+
...(claim === undefined
|
|
51
|
+
? {}
|
|
52
|
+
: { claim: { pid: claim.pid, pidStartTime: claim.pidStartTime, claimedAt: claim.claimedAt, alive: false } }),
|
|
53
|
+
...(command === undefined
|
|
54
|
+
? {}
|
|
55
|
+
: {
|
|
56
|
+
command: {
|
|
57
|
+
pid: command.pid,
|
|
58
|
+
pgid: command.pgid,
|
|
59
|
+
pidStartTime: command.pidStartTime,
|
|
60
|
+
startedAt: command.startedAt,
|
|
61
|
+
attempt: command.attempt ?? 1,
|
|
62
|
+
alive: false,
|
|
63
|
+
},
|
|
64
|
+
}),
|
|
65
|
+
...(result === undefined ? {} : { result }),
|
|
66
|
+
...(lostRecord === undefined ? {} : { lost: lostRecord }),
|
|
67
|
+
...(cleanup === undefined ? {} : { cleanup }),
|
|
68
|
+
...(stop === undefined ? {} : { stopRequestedAt: stop.requestedAt }),
|
|
69
|
+
taskDir: paths.dir,
|
|
70
|
+
logs: { stdout: paths.stdout, stderr: paths.stderr, events: paths.events },
|
|
71
|
+
observedAt: Date.now(),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process identity rules for the local supervisor.
|
|
3
|
+
*
|
|
4
|
+
* Signalling a numeric pid is only safe when the process behind it is provably
|
|
5
|
+
* the one this task recorded. A live pid is *not* proof: pids are recycled, and
|
|
6
|
+
* "still alive" would let a stop kill an unrelated process. Two kinds of proof
|
|
7
|
+
* exist here:
|
|
8
|
+
*
|
|
9
|
+
* - **Verified identity**: the recorded start token matches what the OS reports
|
|
10
|
+
* for that pid right now. Required before the caller signals anything.
|
|
11
|
+
* - **Owned handle**: the runner still holds the `ChildProcess` object it
|
|
12
|
+
* spawned and the child has not exited. The runner may signal that child
|
|
13
|
+
* directly without a token, because the handle *is* the identity.
|
|
14
|
+
*
|
|
15
|
+
* When no start token is available (for example a platform or sandbox where
|
|
16
|
+
* `ps` cannot run), identity is `unknown`. Callers must refuse to signal, not
|
|
17
|
+
* guess.
|
|
18
|
+
*/
|
|
19
|
+
import { processExists } from "../process.mjs";
|
|
20
|
+
import { readProcessStartToken } from "../process-identity.mjs";
|
|
21
|
+
export function readStartToken(pid) {
|
|
22
|
+
return readProcessStartToken(pid);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Decide whether `pid` is provably the recorded process.
|
|
26
|
+
*
|
|
27
|
+
* - `dead` / `absent`: nothing to signal.
|
|
28
|
+
* - `mismatched`: the pid now belongs to a different process; never signal.
|
|
29
|
+
* - `unknown`: alive but unprovable (no recorded or readable start token).
|
|
30
|
+
* - `verified`: safe for the caller to signal.
|
|
31
|
+
*/
|
|
32
|
+
export function verifyProcessIdentity(pid, recordedStartToken, reader = readStartToken) {
|
|
33
|
+
if (pid === undefined || !Number.isInteger(pid) || pid <= 0)
|
|
34
|
+
return "absent";
|
|
35
|
+
if (!processExists(pid))
|
|
36
|
+
return "dead";
|
|
37
|
+
if (!recordedStartToken)
|
|
38
|
+
return "unknown";
|
|
39
|
+
const current = reader(pid);
|
|
40
|
+
if (!current)
|
|
41
|
+
return "unknown";
|
|
42
|
+
return current === recordedStartToken ? "verified" : "mismatched";
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Liveness with the same reader the caller uses for signalling.
|
|
46
|
+
*
|
|
47
|
+
* `processIdentityAlive` in production code always reads the OS token directly.
|
|
48
|
+
* A supervisor instance may be given a different reader (a portability or test
|
|
49
|
+
* seam), and it must not decide "alive" with one identity source and "verified"
|
|
50
|
+
* with another: on a platform where the OS token is readable, a fixture token
|
|
51
|
+
* would otherwise make `inspect` call a live command dead and skip cleanup.
|
|
52
|
+
*
|
|
53
|
+
* With the default reader this is exactly `processIdentityAlive`.
|
|
54
|
+
*/
|
|
55
|
+
export function identityAlive(pid, recordedStartToken, recordedAt, reader = readStartToken) {
|
|
56
|
+
if (pid === undefined || !Number.isInteger(pid) || pid <= 0)
|
|
57
|
+
return false;
|
|
58
|
+
if (!processExists(pid))
|
|
59
|
+
return false;
|
|
60
|
+
const current = reader(pid);
|
|
61
|
+
if (recordedStartToken !== undefined && current !== undefined)
|
|
62
|
+
return recordedStartToken === current;
|
|
63
|
+
if (recordedStartToken === undefined && current !== undefined && recordedAt !== undefined) {
|
|
64
|
+
const startedAt = Date.parse(current);
|
|
65
|
+
if (Number.isFinite(startedAt) && startedAt > recordedAt + 2_000)
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
/** True when the caller may send signals for this verdict. */
|
|
71
|
+
export function identityAllowsSignals(verdict) {
|
|
72
|
+
return verdict === "verified";
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Whether the process group still has any member.
|
|
76
|
+
*
|
|
77
|
+
* POSIX keeps a group id reserved while the group is non-empty, which is what
|
|
78
|
+
* makes a group-directed SIGKILL after the leader exited addressable at all.
|
|
79
|
+
* Windows has no process groups in libuv; there the tree is removed with
|
|
80
|
+
* `taskkill /T /F` and this reports false.
|
|
81
|
+
*/
|
|
82
|
+
export function processGroupAlive(pgid) {
|
|
83
|
+
if (pgid === undefined || pgid <= 0 || process.platform === "win32")
|
|
84
|
+
return false;
|
|
85
|
+
try {
|
|
86
|
+
process.kill(-pgid, 0);
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
return error.code !== "ESRCH";
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the caller launches the detached runner executable.
|
|
3
|
+
*
|
|
4
|
+
* The entrypoint is the emitted JavaScript closure under `generated/`, not the
|
|
5
|
+
* TypeScript source. Node refuses to strip types for a file under `node_modules`
|
|
6
|
+
* (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), so an installed package must
|
|
7
|
+
* ship plain ESM. `emit-runner.mjs` produces that closure and a drift test keeps
|
|
8
|
+
* it in step with the sources.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
export function supervisorRunnerEntry(runnerPath) {
|
|
13
|
+
if (runnerPath !== undefined)
|
|
14
|
+
return runnerPath;
|
|
15
|
+
const entry = fileURLToPath(new URL("./generated/runner.mjs", import.meta.url));
|
|
16
|
+
if (!existsSync(entry)) {
|
|
17
|
+
throw new Error(`The emitted supervisor runner is missing at ${entry}. `
|
|
18
|
+
+ "Run `node src/supervisor/emit-runner.mjs` in packages/pi-better-background-tasks and ship src/supervisor/generated/.");
|
|
19
|
+
}
|
|
20
|
+
return entry;
|
|
21
|
+
}
|
|
22
|
+
export function supervisorRunnerInvocation(directory, taskId, options = {}) {
|
|
23
|
+
const entry = supervisorRunnerEntry(options.runnerPath);
|
|
24
|
+
return {
|
|
25
|
+
execPath: options.nodePath ?? process.execPath,
|
|
26
|
+
args: [entry, directory, taskId],
|
|
27
|
+
entry,
|
|
28
|
+
};
|
|
29
|
+
}
|