@awebai/oats 0.49.0 → 0.51.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/lib/claim.mjs ADDED
@@ -0,0 +1,126 @@
1
+ /** The claim: one file that says which process is doing a thing that must happen once at a time.
2
+ * One protocol, used by `oats worktree add|remove` (the purpose's claim, lib/worktree.mjs
3
+ * `withClaim`) and by `oats retire` (the home's claim, lib/core.mjs `retireInstance`).
4
+ *
5
+ * Unlike lib/dir-lock.mjs, a claim left by a process that died is taken over, so a killed command
6
+ * can always be run again: the owner is named by pid AND start time (processLiveness), never by a
7
+ * pid alone, and a holder whose start cannot be read is never taken for gone.
8
+ *
9
+ * - Taking it: the owner's facts `{ pid, processStart, nonce, at }` are written to a private file
10
+ * and hard-linked to `path`, which fails if `path` exists. So a claim is never seen without its
11
+ * owner, and the nonce makes each holding distinct, even for the same process.
12
+ * - Its owner is alive: waited for up to `waitMs`, then refused (`busy`).
13
+ * - Its owner is gone (processLiveness "gone"; "unknown" is refused, never taken over): the claim
14
+ * is removed under a second claim, `<path>.reclaim-<owner nonce>`, taken by this same protocol.
15
+ * Its holder re-reads `path` and removes it only if it still names that owner. Nothing else
16
+ * removes another's claim: its owner never releases it, and a new acquirer cannot write over an
17
+ * existing file. Two takeovers of one dead owner are therefore serialized, and neither removes
18
+ * a claim made after it read. A takeover cut short leaves its own claim behind, which the next
19
+ * takeover takes over in turn, up to CLAIM_MAX_DEPTH nested levels.
20
+ * - A step the holder recorded in its claim (recordInClaim) is ended by a takeover first
21
+ * (`endHolderStep`), which refuses, keeping the claim, if the step cannot be ended.
22
+ * - Released by unlinking `path`, only while it still names this holding.
23
+ * - An unreadable claim file is never removed: the command is refused, naming the file.
24
+ *
25
+ * Everything is synchronous. What is the caller's own goes in `opts`:
26
+ * busy(holder, unknown, at) the refusal for a holder that lives (`unknown` unset) or whose
27
+ * liveness cannot be read (`unknown` is the reason); `at` is the
28
+ * claim file that names it
29
+ * ownStartUnreadable(reason, at) the refusal when this process's own start cannot be read, so
30
+ * it could not hold `at` verifiably
31
+ * unreadableClaim(at) the refusal for a claim file that does not parse
32
+ * endHolderStep(holder, at) optional: end the step a dead holder recorded
33
+ * → { owed?, remedy?, warning?, details? }
34
+ * waitMs how long a live holder is waited for (default CLAIM_WAIT_MS)
35
+ * warnings optional array a takeover's warnings are pushed to */
36
+ import { linkSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
37
+ import { randomBytes } from "node:crypto";
38
+ import { processLiveness, processStart } from "./worktree-hooks.mjs";
39
+
40
+ export const CLAIM_WAIT_MS = 3000;
41
+ const CLAIM_MAX_DEPTH = 8;
42
+ const NONCE_RE = /^[0-9a-f]{32}$/;
43
+ const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
44
+
45
+ /** The claim at `path` → its record, `{ unreadable: true }` when it does not parse, null when there is none. */
46
+ export function readClaim(path) {
47
+ try { const o = JSON.parse(readFileSync(path, "utf8")); return o && typeof o === "object" ? o : { unreadable: true }; }
48
+ catch (e) { return e.code === "ENOENT" ? null : { unreadable: true }; }
49
+ }
50
+
51
+ /** Take the claim `path` → this holding (`{ pid, processStart, nonce, at }`), to pass to
52
+ * releaseClaim. Throws the caller's refusal when it cannot be taken. The directory exists. */
53
+ export function acquireClaim(path, opts, depth = 0) {
54
+ const { busy, waitMs = CLAIM_WAIT_MS } = opts;
55
+ const own = processStart(process.pid);
56
+ if (own.state !== "alive") throw opts.ownStartUnreadable(own.reason ?? `pid ${process.pid} reads as ${own.state}`, path);
57
+ const me = { pid: process.pid, processStart: own.token, nonce: randomBytes(16).toString("hex"), at: new Date().toISOString() };
58
+ const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
59
+ writeFileSync(tmp, JSON.stringify(me) + "\n", { mode: 0o600 });
60
+ try {
61
+ const deadline = Date.now() + waitMs;
62
+ for (;;) {
63
+ try { linkSync(tmp, path); return me; }
64
+ catch (e) { if (e.code !== "EEXIST") throw e; }
65
+ const holder = readClaim(path);
66
+ if (holder === null) continue; // released in between
67
+ if (holder.unreadable) throw opts.unreadableClaim(path);
68
+ const live = processLiveness(holder);
69
+ // Unreadable is never taken for gone: the claim is kept, and the refusal names the way out.
70
+ if (live.state === "unknown") throw busy(holder, live.reason, path);
71
+ if (live.state === "gone") {
72
+ if (depth >= CLAIM_MAX_DEPTH || typeof holder.nonce !== "string" || !NONCE_RE.test(holder.nonce)) throw busy(holder, null, path);
73
+ takeOver(path, holder, opts, depth);
74
+ continue;
75
+ }
76
+ if (Date.now() >= deadline) throw busy(holder, null, path);
77
+ pauseSync(50);
78
+ }
79
+ } finally {
80
+ try { unlinkSync(tmp); } catch { /* gone */ }
81
+ }
82
+ }
83
+
84
+ /** Remove `path`, held by the dead `holder`, under the claim that serializes takeovers of it. */
85
+ function takeOver(path, holder, opts, depth) {
86
+ const reclaim = `${path}.reclaim-${holder.nonce}`;
87
+ const me = acquireClaim(reclaim, opts, depth + 1);
88
+ try {
89
+ const now = readClaim(path);
90
+ if (now?.nonce === holder.nonce) {
91
+ const ended = opts.endHolderStep?.(now, path) ?? {};
92
+ if (ended.owed) {
93
+ const e = opts.busy(now);
94
+ throw Object.assign(e, { message: `${ended.owed}; ${path} is kept and nothing was done — ${ended.remedy}`, details: { ...e.details, ...ended.details } });
95
+ }
96
+ if (ended.warning) opts.warnings?.push(ended.warning);
97
+ unlinkSync(path);
98
+ }
99
+ } finally {
100
+ releaseClaim(reclaim, me);
101
+ }
102
+ }
103
+
104
+ /** Release the claim `path`, only while it still names the holding `me`. */
105
+ export function releaseClaim(path, me) {
106
+ if (readClaim(path)?.nonce === me.nonce) { try { unlinkSync(path); } catch { /* gone */ } }
107
+ }
108
+
109
+ /** Record (or, with null, clear) a step of the holding `me` in its claim `path`, for a takeover to
110
+ * end (`endHolderStep`). Only the live holder writes its claim. */
111
+ export function recordInClaim(path, me, step) {
112
+ const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
113
+ writeFileSync(tmp, JSON.stringify({ ...me, ...(step ?? {}) }) + "\n", { mode: 0o600 });
114
+ renameSync(tmp, path);
115
+ }
116
+
117
+ /** Remove the claim `path` when its holder is verifiably gone, through the takeover above, and
118
+ * take nothing: for a claim nobody will come back for. → whether it was removed. A claim whose
119
+ * holder is alive, unknown or unreadable is left as it is. Throws what a takeover throws. */
120
+ export function removeGoneClaim(path, opts) {
121
+ const holder = readClaim(path);
122
+ if (!holder || holder.unreadable || typeof holder.nonce !== "string" || !NONCE_RE.test(holder.nonce)) return false;
123
+ if (processLiveness(holder).state !== "gone") return false;
124
+ takeOver(path, holder, opts, 0);
125
+ return readClaim(path)?.nonce !== holder.nonce;
126
+ }