@uuaid/pillar 2.6.1 → 2.7.1
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 +325 -7
- package/bin/carrier.mjs +21 -0
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +282 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +512 -257
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +313 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +320 -91
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +736 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +205 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +612 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +304 -0
- package/src/vnext/jsonl-mailbox.mjs +1132 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +104 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +333 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,736 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* notify-store.mjs — file custody for <home>/notify (RedTeam notify C+N1, Q4).
|
|
3
|
+
*
|
|
4
|
+
* Every notify file goes through this module:
|
|
5
|
+
* - notify/ is 0700, every file in it 0600 (existing artifacts are tightened).
|
|
6
|
+
* - Each path is fixed and home-relative. A symlink, a hard link (nlink > 1),
|
|
7
|
+
* a non-regular file, or a file owned by another uid is refused, never
|
|
8
|
+
* followed or replaced. Reads use O_NOFOLLOW and re-check the open fd.
|
|
9
|
+
* - Writes go to an exclusive private temp file (O_EXCL, 0600), are flushed
|
|
10
|
+
* (fsync), then renamed over the target, under one writer lock.
|
|
11
|
+
* - One writer lock (notify/writer.lock) serialises every state change from
|
|
12
|
+
* every process: readers that emit eligibility events, the resident
|
|
13
|
+
* notifier, and the fallback. One wake lock (notify/wake.lock) admits one
|
|
14
|
+
* wake path (resident `pillar recv --notify` or fallback `pillar notify`).
|
|
15
|
+
* - state.json is the one durable boundary: events, the notify cursor,
|
|
16
|
+
* claims, the wake budget and the last run are committed by one rename.
|
|
17
|
+
* - notifications.jsonl is bounded by lines, bytes and age, and rotates
|
|
18
|
+
* (notifications.1.jsonl, notifications.2.jsonl) under the writer lock.
|
|
19
|
+
* - A legacy log holding message text (the pre-2.7.0 proposal wrote
|
|
20
|
+
* payload.text) is made 0600 and refused: the owner moves it out.
|
|
21
|
+
*/
|
|
22
|
+
import {
|
|
23
|
+
closeSync, constants as C, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync,
|
|
24
|
+
openSync, readdirSync, readFileSync, readSync, renameSync, chmodSync, unlinkSync, writeSync,
|
|
25
|
+
} from "node:fs";
|
|
26
|
+
import { hostname } from "node:os";
|
|
27
|
+
import { execFileSync } from "node:child_process";
|
|
28
|
+
import { dirname, join } from "node:path";
|
|
29
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
30
|
+
|
|
31
|
+
export const NOTIFY_DIR = "notify";
|
|
32
|
+
export const STATE_FILE = "state.json";
|
|
33
|
+
export const STATUS_FILE = "status.json";
|
|
34
|
+
export const LOG_FILE = "notifications.jsonl";
|
|
35
|
+
export const LOG_ROTATED = Object.freeze(["notifications.1.jsonl", "notifications.2.jsonl"]);
|
|
36
|
+
export const WRITER_LOCK = "writer.lock";
|
|
37
|
+
export const WAKE_LOCK = "wake.lock";
|
|
38
|
+
|
|
39
|
+
export const LOG_MAX_LINES = 2000;
|
|
40
|
+
export const LOG_MAX_BYTES = 256 * 1024;
|
|
41
|
+
export const LOG_MAX_AGE_MS = 30 * 24 * 3600_000;
|
|
42
|
+
export const STATE_MAX_BYTES = 4 * 1024 * 1024;
|
|
43
|
+
/**
|
|
44
|
+
* Largest state.json a read will parse to salvage it (V1 F1c). A file
|
|
45
|
+
* between STATE_MAX_BYTES and this keeps its budget and counters and loses
|
|
46
|
+
* its pending events (counted in overflow); a larger one is refused.
|
|
47
|
+
*/
|
|
48
|
+
export const STATE_READ_CEILING = 64 * 1024 * 1024;
|
|
49
|
+
export const WRITER_STALE_MS = 10_000;
|
|
50
|
+
export const WRITER_WAIT_MS = 10_000;
|
|
51
|
+
export const WAKE_STALE_MS = 90_000;
|
|
52
|
+
export const WAKE_HEARTBEAT_MS = 20_000;
|
|
53
|
+
const TMP_STALE_MS = 60_000;
|
|
54
|
+
|
|
55
|
+
export class NotifyCustodyError extends Error {
|
|
56
|
+
constructor(message, path = null) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "NotifyCustodyError";
|
|
59
|
+
this.code = "notify-custody";
|
|
60
|
+
this.path = path;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function legacyPlaintext(p) {
|
|
65
|
+
return new NotifyCustodyError(
|
|
66
|
+
`${p} holds message text written by a pre-2.7.0 notifier (it is now mode 0600). Move it out of the home or delete it, then retry: mv '${p}' <a private place>`, p);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function currentUid() {
|
|
70
|
+
return typeof process.getuid === "function" ? process.getuid() : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function pidAlive(pid) {
|
|
74
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
75
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
79
|
+
|
|
80
|
+
/** Refuse anything but a regular, single-link file owned by `uid`. */
|
|
81
|
+
export function assertSafeFile(st, path, uid = currentUid()) {
|
|
82
|
+
if (st.isSymbolicLink()) throw new NotifyCustodyError(`${path} is a symlink; notify refuses to follow it`, path);
|
|
83
|
+
if (!st.isFile()) throw new NotifyCustodyError(`${path} is not a regular file; notify refuses it`, path);
|
|
84
|
+
if (st.nlink !== 1) throw new NotifyCustodyError(`${path} has ${st.nlink} hard links; notify refuses it`, path); // @rule notify.custody-hardlink
|
|
85
|
+
if (uid !== null && st.uid !== uid) throw new NotifyCustodyError(`${path} is owned by uid ${st.uid}, not ${uid}; notify refuses it`, path); // @rule notify.custody-owner
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** <home>/notify: create 0700, or check and tighten an existing one. Never a symlink. */
|
|
89
|
+
export function ensurePrivateDir(dir, uid = currentUid()) {
|
|
90
|
+
let st;
|
|
91
|
+
try { st = lstatSync(dir); }
|
|
92
|
+
catch (e) {
|
|
93
|
+
if (e.code !== "ENOENT") throw e;
|
|
94
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
95
|
+
st = lstatSync(dir);
|
|
96
|
+
}
|
|
97
|
+
if (st.isSymbolicLink()) throw new NotifyCustodyError(`${dir} is a symlink; notify refuses to follow it`, dir); // @rule notify.custody-dir-symlink
|
|
98
|
+
if (!st.isDirectory()) throw new NotifyCustodyError(`${dir} is not a directory; notify refuses it`, dir);
|
|
99
|
+
if (uid !== null && st.uid !== uid) throw new NotifyCustodyError(`${dir} is owned by uid ${st.uid}, not ${uid}; notify refuses it`, dir);
|
|
100
|
+
if ((st.mode & 0o777) !== 0o700) chmodSync(dir, 0o700); // @rule notify.dir-0700
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Read a private file. Returns null when it does not exist. The file is
|
|
105
|
+
* checked before open and again on the open fd (no swap in between), and
|
|
106
|
+
* tightened to 0600. A file replaced or removed while we look (an atomic
|
|
107
|
+
* rename over it, a released lock) is looked at again, a few times.
|
|
108
|
+
*/
|
|
109
|
+
export function readPrivateFile(path, opts = {}) {
|
|
110
|
+
for (let i = 0; ; i++) {
|
|
111
|
+
try { return readPrivateFileOnce(path, opts); }
|
|
112
|
+
catch (e) { if (!e.race || i >= 4) throw e; }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function raceError(path) {
|
|
117
|
+
const e = new NotifyCustodyError(`${path} changed while it was opened; notify refuses it`, path);
|
|
118
|
+
e.race = true;
|
|
119
|
+
return e;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function readPrivateFileOnce(path, { uid = currentUid(), maxBytes = STATE_MAX_BYTES } = {}) {
|
|
123
|
+
let st;
|
|
124
|
+
try { st = lstatSync(path); }
|
|
125
|
+
catch (e) { if (e.code === "ENOENT") return null; throw e; }
|
|
126
|
+
if (st.isFile() && st.nlink === 0) throw raceError(path); // being replaced right now
|
|
127
|
+
assertSafeFile(st, path, uid);
|
|
128
|
+
let fd;
|
|
129
|
+
try { fd = openSync(path, C.O_RDONLY | C.O_NOFOLLOW | C.O_NONBLOCK); }
|
|
130
|
+
catch (e) {
|
|
131
|
+
if (e.code === "ENOENT") return null;
|
|
132
|
+
if (e.code === "ELOOP") throw new NotifyCustodyError(`${path} is a symlink; notify refuses to follow it`, path);
|
|
133
|
+
throw e;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const fst = fstatSync(fd);
|
|
137
|
+
if (fst.nlink === 0 || fst.ino !== st.ino || fst.dev !== st.dev) throw raceError(path); // replaced or removed after we opened it
|
|
138
|
+
assertSafeFile(fst, path, uid);
|
|
139
|
+
if ((fst.mode & 0o777) !== 0o600) fchmodSync(fd, 0o600); // @rule notify.file-0600
|
|
140
|
+
if (fst.size > maxBytes) throw new NotifyCustodyError(`${path} is ${fst.size} bytes, over the ${maxBytes}-byte limit; notify refuses it`, path);
|
|
141
|
+
const buf = Buffer.alloc(fst.size);
|
|
142
|
+
let off = 0;
|
|
143
|
+
while (off < buf.length) {
|
|
144
|
+
const n = readSync(fd, buf, off, buf.length - off, off);
|
|
145
|
+
if (n === 0) break;
|
|
146
|
+
off += n;
|
|
147
|
+
}
|
|
148
|
+
return buf.subarray(0, off).toString("utf-8");
|
|
149
|
+
} finally { closeSync(fd); }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function fsyncDir(dir) {
|
|
153
|
+
let fd = null;
|
|
154
|
+
try { fd = openSync(dir, C.O_RDONLY); fsyncSync(fd); }
|
|
155
|
+
catch (_e) { /* not every filesystem syncs a directory fd */ }
|
|
156
|
+
finally { if (fd !== null) closeSync(fd); }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Write `data` to `path`: exclusive 0600 temp file, fsync, rename. The old target must be safe. */
|
|
160
|
+
export function writePrivateAtomic(path, data, { uid = currentUid() } = {}) {
|
|
161
|
+
try { assertSafeFile(lstatSync(path), path, uid); }
|
|
162
|
+
catch (e) { if (e.code !== "ENOENT") throw e; }
|
|
163
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
164
|
+
const fd = openSync(tmp, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600); // exclusive, private, never a link
|
|
165
|
+
try {
|
|
166
|
+
const buf = Buffer.from(data, "utf-8");
|
|
167
|
+
let off = 0;
|
|
168
|
+
while (off < buf.length) off += writeSync(fd, buf, off, buf.length - off);
|
|
169
|
+
fsyncSync(fd);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
closeSync(fd);
|
|
172
|
+
try { unlinkSync(tmp); } catch (_e) {}
|
|
173
|
+
throw e;
|
|
174
|
+
}
|
|
175
|
+
closeSync(fd);
|
|
176
|
+
renameSync(tmp, path);
|
|
177
|
+
fsyncDir(dirname(path));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Remove a regular file we own, refusing anything else. Missing is fine.
|
|
182
|
+
*/
|
|
183
|
+
function removePrivateFile(path, uid) {
|
|
184
|
+
let st;
|
|
185
|
+
try { st = lstatSync(path); } catch (e) { if (e.code === "ENOENT") return; throw e; }
|
|
186
|
+
assertSafeFile(st, path, uid);
|
|
187
|
+
unlinkSync(path);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ── locks ────────────────────────────────────────────────────────────────────
|
|
191
|
+
|
|
192
|
+
function readLock(path, uid) {
|
|
193
|
+
let raw;
|
|
194
|
+
try { raw = readPrivateFile(path, { uid, maxBytes: 4096 }); }
|
|
195
|
+
catch (e) { if (e.code === "ENOENT" || e.race) return null; throw e; } // replaced mid-read: look again
|
|
196
|
+
if (raw === null) return null;
|
|
197
|
+
let info = null;
|
|
198
|
+
try { info = JSON.parse(raw); } catch (_e) { info = null; }
|
|
199
|
+
let mtimeMs = Date.now();
|
|
200
|
+
try { mtimeMs = lstatSync(path).mtimeMs; } catch (_e) {}
|
|
201
|
+
return { raw, info, mtimeMs };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const MONTHS = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
|
|
205
|
+
|
|
206
|
+
/** "Tue Dec 1 05:55:05 2026" printed under TZ=UTC -> seconds since 1970 UTC, or null. */
|
|
207
|
+
export function parseUtcLstart(text) {
|
|
208
|
+
const m = /^[A-Z][a-z]{2} ([A-Z][a-z]{2}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(String(text).trim().replace(/\s+/g, " "));
|
|
209
|
+
if (!m || MONTHS[m[1]] === undefined) return null;
|
|
210
|
+
const ms = Date.UTC(Number(m[6]), MONTHS[m[1]], Number(m[2]), Number(m[3]), Number(m[4]), Number(m[5]));
|
|
211
|
+
return Number.isFinite(ms) ? Math.floor(ms / 1000) : null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* When a process started, independent of the caller's environment (V1 F2d,
|
|
216
|
+
* Lead T1), or null when it cannot be read.
|
|
217
|
+
* Linux: "ticks:<n>", /proc/<pid>/stat field 22 (clock ticks since boot).
|
|
218
|
+
* Elsewhere: "epoch:<seconds since 1970 UTC>", from `ps -o lstart=` run with
|
|
219
|
+
* a fresh environment of only TZ=UTC, LC_ALL=C and PATH (never the caller's
|
|
220
|
+
* TZ: lstart prints local time).
|
|
221
|
+
*/
|
|
222
|
+
export function processStartTime(pid) {
|
|
223
|
+
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
224
|
+
try {
|
|
225
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
226
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); // after "pid (comm) "
|
|
227
|
+
return fields[19] ? `ticks:${fields[19]}` : null; // field 22 overall
|
|
228
|
+
} catch (_e) { /* no /proc: use ps */ }
|
|
229
|
+
let env = { ...process.env };
|
|
230
|
+
env = { TZ: "UTC", LC_ALL: "C", PATH: "/bin:/usr/bin" }; // @rule notify.start-time-utc
|
|
231
|
+
try {
|
|
232
|
+
const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf-8", env, stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).trim();
|
|
233
|
+
const epoch = parseUtcLstart(out);
|
|
234
|
+
return epoch === null ? null : `epoch:${epoch}`;
|
|
235
|
+
} catch (_e) { return null; }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let OWN_START = undefined;
|
|
239
|
+
function ownStartTime() {
|
|
240
|
+
if (OWN_START === undefined) OWN_START = processStartTime(process.pid);
|
|
241
|
+
return OWN_START;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* A stable id for this machine, hashed (the raw id stays private), or null.
|
|
246
|
+
* macOS: IOPlatformUUID. Linux: /etc/machine-id or /var/lib/dbus/machine-id.
|
|
247
|
+
* A hostname change keeps it (Lead T3).
|
|
248
|
+
*/
|
|
249
|
+
let MACHINE_ID = undefined;
|
|
250
|
+
export function machineId() {
|
|
251
|
+
if (MACHINE_ID !== undefined) return MACHINE_ID;
|
|
252
|
+
let raw = null;
|
|
253
|
+
for (const f of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
|
|
254
|
+
try { raw = readFileSync(f, "utf-8").trim() || null; } catch (_e) { /* next */ }
|
|
255
|
+
if (raw) break;
|
|
256
|
+
}
|
|
257
|
+
if (!raw) {
|
|
258
|
+
try {
|
|
259
|
+
const out = execFileSync("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], { encoding: "utf-8", env: { LC_ALL: "C", PATH: "/bin:/usr/bin:/usr/sbin" }, stdio: ["ignore", "pipe", "ignore"], timeout: 3000 });
|
|
260
|
+
raw = /"IOPlatformUUID" = "([0-9A-Fa-f-]{36})"/.exec(out)?.[1] ?? null;
|
|
261
|
+
} catch (_e) { raw = null; }
|
|
262
|
+
}
|
|
263
|
+
MACHINE_ID = raw ? `mid:${createHash("sha256").update(`pillar-notify-machine\n${raw}`).digest("hex").slice(0, 32)}` : null;
|
|
264
|
+
return MACHINE_ID;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Was this lock written on this machine? By machine id when both have one; else by hostname. */
|
|
268
|
+
export function sameMachine(info) {
|
|
269
|
+
const mine = machineId();
|
|
270
|
+
let same = info.host === hostname();
|
|
271
|
+
if (mine && typeof info.mid === "string") same = info.mid === mine; // @rule notify.lock-machine-id
|
|
272
|
+
return same;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** "epoch:" vs "epoch:", "ticks:" vs "ticks:"; anything else cannot be compared (Lead T2). */
|
|
276
|
+
function comparableStart(a, b) {
|
|
277
|
+
const kind = (v) => (typeof v === "string" ? /^(epoch|ticks):\d+$/.exec(v)?.[1] ?? null : null);
|
|
278
|
+
const k = kind(a);
|
|
279
|
+
return k !== null && k === kind(b);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Is this lock's holder gone?
|
|
284
|
+
* Wake locks (L1): a same-host holder is stale only when its pid is dead, or
|
|
285
|
+
* alive with a different start time (pid reuse). Never by wall clock: a live
|
|
286
|
+
* holder that missed heartbeats (SIGSTOP, laptop sleep) keeps the lock.
|
|
287
|
+
* Another host's holder, and the short-lived writer lock, keep the `at` rule.
|
|
288
|
+
*/
|
|
289
|
+
export function lockIsStale(held, staleMs, now = Date.now()) {
|
|
290
|
+
const i = held.info;
|
|
291
|
+
if (!i || typeof i !== "object") return now - held.mtimeMs > staleMs; // half-written
|
|
292
|
+
if (sameMachine(i)) {
|
|
293
|
+
if (!pidAlive(i.pid)) return true; // its process is gone
|
|
294
|
+
if (i.kind === "writer") return wallClockStale(i, staleMs, now); // ms-long holds; a hung writer is replaced
|
|
295
|
+
// A lock from before start times were recorded: its holder still rewrites
|
|
296
|
+
// `at`, so the wall-clock rule applies to it only (Lead T4); otherwise a
|
|
297
|
+
// reused pid would block wake-ups forever.
|
|
298
|
+
if (i.start === undefined) return wallClockStale(i, staleMs, now); // @rule notify.lock-no-start-wallclock
|
|
299
|
+
let stale = false;
|
|
300
|
+
const cur = processStartTime(i.pid);
|
|
301
|
+
if (cur !== null && comparableStart(i.start, cur)) stale = cur !== i.start; // @rule notify.lock-pid-reuse
|
|
302
|
+
return stale; // unknown or older format (e.g. "lstart:"): not stale while the pid lives (Lead T2)
|
|
303
|
+
}
|
|
304
|
+
return wallClockStale(i, staleMs, now);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function wallClockStale(i, staleMs, now) {
|
|
308
|
+
const at = Date.parse(i.at ?? "");
|
|
309
|
+
return !Number.isFinite(at) || now - at > staleMs;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Move a lock we judged stale out of the way, and only that one. */
|
|
313
|
+
function stealLock(path, judgedRaw, uid) {
|
|
314
|
+
const aside = `${path}.stale-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
315
|
+
try { renameSync(path, aside); } catch (e) { if (e.code === "ENOENT") return; throw e; }
|
|
316
|
+
let got = null;
|
|
317
|
+
try { got = readPrivateFile(aside, { uid, maxBytes: 4096 }); } catch (_e) { got = null; }
|
|
318
|
+
if (got !== judgedRaw) {
|
|
319
|
+
// A live lock replaced the stale one between our read and the rename: put it back.
|
|
320
|
+
try { linkSync(aside, path); } catch (_e) { /* a newer lock exists; the live holder's release will find it gone */ }
|
|
321
|
+
}
|
|
322
|
+
try { unlinkSync(aside); } catch (_e) {}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function tryCreateLock(path, info) {
|
|
326
|
+
let fd;
|
|
327
|
+
try { fd = openSync(path, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600); }
|
|
328
|
+
catch (e) { if (e.code === "EEXIST") return false; throw e; }
|
|
329
|
+
try { writeSync(fd, JSON.stringify(info)); } finally { closeSync(fd); }
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* One pass of a take-lock loop: create the lock, or steal it from a holder
|
|
335
|
+
* judged stale and create it again. Returns the handle, or null while a live
|
|
336
|
+
* holder keeps it.
|
|
337
|
+
*/
|
|
338
|
+
function tryTakeLock(path, { uid, staleMs, kind, token, start }) {
|
|
339
|
+
for (;;) {
|
|
340
|
+
const mid = kind === "writer" ? null : machineId();
|
|
341
|
+
const info = { pid: process.pid, host: hostname(), kind, at: new Date().toISOString(), token, ...(start ? { start } : {}), ...(mid ? { mid } : {}) };
|
|
342
|
+
if (tryCreateLock(path, info)) return { path, token, kind, uid };
|
|
343
|
+
const held = readLock(path, uid);
|
|
344
|
+
if (held && lockIsStale(held, staleMs)) { stealLock(path, held.raw, uid); continue; }
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Uniform polls (no backoff growth): a long waiter is not out-raced by newcomers. */
|
|
350
|
+
const lockPollMs = () => 4 + Math.floor(Math.random() * 7);
|
|
351
|
+
|
|
352
|
+
/** No barging: how long a process that just released `path` lets waiters go first. */
|
|
353
|
+
function bargeDelayMs(path) {
|
|
354
|
+
const since = Date.now() - (LAST_RELEASE.get(path) ?? 0);
|
|
355
|
+
return since < 6 ? 6 - since : 0;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Take a lock file. `waitMs` 0 = one try. Returns a handle, or null when a
|
|
360
|
+
* live holder keeps it (the holder's info is in `handle.heldBy` on refusal:
|
|
361
|
+
* call `lockHolder(path)` to read it).
|
|
362
|
+
*/
|
|
363
|
+
export async function acquireLock(path, { uid = currentUid(), staleMs, waitMs = 0, kind = "writer" } = {}) {
|
|
364
|
+
const deadline = Date.now() + waitMs;
|
|
365
|
+
const token = randomBytes(8).toString("hex");
|
|
366
|
+
const barge = bargeDelayMs(path);
|
|
367
|
+
if (barge > 0) await sleep(barge);
|
|
368
|
+
const start = kind === "writer" ? null : ownStartTime();
|
|
369
|
+
for (;;) {
|
|
370
|
+
const handle = tryTakeLock(path, { uid, staleMs, kind, token, start });
|
|
371
|
+
if (handle) return handle;
|
|
372
|
+
if (Date.now() >= deadline) return null;
|
|
373
|
+
await sleep(lockPollMs());
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Block this thread for `ms` (a synchronous caller has no event loop turn to give). */
|
|
378
|
+
function sleepSync(ms) {
|
|
379
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* acquireLock for a synchronous caller (the JSONL mailbox: V1 F1). The same
|
|
384
|
+
* lock file, stale rule, steal and anti-barging; the waits block the thread.
|
|
385
|
+
* Only for short "writer" holds.
|
|
386
|
+
*/
|
|
387
|
+
export function acquireLockSync(path, { uid = currentUid(), staleMs, waitMs = 0 } = {}) {
|
|
388
|
+
const deadline = Date.now() + waitMs;
|
|
389
|
+
const token = randomBytes(8).toString("hex");
|
|
390
|
+
const barge = bargeDelayMs(path);
|
|
391
|
+
if (barge > 0) sleepSync(barge);
|
|
392
|
+
for (;;) {
|
|
393
|
+
const handle = tryTakeLock(path, { uid, staleMs, kind: "writer", token, start: null });
|
|
394
|
+
if (handle) return handle;
|
|
395
|
+
if (Date.now() >= deadline) return null;
|
|
396
|
+
sleepSync(lockPollMs());
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** When this process last released each lock path (anti-barging). */
|
|
401
|
+
const LAST_RELEASE = new Map();
|
|
402
|
+
|
|
403
|
+
/** A handle that holds nothing (released as a no-op). */
|
|
404
|
+
const NO_LOCK = Object.freeze({ path: null, token: null, kind: null, uid: null });
|
|
405
|
+
|
|
406
|
+
/** Release a lock only if it is still ours (its token). */
|
|
407
|
+
export function releaseLock(handle) {
|
|
408
|
+
if (!handle?.path) return;
|
|
409
|
+
const held = readLock(handle.path, handle.uid);
|
|
410
|
+
if (held?.info?.token === handle.token) {
|
|
411
|
+
try { unlinkSync(handle.path); } catch (_e) {}
|
|
412
|
+
LAST_RELEASE.set(handle.path, Date.now());
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Is this lock file still ours (our token)? false when it was stolen,
|
|
418
|
+
* replaced, removed or cannot be read. A writer that may have stalled past
|
|
419
|
+
* the stale rule calls this just before it commits (V1 P3, 2.7.1 A2).
|
|
420
|
+
*/
|
|
421
|
+
export function stillHoldsLock(handle) {
|
|
422
|
+
if (!handle?.path) return false;
|
|
423
|
+
try { return readLock(handle.path, handle.uid)?.info?.token === handle.token; }
|
|
424
|
+
catch (_e) { return false; }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Refresh a long-held lock's `at` (cross-host staleness); false if it is no longer ours. */
|
|
428
|
+
/**
|
|
429
|
+
* Refresh a long-held lock's `at` (it still matters for another host).
|
|
430
|
+
* false = the lock is no longer ours (stolen, replaced or gone): the caller
|
|
431
|
+
* has lost it and must stop acting as its holder (Lead L2). A throw (custody,
|
|
432
|
+
* I/O) means the same to a caller that cannot prove it still holds the lock.
|
|
433
|
+
*/
|
|
434
|
+
export function heartbeatLock(handle) {
|
|
435
|
+
const held = readLock(handle.path, handle.uid);
|
|
436
|
+
if (held?.info?.token !== handle.token) return false;
|
|
437
|
+
// Same host: liveness is the pid and its start time (L1), so `at` needs no
|
|
438
|
+
// refresh, and the lock is only read. A read-then-rewrite would erase a new
|
|
439
|
+
// holder that wrote between the read and the rewrite. Another host's
|
|
440
|
+
// reader still needs a fresh `at`: there the narrow read/rewrite window
|
|
441
|
+
// remains (documented).
|
|
442
|
+
let refresh = true;
|
|
443
|
+
if (sameMachine(held.info) && held.info.start !== undefined && handle.kind !== "writer") refresh = false; // @rule notify.heartbeat-no-local-rewrite
|
|
444
|
+
if (refresh) writePrivateAtomic(handle.path, JSON.stringify({ ...held.info, at: new Date().toISOString() }), { uid: handle.uid });
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Keep a wake lock while running (Lead L2). Every `intervalMs` (and on
|
|
450
|
+
* check()) the lock is re-read: if the token is gone or the read/refresh
|
|
451
|
+
* throws, onLost(reason) runs once and the guard stops. Returns
|
|
452
|
+
* { check, stop, lost }.
|
|
453
|
+
*/
|
|
454
|
+
export function guardLock(handle, { intervalMs = WAKE_HEARTBEAT_MS, onLost } = {}) {
|
|
455
|
+
let lost = null;
|
|
456
|
+
let timer = null;
|
|
457
|
+
const check = () => {
|
|
458
|
+
if (lost) return false;
|
|
459
|
+
let ok = false;
|
|
460
|
+
let reason = "token gone";
|
|
461
|
+
try { ok = heartbeatLock(handle); } catch (e) { reason = `${e.code ?? "error"}: ${String(e.message ?? e).slice(0, 160)}`; }
|
|
462
|
+
let held = true;
|
|
463
|
+
held = ok; // @rule notify.lock-loss-stops
|
|
464
|
+
if (held) return true;
|
|
465
|
+
lost = reason;
|
|
466
|
+
clearInterval(timer);
|
|
467
|
+
onLost?.(reason);
|
|
468
|
+
return false;
|
|
469
|
+
};
|
|
470
|
+
timer = setInterval(check, intervalMs);
|
|
471
|
+
return { check, stop: () => clearInterval(timer), get lost() { return lost; } };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** The live holder of a lock, or null. */
|
|
475
|
+
export function lockHolder(path, { uid = currentUid(), staleMs = WAKE_STALE_MS } = {}) {
|
|
476
|
+
const held = readLock(path, uid);
|
|
477
|
+
if (!held || lockIsStale(held, staleMs)) return null;
|
|
478
|
+
return held.info;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ── state ────────────────────────────────────────────────────────────────────
|
|
482
|
+
|
|
483
|
+
export function emptyState() {
|
|
484
|
+
return {
|
|
485
|
+
v: 1,
|
|
486
|
+
nextSeq: 1, // next eligibility-event seq
|
|
487
|
+
cursor: null, // notify cursor: last event seq claimed by a wake path; null = not activated
|
|
488
|
+
activatedAt: null,
|
|
489
|
+
events: [], // unclaimed eligibility events, oldest first (bounded)
|
|
490
|
+
recent: [], // event ids already emitted (claim keys), bounded
|
|
491
|
+
overflow: 0, // events dropped because `events` was full (counted, not listed)
|
|
492
|
+
budget: { starts: [], unknown: [], principals: {}, day: [] },
|
|
493
|
+
counters: {},
|
|
494
|
+
run: null, // the last claimed wake: { id, pid, host, startedAt, endedAt, n, seqTo, status }
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* V1 F1b: keep the serialized state within `cap` bytes before it is written.
|
|
500
|
+
* The oldest pending events go first (counted in overflow), then the oldest
|
|
501
|
+
* claim keys, then per-sender budget entries, then counters. Returns the
|
|
502
|
+
* JSON to write (`json` is the current serialization, to avoid redoing it).
|
|
503
|
+
*/
|
|
504
|
+
export function boundState(state, cap, json = JSON.stringify(state)) {
|
|
505
|
+
const size = () => Buffer.byteLength(json) + 1;
|
|
506
|
+
if (size() <= cap) return json;
|
|
507
|
+
let dropped = 0;
|
|
508
|
+
while (size() > cap && state.events.length) {
|
|
509
|
+
const n = Math.max(1, Math.ceil(state.events.length / 8));
|
|
510
|
+
state.events.splice(0, n);
|
|
511
|
+
dropped += n;
|
|
512
|
+
json = JSON.stringify(state);
|
|
513
|
+
}
|
|
514
|
+
state.overflow = (Number.isFinite(state.overflow) ? state.overflow : 0) + dropped;
|
|
515
|
+
state.counters.stateTrimmed = (state.counters.stateTrimmed ?? 0) + dropped;
|
|
516
|
+
for (const trim of [
|
|
517
|
+
() => { state.recent = state.recent.slice(Math.ceil(state.recent.length / 2)); return state.recent.length > 0; },
|
|
518
|
+
() => { state.budget.principals = {}; return false; },
|
|
519
|
+
() => { state.counters = { stateTrimmed: state.counters.stateTrimmed }; return false; },
|
|
520
|
+
]) {
|
|
521
|
+
json = JSON.stringify(state);
|
|
522
|
+
while (size() > cap) {
|
|
523
|
+
const more = trim();
|
|
524
|
+
json = JSON.stringify(state);
|
|
525
|
+
if (!more) break;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return json;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function validState(s) {
|
|
532
|
+
return s && typeof s === "object" && s.v === 1 && Number.isInteger(s.nextSeq) && s.nextSeq >= 1
|
|
533
|
+
&& (s.cursor === null || Number.isInteger(s.cursor)) && Array.isArray(s.events) && Array.isArray(s.recent)
|
|
534
|
+
&& s.budget && typeof s.budget === "object" && s.counters && typeof s.counters === "object";
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* NotifyStore — custody-checked access to <home>/notify.
|
|
539
|
+
* open() check the dir and every file in it (once per instance)
|
|
540
|
+
* mutate(fn) writer lock -> load state -> fn(state, tx) -> save if changed -> log -> status -> unlock
|
|
541
|
+
* snapshot() unlocked read of state (for polling)
|
|
542
|
+
* acquireWake() the single-wake-path lock
|
|
543
|
+
*/
|
|
544
|
+
export class NotifyStore {
|
|
545
|
+
constructor(home, { uid = currentUid(), maxBytes = STATE_MAX_BYTES } = {}) {
|
|
546
|
+
this.home = home;
|
|
547
|
+
this.dir = join(home, NOTIFY_DIR);
|
|
548
|
+
this.uid = uid;
|
|
549
|
+
this.maxBytes = maxBytes; // state.json write cap (and normal read size)
|
|
550
|
+
this._opened = false;
|
|
551
|
+
this._warnedOversize = false;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
path(name) { return join(this.dir, name); }
|
|
555
|
+
|
|
556
|
+
/** Check custody of notify/ and everything in it; refuse legacy plaintext logs. */
|
|
557
|
+
open() {
|
|
558
|
+
if (this._opened) return this;
|
|
559
|
+
ensurePrivateDir(this.dir, this.uid);
|
|
560
|
+
const now = Date.now();
|
|
561
|
+
for (const name of readdirSync(this.dir)) {
|
|
562
|
+
const p = this.path(name);
|
|
563
|
+
let st;
|
|
564
|
+
try { st = lstatSync(p); } catch (e) { if (e.code === "ENOENT") continue; throw e; }
|
|
565
|
+
if (st.isFile() && st.nlink === 0) continue; // replaced or removed while we looked
|
|
566
|
+
// A temp file left by an interrupted write: ours by name, regular, old.
|
|
567
|
+
if (/\.tmp-\d+-[0-9a-f]+$/.test(name) || /\.stale-\d+-[0-9a-f]+$/.test(name)) {
|
|
568
|
+
if (st.isFile() && st.nlink === 1 && (this.uid === null || st.uid === this.uid) && now - st.mtimeMs > TMP_STALE_MS) {
|
|
569
|
+
try { unlinkSync(p); } catch (_e) {}
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
assertSafeFile(st, p, this.uid); // @rule notify.custody-every-file
|
|
574
|
+
if ((st.mode & 0o777) !== 0o600) chmodSync(p, 0o600);
|
|
575
|
+
}
|
|
576
|
+
for (const name of [LOG_FILE, ...LOG_ROTATED]) this._refuseLegacyPlaintext(this.path(name));
|
|
577
|
+
this._opened = true;
|
|
578
|
+
return this;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
_refuseLegacyPlaintext(p) {
|
|
582
|
+
const raw = readPrivateFile(p, { uid: this.uid, maxBytes: 64 * 1024 * 1024 });
|
|
583
|
+
if (raw === null) return;
|
|
584
|
+
for (const line of raw.split("\n")) {
|
|
585
|
+
if (!line.trim()) continue;
|
|
586
|
+
let j;
|
|
587
|
+
try { j = JSON.parse(line); } catch (_e) { continue; }
|
|
588
|
+
const recs = j && typeof j === "object" ? [j, ...(Array.isArray(j.records) ? j.records : [])] : [];
|
|
589
|
+
if (recs.some((r) => r && typeof r === "object" && Object.hasOwn(r, "text"))) throw legacyPlaintext(p); // @rule notify.legacy-plaintext-refused
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
_load() {
|
|
594
|
+
const p = this.path(STATE_FILE);
|
|
595
|
+
const raw = readPrivateFile(p, { uid: this.uid, maxBytes: STATE_READ_CEILING });
|
|
596
|
+
if (raw === null) return emptyState();
|
|
597
|
+
let s = null;
|
|
598
|
+
try { s = JSON.parse(raw); } catch (_e) { s = null; }
|
|
599
|
+
if (validState(s)) {
|
|
600
|
+
if (Buffer.byteLength(raw) > this.maxBytes) this._salvageOversize(s, Buffer.byteLength(raw)); // @rule notify.state-oversize-salvage
|
|
601
|
+
return s;
|
|
602
|
+
}
|
|
603
|
+
// Unreadable state: keep it (private) for the owner, start again from the tip.
|
|
604
|
+
const aside = this.path(`state.corrupt-${Date.now()}.json`);
|
|
605
|
+
renameSync(p, aside);
|
|
606
|
+
const fresh = emptyState();
|
|
607
|
+
fresh.counters.stateRecovered = 1;
|
|
608
|
+
return fresh;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* V1 F1c: an oversized state.json (written before the write cap existed)
|
|
613
|
+
* is NOT "corrupt -> fresh state", which would reset the durable budget.
|
|
614
|
+
* Keep cursor, budget, counters and claims; drop the pending events into
|
|
615
|
+
* overflow (counted); warn once.
|
|
616
|
+
*/
|
|
617
|
+
_salvageOversize(s, bytes) {
|
|
618
|
+
const n = s.events.length;
|
|
619
|
+
s.overflow = (Number.isFinite(s.overflow) ? s.overflow : 0) + n;
|
|
620
|
+
s.events = [];
|
|
621
|
+
s.counters.stateOversize = (s.counters.stateOversize ?? 0) + 1;
|
|
622
|
+
this._repaired = true; // write the salvaged state back on this mutate, even if nothing else changes
|
|
623
|
+
if (!this._warnedOversize) {
|
|
624
|
+
this._warnedOversize = true;
|
|
625
|
+
// eslint-disable-next-line no-console
|
|
626
|
+
console.warn(`pillar: notify/state.json was ${bytes} bytes (cap ${this.maxBytes}); its ${n} pending events were dropped and counted in overflow; budget and counters kept`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
_save(state) {
|
|
631
|
+
let json = JSON.stringify(state);
|
|
632
|
+
json = boundState(state, this.maxBytes, json); // @rule notify.state-write-cap
|
|
633
|
+
writePrivateAtomic(this.path(STATE_FILE), `${json}\n`, { uid: this.uid });
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Unlocked, read-only look at state: the state, or null when absent or unreadable. Never repairs. */
|
|
637
|
+
peek() {
|
|
638
|
+
this.open();
|
|
639
|
+
const raw = readPrivateFile(this.path(STATE_FILE), { uid: this.uid, maxBytes: STATE_READ_CEILING });
|
|
640
|
+
if (raw === null) return null;
|
|
641
|
+
try { const s = JSON.parse(raw); return validState(s) ? s : null; } catch (_e) { return null; }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Unlocked snapshot (may be one write behind). */
|
|
645
|
+
snapshot() {
|
|
646
|
+
this.open();
|
|
647
|
+
return this._load();
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* Run fn(state, tx) under the writer lock and commit state by one rename
|
|
652
|
+
* when it changed. tx.appendLog(lines) writes the log under the same lock.
|
|
653
|
+
* Throws NotifyCustodyError, or an error with code "notify-busy" when the
|
|
654
|
+
* lock stays held past waitMs.
|
|
655
|
+
*/
|
|
656
|
+
async mutate(fn, { waitMs = WRITER_WAIT_MS } = {}) {
|
|
657
|
+
this.open();
|
|
658
|
+
let lock = NO_LOCK;
|
|
659
|
+
lock = await acquireLock(this.path(WRITER_LOCK), { uid: this.uid, staleMs: WRITER_STALE_MS, waitMs, kind: "writer" }); // @rule notify.writer-lock
|
|
660
|
+
if (!lock) {
|
|
661
|
+
const e = new Error(`notify: the writer lock ${this.path(WRITER_LOCK)} stayed held for ${waitMs} ms`);
|
|
662
|
+
e.code = "notify-busy";
|
|
663
|
+
throw e;
|
|
664
|
+
}
|
|
665
|
+
try {
|
|
666
|
+
const state = this._load();
|
|
667
|
+
const before = JSON.stringify(state);
|
|
668
|
+
const logLines = [];
|
|
669
|
+
let status = null;
|
|
670
|
+
const tx = { appendLog: (lines) => { logLines.push(...lines); }, writeStatus: (obj) => { status = obj; } };
|
|
671
|
+
const result = await fn(state, tx);
|
|
672
|
+
const repaired = this._repaired;
|
|
673
|
+
this._repaired = false;
|
|
674
|
+
if (repaired || JSON.stringify(state) !== before) this._save(state); // the durable boundary
|
|
675
|
+
this._appendLog(logLines); // after the commit, under the same lock
|
|
676
|
+
if (status) writePrivateAtomic(this.path(STATUS_FILE), `${JSON.stringify(status)}\n`, { uid: this.uid });
|
|
677
|
+
return result;
|
|
678
|
+
} finally {
|
|
679
|
+
releaseLock(lock);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** Append lines to notifications.jsonl, rotating by lines, bytes and age. Caller holds the writer lock. */
|
|
684
|
+
_appendLog(lines) {
|
|
685
|
+
if (!lines.length) return;
|
|
686
|
+
const active = this.path(LOG_FILE);
|
|
687
|
+
const existing = readPrivateFile(active, { uid: this.uid, maxBytes: 64 * 1024 * 1024 }) ?? "";
|
|
688
|
+
const old = existing.split("\n").filter((l) => l.trim());
|
|
689
|
+
const add = lines.map((l) => (typeof l === "string" ? l : JSON.stringify(l)));
|
|
690
|
+
const bytes = (arr) => arr.reduce((n, l) => n + Buffer.byteLength(l) + 1, 0);
|
|
691
|
+
const over = old.length > 0 && (old.length + add.length > LOG_MAX_LINES || bytes(old) + bytes(add) > LOG_MAX_BYTES);
|
|
692
|
+
if (over) this._rotate(); // @rule notify.log-rotate
|
|
693
|
+
const keep = over ? add : [...old, ...add];
|
|
694
|
+
writePrivateAtomic(active, `${keep.slice(-LOG_MAX_LINES).join("\n")}\n`, { uid: this.uid });
|
|
695
|
+
this._expireRotated();
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
_rotate() {
|
|
699
|
+
const [r1, r2] = LOG_ROTATED.map((n) => this.path(n));
|
|
700
|
+
removePrivateFile(r2, this.uid);
|
|
701
|
+
try { assertSafeFile(lstatSync(r1), r1, this.uid); renameSync(r1, r2); } catch (e) { if (e.code !== "ENOENT") throw e; }
|
|
702
|
+
const active = this.path(LOG_FILE);
|
|
703
|
+
assertSafeFile(lstatSync(active), active, this.uid);
|
|
704
|
+
renameSync(active, r1);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
_expireRotated(now = Date.now()) {
|
|
708
|
+
for (const n of LOG_ROTATED) {
|
|
709
|
+
const p = this.path(n);
|
|
710
|
+
let st;
|
|
711
|
+
try { st = lstatSync(p); } catch (e) { if (e.code === "ENOENT") continue; throw e; }
|
|
712
|
+
assertSafeFile(st, p, this.uid);
|
|
713
|
+
if (now - st.mtimeMs > LOG_MAX_AGE_MS) unlinkSync(p); // @rule notify.log-age
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Lines of the active log (tests and `pillar notify --status`). */
|
|
718
|
+
readLog() {
|
|
719
|
+
this.open();
|
|
720
|
+
const raw = readPrivateFile(this.path(LOG_FILE), { uid: this.uid, maxBytes: 64 * 1024 * 1024 });
|
|
721
|
+
return raw ? raw.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l)) : [];
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Take the wake-path lock for `kind` ("resident" | "fallback"). Returns
|
|
726
|
+
* { handle } or { heldBy } when another live wake path holds it.
|
|
727
|
+
*/
|
|
728
|
+
async acquireWake(kind) {
|
|
729
|
+
this.open();
|
|
730
|
+
const p = this.path(WAKE_LOCK);
|
|
731
|
+
let handle = { ...NO_LOCK, kind };
|
|
732
|
+
handle = await acquireLock(p, { uid: this.uid, staleMs: WAKE_STALE_MS, waitMs: 0, kind }); // @rule notify.one-wake-path
|
|
733
|
+
if (handle) return { handle };
|
|
734
|
+
return { heldBy: lockHolder(p, { uid: this.uid }) ?? { kind: "unknown" } };
|
|
735
|
+
}
|
|
736
|
+
}
|