@aeondave/pi-persona-mind 0.9.6 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +137 -135
- package/CHANGELOG.md +287 -270
- package/LICENSE +24 -24
- package/README.md +84 -171
- package/docs/DESIGN.md +605 -573
- package/docs/MEMORY-RESEARCH.md +163 -163
- package/package.json +15 -6
- package/src/core/auto-optimize.ts +323 -249
- package/src/core/backlog.ts +228 -228
- package/src/core/blocked.ts +38 -38
- package/src/core/capture.ts +155 -154
- package/src/core/context-budget.ts +74 -74
- package/src/core/handoff-store.ts +111 -111
- package/src/core/handoff.ts +70 -70
- package/src/core/host-compat.ts +16 -16
- package/src/core/ids.ts +59 -59
- package/src/core/inject.ts +247 -247
- package/src/core/knowledge-review.ts +107 -107
- package/src/core/memory-read.ts +34 -34
- package/src/core/memory.ts +321 -321
- package/src/core/migrate.ts +713 -713
- package/src/core/mind-settings.ts +54 -54
- package/src/core/optimize-history.ts +163 -163
- package/src/core/optimize-service.ts +189 -180
- package/src/core/optimize.ts +127 -127
- package/src/core/retrieval.ts +164 -164
- package/src/core/scanner.ts +146 -146
- package/src/core/scope.ts +201 -205
- package/src/core/service.ts +720 -720
- package/src/core/session-memory.ts +71 -71
- package/src/core/store.ts +1002 -1002
- package/src/extension/activity.ts +79 -79
- package/src/extension/auto-optimize-session.ts +143 -143
- package/src/extension/auto-optimize.ts +565 -569
- package/src/extension/handoff.ts +23 -23
- package/src/extension/knowledge-review.ts +229 -229
- package/src/extension/memory-inspector.ts +82 -82
- package/src/extension/mind-actions.ts +38 -38
- package/src/extension/mind-worker.ts +32 -32
- package/src/extension/persona-dependency.ts +76 -76
- package/src/extension/reference-anchor.ts +48 -0
- package/src/extension/review-evidence.ts +222 -222
- package/src/extension/worker-memory-anchor.ts +28 -28
- package/src/index.ts +1357 -1310
- package/src/session-memory.ts +127 -122
- package/src/tools/backlog.ts +126 -126
- package/src/tools/memory-handoff.ts +30 -30
- package/src/tools/memory-history.ts +46 -46
- package/src/tools/memory.ts +6 -4
- package/src/ui/card-frame.ts +161 -161
- package/src/ui/inspector-frame.ts +44 -44
- package/src/ui/memory-inspector.ts +464 -464
- package/src/ui/mind-result-card.ts +48 -48
- package/src/ui/presentation.ts +87 -87
- package/src/ui/session-note-card.ts +58 -56
package/src/core/store.ts
CHANGED
|
@@ -1,1002 +1,1002 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable, cross-OS, concurrency-safe JSON persistence for pi-persona-mind's stores.
|
|
3
|
-
*
|
|
4
|
-
* A store is one JSON file rewritten in full. Without care, a crash mid-write leaves a torn
|
|
5
|
-
* file that loads as a silent empty store (memory vanishes with no signal), and two writers
|
|
6
|
-
* race with last-writer-wins. These primitives prevent both, using only the Node stdlib — no
|
|
7
|
-
* native binding, no `flock`/`lockf` (so it works on Windows, unlike the POSIX-lock stores in
|
|
8
|
-
* the Pi memory ecosystem):
|
|
9
|
-
*
|
|
10
|
-
* 1. {@link atomicWriteFile} — temp-in-same-dir → fsync → atomic rename. A crash before the
|
|
11
|
-
* rename leaves the prior file intact; never a partially-written store.
|
|
12
|
-
* 2. {@link casUpdate} — the load→mutate→write runs inside a per-file advisory lockfile
|
|
13
|
-
* (`wx`/O_EXCL create, polled, with dead-local recovery for a crashed holder and an ownership
|
|
14
|
-
* token so a stolen hold is never wrongly released). No committed write is lost.
|
|
15
|
-
* 3. {@link quarantineCorrupt} — a file that fails validation is moved aside to `*.corrupt-N`
|
|
16
|
-
* (never silently replaced with empty, which would present absence as current fact).
|
|
17
|
-
*
|
|
18
|
-
* The pattern is adapted from OpenLore's `atomic-store.ts` (clay-good/openlore, MIT).
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
import { constants as fsConstants } from "node:fs";
|
|
22
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
23
|
-
import { copyFile, link, lstat, mkdir, open, rename, rmdir, unlink } from "node:fs/promises";
|
|
24
|
-
import { hostname } from "node:os";
|
|
25
|
-
import { performance } from "node:perf_hooks";
|
|
26
|
-
import { basename, dirname, join } from "node:path";
|
|
27
|
-
|
|
28
|
-
/** Every persisted store carries the monotonic compare-and-swap counter. */
|
|
29
|
-
export interface StoreFile<E> {
|
|
30
|
-
version: number;
|
|
31
|
-
updatedAt: string;
|
|
32
|
-
/** Monotonic write counter: orders writes and lets an external reader detect change. */
|
|
33
|
-
sequence: number;
|
|
34
|
-
entries: E[];
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* A tolerant read together with whether it saw every row. `complete` is false when the result may be
|
|
39
|
-
* missing rows that exist on disk: rows hidden as invalid, a file quarantined to start empty, or an
|
|
40
|
-
* existing backup that could not be used while the live file is absent. `reasons` says why.
|
|
41
|
-
*/
|
|
42
|
-
export interface StoreRead<E> {
|
|
43
|
-
file: StoreFile<E>;
|
|
44
|
-
complete: boolean;
|
|
45
|
-
reasons: string[];
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface StoreSnapshot<E> {
|
|
49
|
-
store: StoreFile<E>;
|
|
50
|
-
/** Binds the exact live bytes and store path, including same-sequence replacements. */
|
|
51
|
-
fingerprint: string;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export class StoreConflictError extends Error {
|
|
55
|
-
constructor() { super("memory store changed since preview; inspect and preview again"); this.name = "StoreConflictError"; }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Defensive defaults for out-of-band/corrupt stores. Normal stores are far smaller than these. */
|
|
59
|
-
export const DEFAULT_STORE_MAX_BYTES = 4 * 1024 * 1024;
|
|
60
|
-
export const DEFAULT_STORE_MAX_ENTRIES = 10_000;
|
|
61
|
-
|
|
62
|
-
// Lock tokens are process-local sequence values. Temp names use cryptographic randomness and are
|
|
63
|
-
// still opened with O_EXCL so a pre-created symlink can never be followed by a writer.
|
|
64
|
-
let lockSeq = 0;
|
|
65
|
-
|
|
66
|
-
// Invalid raw entries are retained only inside an update's private state. They are never returned by
|
|
67
|
-
// JsonStore.load(), but the next atomic rewrite can put them back verbatim instead of silently
|
|
68
|
-
// erasing data that the current validator does not understand yet.
|
|
69
|
-
const PRESERVED_INVALID_ENTRIES: unique symbol = Symbol("preservedInvalidEntries");
|
|
70
|
-
// Set on an empty store that stands in for data which exists but could not be read, so loadChecked()
|
|
71
|
-
// can tell it from a store that is genuinely empty. Never persisted.
|
|
72
|
-
const UNREAD_REASON: unique symbol = Symbol("unreadReason");
|
|
73
|
-
type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[]; [UNREAD_REASON]?: string };
|
|
74
|
-
|
|
75
|
-
/** What the `.bak` sidecar offers: nothing, a valid store, or a file that exists but cannot be used. */
|
|
76
|
-
type BackupRead<E> = { kind: "absent" } | { kind: "usable"; store: InternalStoreFile<E> } | { kind: "unusable"; reason: string };
|
|
77
|
-
|
|
78
|
-
export interface AtomicWriteOptions {
|
|
79
|
-
/** Refresh the `.bak` sidecar from the current live file only when this returns true for its
|
|
80
|
-
* bytes. Guards against copying a torn file — one that load() just recovered FROM `.bak` — over
|
|
81
|
-
* the only good backup, which would destroy the sole recoverable copy. Absent ⇒ always refresh. */
|
|
82
|
-
backupIf?: (currentRaw: string) => boolean;
|
|
83
|
-
/** Maximum live-file bytes read when evaluating `backupIf`; oversized files are not backed up. */
|
|
84
|
-
maxBackupBytes?: number;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export type BoundedReadFailureKind = "bytes" | "entries" | "path";
|
|
88
|
-
|
|
89
|
-
export class BoundedReadFailure extends Error {
|
|
90
|
-
readonly kind: BoundedReadFailureKind;
|
|
91
|
-
|
|
92
|
-
constructor(kind: BoundedReadFailureKind, message: string) {
|
|
93
|
-
super(message);
|
|
94
|
-
this.kind = kind;
|
|
95
|
-
this.name = "BoundedReadFailure";
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Thrown when a store envelope carries a version this build does not implement. It is deliberately
|
|
101
|
-
* NOT a corruption signal: a store written by another version is intact, just unreadable here, so it
|
|
102
|
-
* must be left in place (never quarantined, never overwritten) until a build that understands it —
|
|
103
|
-
* or a migration — runs. Failing loudly is the only non-destructive answer available.
|
|
104
|
-
*/
|
|
105
|
-
export class StoreVersionError extends Error {
|
|
106
|
-
readonly found: number;
|
|
107
|
-
readonly expected: number;
|
|
108
|
-
|
|
109
|
-
constructor(found: number, expected: number) {
|
|
110
|
-
super(`mind store version ${found} was written by a different pi-persona-mind build (this one reads version ${expected}); the file is left untouched`);
|
|
111
|
-
this.found = found;
|
|
112
|
-
this.expected = expected;
|
|
113
|
-
this.name = "StoreVersionError";
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** Thrown before an update writes a store that the next bounded load would reject. */
|
|
118
|
-
export class StoreCapacityError extends Error {
|
|
119
|
-
readonly kind: "bytes" | "entries";
|
|
120
|
-
readonly actual: number;
|
|
121
|
-
readonly limit: number;
|
|
122
|
-
|
|
123
|
-
constructor(kind: "bytes" | "entries", actual: number, limit: number) {
|
|
124
|
-
super(`mind store capacity: ${kind} ${actual} exceeds limit ${limit}`);
|
|
125
|
-
this.kind = kind;
|
|
126
|
-
this.actual = actual;
|
|
127
|
-
this.limit = limit;
|
|
128
|
-
this.name = "StoreCapacityError";
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const noFollow = (fsConstants as { O_NOFOLLOW?: number }).O_NOFOLLOW;
|
|
133
|
-
const readFlags: string | number = noFollow === undefined ? "r" : fsConstants.O_RDONLY | noFollow;
|
|
134
|
-
|
|
135
|
-
function sameFile(a: { dev: number; ino: number }, b: { dev: number; ino: number }): boolean {
|
|
136
|
-
return a.dev === b.dev && a.ino === b.ino;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
const LOCK_POLL_MS = 25;
|
|
140
|
-
const LOCK_MAX_WAIT_MS = 30_000;
|
|
141
|
-
const REPLACE_MAX_WAIT_MS = 30_000;
|
|
142
|
-
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
|
143
|
-
|
|
144
|
-
type LockStats = { dev: number; ino: number };
|
|
145
|
-
|
|
146
|
-
export interface FileLockOptions {
|
|
147
|
-
/** Internal seam used to prove cleanup when closing a newly-created lock handle fails. */
|
|
148
|
-
close?: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function unlinkIfSameFile(path: string, expected: LockStats): Promise<void> {
|
|
152
|
-
try {
|
|
153
|
-
const current = await lstat(path);
|
|
154
|
-
if (sameFile(expected, current)) await unlink(path).catch(() => {});
|
|
155
|
-
} catch {
|
|
156
|
-
/* the failed acquisition may already have been cleaned up */
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Create a lockfile and clean up its inode if writing or closing the handle fails. */
|
|
161
|
-
async function createLockFile(
|
|
162
|
-
lockPath: string,
|
|
163
|
-
token: string,
|
|
164
|
-
closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void> = (handle) => handle.close(),
|
|
165
|
-
): Promise<void> {
|
|
166
|
-
const fh = await open(lockPath, "wx");
|
|
167
|
-
let created: LockStats | undefined;
|
|
168
|
-
try {
|
|
169
|
-
created = await fh.stat();
|
|
170
|
-
await fh.writeFile(token);
|
|
171
|
-
await closeHandle(fh);
|
|
172
|
-
} catch (err) {
|
|
173
|
-
// A failed write can leave an empty/partial lock that no waiter can safely attribute. Close
|
|
174
|
-
// the descriptor when possible, then remove only the inode this acquisition created.
|
|
175
|
-
await fh.close().catch(() => {});
|
|
176
|
-
if (created) await unlinkIfSameFile(lockPath, created);
|
|
177
|
-
throw err;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** Read at most one byte beyond the fstat-observed size, rejecting symlinks, replacements, and floods. */
|
|
182
|
-
export async function readTextFileBounded(path: string, maxBytes: number): Promise<string> {
|
|
183
|
-
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("store maxBytes must be a positive safe integer");
|
|
184
|
-
let listed;
|
|
185
|
-
try {
|
|
186
|
-
listed = await lstat(path);
|
|
187
|
-
} catch (err) {
|
|
188
|
-
throw err;
|
|
189
|
-
}
|
|
190
|
-
if (listed.isSymbolicLink()) throw new BoundedReadFailure("path", "store path is a symbolic link");
|
|
191
|
-
if (!listed.isFile()) throw new BoundedReadFailure("path", "store path is not a regular file");
|
|
192
|
-
|
|
193
|
-
let fh;
|
|
194
|
-
try {
|
|
195
|
-
fh = await open(path, readFlags);
|
|
196
|
-
} catch (err) {
|
|
197
|
-
if ((err as NodeJS.ErrnoException).code === "ELOOP") {
|
|
198
|
-
throw new BoundedReadFailure("path", "store path is a symbolic link");
|
|
199
|
-
}
|
|
200
|
-
throw err;
|
|
201
|
-
}
|
|
202
|
-
try {
|
|
203
|
-
const opened = await fh.stat();
|
|
204
|
-
if (!opened.isFile() || !sameFile(listed, opened)) {
|
|
205
|
-
throw new BoundedReadFailure("path", "store path changed or is not a regular file");
|
|
206
|
-
}
|
|
207
|
-
const observedSize = opened.size;
|
|
208
|
-
if (!Number.isSafeInteger(observedSize) || observedSize > maxBytes) {
|
|
209
|
-
throw new BoundedReadFailure("bytes", `store file exceeds the ${maxBytes}-byte limit`);
|
|
210
|
-
}
|
|
211
|
-
const bytes = Buffer.allocUnsafe(observedSize + 1);
|
|
212
|
-
let offset = 0;
|
|
213
|
-
while (offset < bytes.length) {
|
|
214
|
-
const result = await fh.read(bytes, offset, bytes.length - offset, offset);
|
|
215
|
-
if (result.bytesRead === 0) break;
|
|
216
|
-
offset += result.bytesRead;
|
|
217
|
-
}
|
|
218
|
-
if (offset > observedSize) throw new BoundedReadFailure("bytes", "store file grew while it was being read");
|
|
219
|
-
const finalOpened = await fh.stat();
|
|
220
|
-
if (!finalOpened.isFile() || !sameFile(opened, finalOpened) || finalOpened.size !== observedSize || offset !== observedSize) {
|
|
221
|
-
throw new BoundedReadFailure("path", "store file changed or was truncated while it was being read");
|
|
222
|
-
}
|
|
223
|
-
const current = await lstat(path);
|
|
224
|
-
if (current.isSymbolicLink() || !current.isFile() || !sameFile(opened, current) || current.size !== observedSize) {
|
|
225
|
-
throw new BoundedReadFailure("path", "store path changed while it was being read");
|
|
226
|
-
}
|
|
227
|
-
return bytes.subarray(0, offset).toString("utf8");
|
|
228
|
-
} finally {
|
|
229
|
-
await fh.close();
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const MAX_LOCK_TOKEN_BYTES = 1024;
|
|
234
|
-
|
|
235
|
-
async function openRandomTemp(dir: string, base: string): Promise<{ path: string; handle: Awaited<ReturnType<typeof open>> }> {
|
|
236
|
-
for (let attempt = 0; attempt < 16; attempt++) {
|
|
237
|
-
const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
|
|
238
|
-
try {
|
|
239
|
-
return { path, handle: await open(path, "wx") };
|
|
240
|
-
} catch (err) {
|
|
241
|
-
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
throw new Error(`mind store: could not allocate a unique temporary file beside ${base}`);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
async function copyToRandomTemp(source: string, dir: string, base: string): Promise<string> {
|
|
248
|
-
for (let attempt = 0; attempt < 16; attempt++) {
|
|
249
|
-
const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
|
|
250
|
-
try {
|
|
251
|
-
await copyFile(source, path, fsConstants.COPYFILE_EXCL);
|
|
252
|
-
return path;
|
|
253
|
-
} catch (err) {
|
|
254
|
-
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
throw new Error(`mind store: could not allocate a unique backup temporary file beside ${base}`);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Replace a destination path without ever opening/following an existing destination symlink. */
|
|
261
|
-
async function replacePath(staged: string, destination: string): Promise<void> {
|
|
262
|
-
const started = performance.now();
|
|
263
|
-
try {
|
|
264
|
-
await rename(staged, destination);
|
|
265
|
-
return;
|
|
266
|
-
} catch (err) {
|
|
267
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
268
|
-
if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
|
|
269
|
-
}
|
|
270
|
-
// Windows may reject rename over a live destination while another process still has an open
|
|
271
|
-
// handle. Keep the staged bytes in place and retry the remove/rename sequence until that handle
|
|
272
|
-
// closes. The destination identity is checked before unlinking so a concurrent replacement is
|
|
273
|
-
// never removed by a stale retry.
|
|
274
|
-
for (;;) {
|
|
275
|
-
let observed;
|
|
276
|
-
try {
|
|
277
|
-
observed = await lstat(destination);
|
|
278
|
-
} catch (err) {
|
|
279
|
-
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
280
|
-
}
|
|
281
|
-
if (observed) {
|
|
282
|
-
let current;
|
|
283
|
-
try {
|
|
284
|
-
current = await lstat(destination);
|
|
285
|
-
} catch (err) {
|
|
286
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
287
|
-
throw err;
|
|
288
|
-
}
|
|
289
|
-
if (!sameFile(observed, current)) continue;
|
|
290
|
-
try {
|
|
291
|
-
await unlink(destination);
|
|
292
|
-
} catch (err) {
|
|
293
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
294
|
-
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
|
|
295
|
-
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
296
|
-
await sleep(LOCK_POLL_MS);
|
|
297
|
-
continue;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
try {
|
|
301
|
-
await rename(staged, destination);
|
|
302
|
-
return;
|
|
303
|
-
} catch (err) {
|
|
304
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
305
|
-
if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
|
|
306
|
-
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
307
|
-
await sleep(LOCK_POLL_MS);
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Replace the live store atomically. Windows rejects rename-over-destination while a reader still
|
|
314
|
-
* holds the destination open; retry the SAME rename (without unlinking the committed file) until
|
|
315
|
-
* that short-lived reader closes. The old or new file is therefore always present.
|
|
316
|
-
*/
|
|
317
|
-
async function replaceLivePath(staged: string, destination: string): Promise<void> {
|
|
318
|
-
const started = performance.now();
|
|
319
|
-
for (;;) {
|
|
320
|
-
try {
|
|
321
|
-
await rename(staged, destination);
|
|
322
|
-
return;
|
|
323
|
-
} catch (err) {
|
|
324
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
325
|
-
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
|
|
326
|
-
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
327
|
-
await sleep(LOCK_POLL_MS);
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
async function refreshBackup(source: string, destination: string): Promise<void> {
|
|
333
|
-
const listed = await lstat(source);
|
|
334
|
-
if (!listed.isFile()) return;
|
|
335
|
-
const staged = await copyToRandomTemp(source, dirname(destination), basename(destination));
|
|
336
|
-
let replaced = false;
|
|
337
|
-
try {
|
|
338
|
-
const current = await lstat(source);
|
|
339
|
-
if (!current.isFile() || !sameFile(listed, current)) return;
|
|
340
|
-
await replacePath(staged, destination);
|
|
341
|
-
replaced = true;
|
|
342
|
-
} finally {
|
|
343
|
-
if (!replaced) await unlink(staged).catch(() => {});
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/** Lock metadata is trusted only when it is a tiny regular file; never read an attacker-sized token. */
|
|
348
|
-
async function readLockToken(lockPath: string): Promise<string | null> {
|
|
349
|
-
let listed;
|
|
350
|
-
try {
|
|
351
|
-
listed = await lstat(lockPath);
|
|
352
|
-
if (!listed.isFile()) return null;
|
|
353
|
-
const fh = await open(lockPath, readFlags);
|
|
354
|
-
try {
|
|
355
|
-
const opened = await fh.stat();
|
|
356
|
-
if (!opened.isFile() || !sameFile(listed, opened) || opened.size > MAX_LOCK_TOKEN_BYTES) return null;
|
|
357
|
-
const bytes = Buffer.alloc(MAX_LOCK_TOKEN_BYTES);
|
|
358
|
-
const result = await fh.read(bytes, 0, MAX_LOCK_TOKEN_BYTES, 0);
|
|
359
|
-
if (result.bytesRead !== opened.size) return null;
|
|
360
|
-
const current = await lstat(lockPath);
|
|
361
|
-
if (!current.isFile() || !sameFile(opened, current) || current.size !== opened.size) return null;
|
|
362
|
-
return bytes.subarray(0, result.bytesRead).toString("utf8");
|
|
363
|
-
} finally {
|
|
364
|
-
await fh.close();
|
|
365
|
-
}
|
|
366
|
-
} catch {
|
|
367
|
-
return null;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* Write `data` to `path` atomically: to a sibling temp file, flushed to disk (`fsync`), then
|
|
373
|
-
* moved into place with a single atomic `rename`. A crash before the rename leaves the previous
|
|
374
|
-
* file untouched. The directory fsync is best-effort — Windows rejects it, and the data fsync
|
|
375
|
-
* already bounds the loss.
|
|
376
|
-
*/
|
|
377
|
-
export async function atomicWriteFile(path: string, data: string, opts: AtomicWriteOptions = {}): Promise<void> {
|
|
378
|
-
const dir = dirname(path);
|
|
379
|
-
await mkdir(dir, { recursive: true });
|
|
380
|
-
const temp = await openRandomTemp(dir, basename(path));
|
|
381
|
-
const tmp = temp.path;
|
|
382
|
-
let renamed = false;
|
|
383
|
-
try {
|
|
384
|
-
const fh = temp.handle;
|
|
385
|
-
try {
|
|
386
|
-
await fh.writeFile(data, "utf-8");
|
|
387
|
-
await fh.sync();
|
|
388
|
-
} finally {
|
|
389
|
-
await fh.close();
|
|
390
|
-
}
|
|
391
|
-
// Preserve the current (known-good) file as a last-known-good sidecar BEFORE we overwrite it,
|
|
392
|
-
// so a later torn/truncated live file can be rolled back to it (JsonStore.load consults .bak
|
|
393
|
-
// before quarantining). But never clobber a good .bak with a live file that isn't itself good
|
|
394
|
-
// (a torn file we just recovered FROM .bak): that would destroy the only recoverable copy.
|
|
395
|
-
try {
|
|
396
|
-
if (!opts.backupIf) {
|
|
397
|
-
await refreshBackup(path, `${path}.bak`);
|
|
398
|
-
} else {
|
|
399
|
-
const current = await readTextFileBounded(path, opts.maxBackupBytes ?? DEFAULT_STORE_MAX_BYTES);
|
|
400
|
-
if (opts.backupIf(current)) await refreshBackup(path, `${path}.bak`);
|
|
401
|
-
}
|
|
402
|
-
} catch {
|
|
403
|
-
/* no current file, unsafe path, or oversized current file — nothing to preserve */
|
|
404
|
-
}
|
|
405
|
-
await replaceLivePath(tmp, path);
|
|
406
|
-
renamed = true;
|
|
407
|
-
} finally {
|
|
408
|
-
if (!renamed) await unlink(tmp).catch(() => {});
|
|
409
|
-
}
|
|
410
|
-
try {
|
|
411
|
-
const dh = await open(dir, "r");
|
|
412
|
-
try {
|
|
413
|
-
await dh.sync();
|
|
414
|
-
} finally {
|
|
415
|
-
await dh.close();
|
|
416
|
-
}
|
|
417
|
-
} catch {
|
|
418
|
-
/* directory fsync unsupported (e.g. Windows) — skip */
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// Dead-lock recovery is itself a critical section. The directory gate is process-wide (not merely
|
|
423
|
-
// an in-memory promise), and contenders check it before every acquisition attempt. A recovering
|
|
424
|
-
// process keeps the gate until it has installed its replacement token, so another process can never
|
|
425
|
-
// observe the old dead lock removed and enter the callback during the hand-off window.
|
|
426
|
-
const recoveryTails = new Map<string, Promise<void>>();
|
|
427
|
-
async function withRecoveryGate<T>(lockPath: string, fn: () => Promise<T>): Promise<T> {
|
|
428
|
-
const previous = recoveryTails.get(lockPath) ?? Promise.resolve();
|
|
429
|
-
let release!: () => void;
|
|
430
|
-
const current = new Promise<void>((resolve) => {
|
|
431
|
-
release = resolve;
|
|
432
|
-
});
|
|
433
|
-
recoveryTails.set(lockPath, current);
|
|
434
|
-
await previous;
|
|
435
|
-
try {
|
|
436
|
-
return await fn();
|
|
437
|
-
} finally {
|
|
438
|
-
release();
|
|
439
|
-
if (recoveryTails.get(lockPath) === current) recoveryTails.delete(lockPath);
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
function recoveryGatePath(lockPath: string): string {
|
|
444
|
-
return `${lockPath}.recovery`;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
async function recoveryGateExists(lockPath: string): Promise<boolean> {
|
|
448
|
-
try {
|
|
449
|
-
await lstat(recoveryGatePath(lockPath));
|
|
450
|
-
return true;
|
|
451
|
-
} catch (err) {
|
|
452
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
453
|
-
return true; // an unreadable gate is treated as held: fail closed, never race recovery
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
/**
|
|
458
|
-
* Is the lock held by a LOCAL process that is already dead? The lock token is `host:pid-seq`; only
|
|
459
|
-
* when the host matches ours can we probe the pid (`process.kill(pid, 0)`: ESRCH ⇒ gone). A token
|
|
460
|
-
* from another machine (network FS) or an unparseable/legacy one returns false and is never
|
|
461
|
-
* stealable by age: without a trustworthy owner identity, time alone cannot distinguish a crashed
|
|
462
|
-
* process from a slow-but-alive one.
|
|
463
|
-
*/
|
|
464
|
-
function tokenHolderIsDeadLocal(content: string): boolean {
|
|
465
|
-
const match = /^([^:\r\n]+):([0-9]+)-([0-9]+)$/.exec(content);
|
|
466
|
-
if (!match || match[1] !== hostname()) return false;
|
|
467
|
-
const pid = Number(match[2]);
|
|
468
|
-
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(Number(match[3]))) return false;
|
|
469
|
-
try {
|
|
470
|
-
process.kill(pid, 0);
|
|
471
|
-
return false; // exists (alive)
|
|
472
|
-
} catch (err) {
|
|
473
|
-
return (err as NodeJS.ErrnoException).code === "ESRCH"; // ESRCH ⇒ dead; EPERM ⇒ alive
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/**
|
|
478
|
-
* Recover a dead lock while holding a cross-process gate. The replacement lock is created before
|
|
479
|
-
* the gate is released; this is the key ordering that prevents a second process from deleting a
|
|
480
|
-
* fresh lock after observing the same old dead token. A recovery process that itself crashes leaves
|
|
481
|
-
* the gate behind; waiters fail closed after the normal bounded wait instead of guessing that a
|
|
482
|
-
* potentially live recovery owner is dead.
|
|
483
|
-
*/
|
|
484
|
-
async function recoverDeadLocalLock(
|
|
485
|
-
lockPath: string,
|
|
486
|
-
token: string,
|
|
487
|
-
closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>,
|
|
488
|
-
): Promise<boolean> {
|
|
489
|
-
return withRecoveryGate(lockPath, async () => {
|
|
490
|
-
const gate = recoveryGatePath(lockPath);
|
|
491
|
-
try {
|
|
492
|
-
await mkdir(gate);
|
|
493
|
-
} catch (err) {
|
|
494
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
495
|
-
// Windows may report EPERM while a contender's removed gate is still pending
|
|
496
|
-
// deletion. We acquired nothing: retry through the caller's bounded contention
|
|
497
|
-
// wait, without removing the gate or inspecting/replacing the canonical token.
|
|
498
|
-
if (code === "EEXIST" || (process.platform === "win32" && code === "EPERM")) return false;
|
|
499
|
-
throw err;
|
|
500
|
-
}
|
|
501
|
-
try {
|
|
502
|
-
const observed = await readLockToken(lockPath);
|
|
503
|
-
if (observed === null || !tokenHolderIsDeadLocal(observed)) return false;
|
|
504
|
-
// Re-read immediately before removal while every other contender is required to honor `gate`.
|
|
505
|
-
if ((await readLockToken(lockPath)) !== observed) return false;
|
|
506
|
-
await unlink(lockPath);
|
|
507
|
-
// Acquire the canonical lock before releasing the recovery gate. If this fails, the caller
|
|
508
|
-
// will continue polling; importantly, no other contender can enter during this hand-off.
|
|
509
|
-
await createLockFile(lockPath, token, closeHandle);
|
|
510
|
-
return true;
|
|
511
|
-
} finally {
|
|
512
|
-
await rmdir(gate).catch(() => {});
|
|
513
|
-
}
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
/** Thrown internally when the commit lock was stolen mid-critical-section; {@link casUpdate} re-acquires. */
|
|
518
|
-
class LockLostError extends Error {}
|
|
519
|
-
|
|
520
|
-
/**
|
|
521
|
-
* Run `fn` while holding a per-file advisory lock (exclusive-create lockfile, polled, with dead-local
|
|
522
|
-
* recovery for a crashed holder). The lock carries an ownership token — passed to `fn` so it can
|
|
523
|
-
* re-verify ownership before committing — and is released only if still ours, so a hold stolen after
|
|
524
|
-
* proving its local owner is dead is never wrongly deleted. Foreign, malformed, or otherwise
|
|
525
|
-
* unprobeable locks fail closed after the bounded wait instead of being stolen by age.
|
|
526
|
-
*/
|
|
527
|
-
export async function withFileLock<T>(lockPath: string, fn: (token: string) => Promise<T>, options: FileLockOptions = {}): Promise<T> {
|
|
528
|
-
await mkdir(dirname(lockPath), { recursive: true });
|
|
529
|
-
const token = `${hostname()}:${process.pid}-${lockSeq++}`;
|
|
530
|
-
const start = performance.now();
|
|
531
|
-
const closeHandle = options.close ?? ((handle: Awaited<ReturnType<typeof open>>) => handle.close());
|
|
532
|
-
for (;;) {
|
|
533
|
-
if (await recoveryGateExists(lockPath)) {
|
|
534
|
-
if (performance.now() - start > LOCK_MAX_WAIT_MS) {
|
|
535
|
-
throw new Error(
|
|
536
|
-
`mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
|
|
537
|
-
`(recovery gate is held; retry the operation)`,
|
|
538
|
-
);
|
|
539
|
-
}
|
|
540
|
-
await sleep(LOCK_POLL_MS);
|
|
541
|
-
continue;
|
|
542
|
-
}
|
|
543
|
-
try {
|
|
544
|
-
await createLockFile(lockPath, token, closeHandle);
|
|
545
|
-
break;
|
|
546
|
-
} catch (err) {
|
|
547
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
548
|
-
if (code !== "EEXIST") {
|
|
549
|
-
// Windows can report EPERM, rather than EEXIST, when another process has the
|
|
550
|
-
// lockfile open. Treat it as contention only when the path can be observed; a
|
|
551
|
-
// genuine permission failure on an absent/inaccessible path must still surface.
|
|
552
|
-
if (code !== "EPERM") throw err;
|
|
553
|
-
try {
|
|
554
|
-
await lstat(lockPath);
|
|
555
|
-
} catch (probeErr) {
|
|
556
|
-
// On Windows an open racing with a concurrent unlink can report EPERM even
|
|
557
|
-
// though the path has already vanished. Retry the acquisition; surfacing that
|
|
558
|
-
// transient error would strand otherwise live writers.
|
|
559
|
-
if ((probeErr as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
560
|
-
throw err;
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
// A crashed LOCAL holder is stolen at once (no 10s wait).
|
|
564
|
-
if (await recoverDeadLocalLock(lockPath, token, closeHandle)) {
|
|
565
|
-
break;
|
|
566
|
-
}
|
|
567
|
-
// A LIVE local holder is genuinely mid-critical-section, while a foreign or malformed
|
|
568
|
-
// token is unprobeable. Never time-steal either case: age cannot prove that the owner is
|
|
569
|
-
// dead, and stealing could let both writers pass their ownership checks and lose a commit.
|
|
570
|
-
if (performance.now() - start > LOCK_MAX_WAIT_MS) {
|
|
571
|
-
throw new Error(
|
|
572
|
-
`mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
|
|
573
|
-
`(sustained write contention) — retry the operation`,
|
|
574
|
-
);
|
|
575
|
-
}
|
|
576
|
-
await sleep(LOCK_POLL_MS);
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
try {
|
|
580
|
-
return await fn(token);
|
|
581
|
-
} finally {
|
|
582
|
-
try {
|
|
583
|
-
if ((await readLockToken(lockPath)) === token) await unlink(lockPath).catch(() => {});
|
|
584
|
-
} catch {
|
|
585
|
-
/* lock already gone */
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
/**
|
|
591
|
-
* Atomically read-modify-write a sequenced JSON store. The load→mutate→write runs inside the
|
|
592
|
-
* per-store lock, so the lock (not an optimistic sequence guard) is the serialization point:
|
|
593
|
-
* `mutate` always runs against the freshest on-disk store and a competing write cannot interleave.
|
|
594
|
-
* `mutate` MUST be a pure merge over the loaded store; every writer MUST go through this function.
|
|
595
|
-
*/
|
|
596
|
-
export async function casUpdate<T extends { sequence: number }>(opts: {
|
|
597
|
-
storePath: string;
|
|
598
|
-
load: (token?: string) => Promise<T>;
|
|
599
|
-
mutate: (current: T) => T;
|
|
600
|
-
serialize: (next: T) => string;
|
|
601
|
-
/** Forwarded to atomicWriteFile: gate the `.bak` refresh on the current live file being valid. */
|
|
602
|
-
backupIf?: (currentRaw: string) => boolean;
|
|
603
|
-
/** Forwarded to atomicWriteFile: bound the live bytes inspected for `.bak` refresh. */
|
|
604
|
-
maxBackupBytes?: number;
|
|
605
|
-
}): Promise<T> {
|
|
606
|
-
const lockPath = `${opts.storePath}.lock`;
|
|
607
|
-
for (let attempt = 0; ; attempt++) {
|
|
608
|
-
try {
|
|
609
|
-
return await withFileLock(lockPath, async (token) => {
|
|
610
|
-
const current = await opts.load(token);
|
|
611
|
-
const merged = opts.mutate(current);
|
|
612
|
-
const next: T = { ...merged, sequence: current.sequence + 1 };
|
|
613
|
-
// Re-verify ownership before committing: recovery or a post-crash dual-steal could have
|
|
614
|
-
// handed the lock to another writer while we loaded/mutated — writing now would overwrite
|
|
615
|
-
// their committed entry with our stale snapshot. If we no longer own the lock, re-acquire.
|
|
616
|
-
const owner = await readLockToken(lockPath);
|
|
617
|
-
if (owner !== token) throw new LockLostError();
|
|
618
|
-
const writeOptions: AtomicWriteOptions = {};
|
|
619
|
-
if (opts.backupIf) writeOptions.backupIf = opts.backupIf;
|
|
620
|
-
if (opts.maxBackupBytes !== undefined) writeOptions.maxBackupBytes = opts.maxBackupBytes;
|
|
621
|
-
await atomicWriteFile(opts.storePath, opts.serialize(next), writeOptions);
|
|
622
|
-
return next;
|
|
623
|
-
});
|
|
624
|
-
} catch (err) {
|
|
625
|
-
if (err instanceof LockLostError && attempt < 5) continue; // re-acquire and retry
|
|
626
|
-
throw err;
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
export interface QuarantineOptions {
|
|
632
|
-
/** Existing store-lock ownership, used internally when the caller already holds the lock. */
|
|
633
|
-
lockToken?: string;
|
|
634
|
-
/** Test seam executed after the hard-link claim and before the source is removed. */
|
|
635
|
-
beforeRemove?: () => Promise<void>;
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
async function quarantineUnderLock(path: string, opts: QuarantineOptions): Promise<string | null> {
|
|
639
|
-
const lockPath = `${path}.lock`;
|
|
640
|
-
for (let n = 0; ; n++) {
|
|
641
|
-
const dest = `${path}.corrupt-${n}`;
|
|
642
|
-
let original;
|
|
643
|
-
try {
|
|
644
|
-
original = await lstat(path);
|
|
645
|
-
} catch (err) {
|
|
646
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
647
|
-
throw err;
|
|
648
|
-
}
|
|
649
|
-
try {
|
|
650
|
-
await link(path, dest);
|
|
651
|
-
} catch (err) {
|
|
652
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
653
|
-
if (code === "EEXIST") continue;
|
|
654
|
-
if (code === "ENOENT") return null; // already moved by a concurrent loader
|
|
655
|
-
if (code !== "EPERM" && code !== "ENOSYS" && code !== "EXDEV" && code !== "EMLINK") throw err;
|
|
656
|
-
// Filesystems without hard links use rename, but still revalidate the source and lock first.
|
|
657
|
-
if (opts.beforeRemove) await opts.beforeRemove();
|
|
658
|
-
const current = await lstat(path);
|
|
659
|
-
if (!sameFile(original, current) || (opts.lockToken !== undefined && (await readLockToken(lockPath)) !== opts.lockToken)) return null;
|
|
660
|
-
let claimed = false;
|
|
661
|
-
try {
|
|
662
|
-
await rename(path, dest);
|
|
663
|
-
claimed = true;
|
|
664
|
-
return dest;
|
|
665
|
-
} finally {
|
|
666
|
-
if (!claimed) await unlink(dest).catch(() => {});
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
try {
|
|
670
|
-
if (opts.beforeRemove) await opts.beforeRemove();
|
|
671
|
-
const current = await lstat(path);
|
|
672
|
-
const claim = await lstat(dest);
|
|
673
|
-
const ownsLock = opts.lockToken === undefined || (await readLockToken(lockPath)) === opts.lockToken;
|
|
674
|
-
if (!sameFile(original, current) || !sameFile(original, claim) || !ownsLock) {
|
|
675
|
-
await unlink(dest).catch(() => {});
|
|
676
|
-
return null;
|
|
677
|
-
}
|
|
678
|
-
await unlink(path);
|
|
679
|
-
return dest;
|
|
680
|
-
} catch (err) {
|
|
681
|
-
await unlink(dest).catch(() => {});
|
|
682
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
683
|
-
throw err;
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
/**
|
|
689
|
-
* Move a store that failed validation aside to `${path}.corrupt-<n>` (first free suffix, derived
|
|
690
|
-
* from disk not wall-clock so recovery is reproducible), instead of silently substituting empty.
|
|
691
|
-
* Quarantine is serialized by the same per-store lock used by updates, and the hard-link claim is
|
|
692
|
-
* revalidated before removal so a concurrent atomic replacement can never be unlinked.
|
|
693
|
-
*/
|
|
694
|
-
export async function quarantineCorrupt(path: string, reason: string, opts: QuarantineOptions = {}): Promise<string | null> {
|
|
695
|
-
void reason;
|
|
696
|
-
if (opts.lockToken !== undefined) {
|
|
697
|
-
try {
|
|
698
|
-
return await quarantineUnderLock(path, opts);
|
|
699
|
-
} catch {
|
|
700
|
-
return null;
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
try {
|
|
704
|
-
return await withFileLock(`${path}.lock`, async (token) => quarantineUnderLock(path, { ...opts, lockToken: token }));
|
|
705
|
-
} catch {
|
|
706
|
-
return null; // could not move it aside — caller degrades to empty, loudly
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
export interface JsonStoreOptions<E> {
|
|
711
|
-
version: number;
|
|
712
|
-
/** Validate one raw entry; return the typed entry, or null to drop it (schema drift). */
|
|
713
|
-
validateEntry: (raw: unknown) => E | null;
|
|
714
|
-
/** Maximum bytes read from or written to a live or backup store. Defaults to {@link DEFAULT_STORE_MAX_BYTES}. */
|
|
715
|
-
maxBytes?: number;
|
|
716
|
-
/** Maximum entries accepted from a store wrapper. Defaults to {@link DEFAULT_STORE_MAX_ENTRIES}. */
|
|
717
|
-
maxEntries?: number;
|
|
718
|
-
/** Wall clock for `updatedAt` (injectable for tests). Default Date.now. */
|
|
719
|
-
now?: () => number;
|
|
720
|
-
/** Surfacing for recovery events (quarantine). Default: none. */
|
|
721
|
-
onWarn?: (message: string) => void;
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
/**
|
|
725
|
-
* A typed, durable store of entries in one JSON file. Load degrades safely (missing → empty;
|
|
726
|
-
* torn/invalid shape → quarantine + empty; individual invalid entries → hidden and preserved).
|
|
727
|
-
* Update is serialized and atomic. The generic `E` is the entry type; the file wraps `E[]` with
|
|
728
|
-
* version and the CAS sequence.
|
|
729
|
-
*/
|
|
730
|
-
export class JsonStore<E> {
|
|
731
|
-
readonly filePath: string;
|
|
732
|
-
private readonly opts: JsonStoreOptions<E>;
|
|
733
|
-
private readonly now: () => number;
|
|
734
|
-
private readonly onWarn: (message: string) => void;
|
|
735
|
-
private readonly maxBytes: number;
|
|
736
|
-
private readonly maxEntries: number;
|
|
737
|
-
|
|
738
|
-
constructor(
|
|
739
|
-
filePath: string,
|
|
740
|
-
opts: JsonStoreOptions<E>,
|
|
741
|
-
) {
|
|
742
|
-
this.filePath = filePath;
|
|
743
|
-
this.opts = opts;
|
|
744
|
-
this.now = opts.now ?? Date.now;
|
|
745
|
-
this.onWarn = opts.onWarn ?? (() => {});
|
|
746
|
-
this.maxBytes = opts.maxBytes ?? DEFAULT_STORE_MAX_BYTES;
|
|
747
|
-
this.maxEntries = opts.maxEntries ?? DEFAULT_STORE_MAX_ENTRIES;
|
|
748
|
-
if (!Number.isSafeInteger(this.maxBytes) || this.maxBytes <= 0) throw new RangeError("mind store maxBytes must be a positive safe integer");
|
|
749
|
-
if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries <= 0) throw new RangeError("mind store maxEntries must be a positive safe integer");
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
private empty(): StoreFile<E> {
|
|
753
|
-
return { version: this.opts.version, updatedAt: new Date(this.now()).toISOString(), sequence: 0, entries: [] };
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
/** Parse + validate raw store bytes into a StoreFile, or null on unparseable JSON / wrong shape. */
|
|
757
|
-
private parseStore(raw: string): InternalStoreFile<E> | null {
|
|
758
|
-
let parsed: unknown;
|
|
759
|
-
try {
|
|
760
|
-
parsed = JSON.parse(raw);
|
|
761
|
-
} catch {
|
|
762
|
-
return null;
|
|
763
|
-
}
|
|
764
|
-
if (!parsed || typeof parsed !== "object" || !Array.isArray((parsed as { entries?: unknown }).entries)) return null;
|
|
765
|
-
const obj = parsed as Partial<StoreFile<unknown>>;
|
|
766
|
-
if (obj.version !== this.opts.version) {
|
|
767
|
-
// A well-formed envelope naming another version is a different build's store, not corruption:
|
|
768
|
-
// surface it and leave the file alone. An absent/garbage version is envelope corruption.
|
|
769
|
-
if (typeof obj.version === "number" && Number.isSafeInteger(obj.version) && obj.version > 0) throw new StoreVersionError(obj.version, this.opts.version);
|
|
770
|
-
return null;
|
|
771
|
-
}
|
|
772
|
-
if (typeof obj.updatedAt !== "string" || !Number.isFinite(Date.parse(obj.updatedAt))) return null;
|
|
773
|
-
if (typeof obj.sequence !== "number" || !Number.isSafeInteger(obj.sequence) || obj.sequence < 0) return null;
|
|
774
|
-
const rawEntries = obj.entries as unknown[];
|
|
775
|
-
if (rawEntries.length > this.maxEntries) {
|
|
776
|
-
throw new BoundedReadFailure("entries", `store file exceeds the ${this.maxEntries}-entry limit`);
|
|
777
|
-
}
|
|
778
|
-
const entries: E[] = [];
|
|
779
|
-
const invalidEntries: unknown[] = [];
|
|
780
|
-
for (const rawEntry of rawEntries) {
|
|
781
|
-
const e = this.opts.validateEntry(rawEntry);
|
|
782
|
-
if (e !== null) entries.push(e);
|
|
783
|
-
else invalidEntries.push(rawEntry);
|
|
784
|
-
}
|
|
785
|
-
const store: InternalStoreFile<E> = {
|
|
786
|
-
version: obj.version,
|
|
787
|
-
updatedAt: obj.updatedAt,
|
|
788
|
-
sequence: obj.sequence,
|
|
789
|
-
entries,
|
|
790
|
-
};
|
|
791
|
-
if (invalidEntries.length > 0) store[PRESERVED_INVALID_ENTRIES] = invalidEntries;
|
|
792
|
-
return store;
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
private async restoreLive(store: InternalStoreFile<E>): Promise<void> {
|
|
796
|
-
const invalidEntries = store[PRESERVED_INVALID_ENTRIES] ?? [];
|
|
797
|
-
const persisted = invalidEntries.length > 0 ? { ...store, entries: [...store.entries, ...invalidEntries] } : store;
|
|
798
|
-
await atomicWriteFile(this.filePath, `${JSON.stringify(persisted, null, 2)}\n`, {
|
|
799
|
-
backupIf: () => false,
|
|
800
|
-
maxBackupBytes: this.maxBytes,
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
/** A missing backup is normal; one that exists but cannot be used is not, and is never repaired or moved. */
|
|
805
|
-
private async readBak(): Promise<BackupRead<E>> {
|
|
806
|
-
try {
|
|
807
|
-
const store = this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
|
|
808
|
-
return store ? { kind: "usable", store } : { kind: "unusable", reason: "unparseable or unexpected shape" };
|
|
809
|
-
} catch (err) {
|
|
810
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { kind: "absent" };
|
|
811
|
-
return { kind: "unusable", reason: err instanceof Error ? err.message : String(err) };
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
/** Restore the last-known-good `.bak` over the live path. Only an unusable backup warns; an absent one is silent. */
|
|
816
|
-
private async recoverFromBak(reason: string): Promise<BackupRead<E>> {
|
|
817
|
-
const bak = await this.readBak();
|
|
818
|
-
if (bak.kind === "unusable") this.onWarn(`mind store: ${this.filePath}.bak rejected — ${bak.reason}`);
|
|
819
|
-
if (bak.kind !== "usable") return bak;
|
|
820
|
-
this.onWarn(`mind store: ${this.filePath} ${reason}; recovered from ${this.filePath}.bak`);
|
|
821
|
-
this.warnInvalidEntries(bak.store);
|
|
822
|
-
await this.restoreLive(bak.store);
|
|
823
|
-
return bak;
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
/** Empty stand-in for data that exists but was not read, flagged so loadChecked() reports it incomplete. */
|
|
827
|
-
private unreadEmpty(reason: string): InternalStoreFile<E> {
|
|
828
|
-
const store: InternalStoreFile<E> = this.empty();
|
|
829
|
-
store[UNREAD_REASON] = reason;
|
|
830
|
-
return store;
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
/** An unreadable live file was set aside: announce it and start empty, flagged incomplete. */
|
|
834
|
-
private startEmpty(reason: string): InternalStoreFile<E> {
|
|
835
|
-
this.onWarn(`mind store: ${this.filePath} ${reason}`);
|
|
836
|
-
return this.unreadEmpty(reason);
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
private invalidEntriesNote(store: InternalStoreFile<E>): string | null {
|
|
840
|
-
const count = store[PRESERVED_INVALID_ENTRIES]?.length ?? 0;
|
|
841
|
-
return count === 0 ? null : `contained ${count} invalid entr${count === 1 ? "y" : "ies"}; preserved raw and hidden from consumers`;
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
private warnInvalidEntries(store: InternalStoreFile<E>): void {
|
|
845
|
-
const note = this.invalidEntriesNote(store);
|
|
846
|
-
if (note !== null) this.onWarn(`mind store: ${this.filePath} ${note}`);
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
private async recoverBoundedFailure(failure: BoundedReadFailure, lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
850
|
-
if (lockToken === undefined) {
|
|
851
|
-
// Keep healthy/missing reads non-blocking. A bounded failure is re-read under the same
|
|
852
|
-
// store lock before quarantine so a writer that repaired the path wins the race safely.
|
|
853
|
-
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
854
|
-
}
|
|
855
|
-
const bak = await this.recoverFromBak(`rejected — ${failure.message}`);
|
|
856
|
-
if (bak.kind === "usable") return bak.store;
|
|
857
|
-
const quarantineOptions: QuarantineOptions = {};
|
|
858
|
-
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
859
|
-
const dest = await quarantineCorrupt(this.filePath, failure.message, quarantineOptions);
|
|
860
|
-
return this.startEmpty(`rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
private async loadInternal(lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
864
|
-
let raw: string;
|
|
865
|
-
try {
|
|
866
|
-
raw = await readTextFileBounded(this.filePath, this.maxBytes);
|
|
867
|
-
} catch (err) {
|
|
868
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
869
|
-
if (lockToken === undefined) {
|
|
870
|
-
// Missing was only an optimistic observation: a writer may repair and commit while this reader
|
|
871
|
-
// waits. Unless there is no backup at all, re-read live state under its lock before restoring.
|
|
872
|
-
if ((await this.readBak()).kind === "absent") return this.empty();
|
|
873
|
-
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
874
|
-
}
|
|
875
|
-
const bak = await this.recoverFromBak("missing");
|
|
876
|
-
if (bak.kind === "usable") return bak.store;
|
|
877
|
-
// Only an absent backup makes this tier genuinely empty. One that exists but cannot be used leaves
|
|
878
|
-
// the tier unread: the rows it holds may be exactly the ones a caller needs to see. The backup
|
|
879
|
-
// warning has already been given by recoverFromBak.
|
|
880
|
-
return bak.kind === "unusable" ? this.unreadEmpty(`has no live file and its backup ${this.filePath}.bak could not be used (${bak.reason}); the tier was not read`) : this.empty();
|
|
881
|
-
}
|
|
882
|
-
if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
|
|
883
|
-
throw err;
|
|
884
|
-
}
|
|
885
|
-
let parsed: InternalStoreFile<E> | null;
|
|
886
|
-
try {
|
|
887
|
-
parsed = this.parseStore(raw);
|
|
888
|
-
} catch (err) {
|
|
889
|
-
if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
|
|
890
|
-
throw err;
|
|
891
|
-
}
|
|
892
|
-
if (parsed) {
|
|
893
|
-
this.warnInvalidEntries(parsed);
|
|
894
|
-
return parsed;
|
|
895
|
-
}
|
|
896
|
-
if (lockToken === undefined) {
|
|
897
|
-
// The first read was only an optimistic check. Re-read while holding the update lock before
|
|
898
|
-
// deciding whether the path is still corrupt and may be quarantined.
|
|
899
|
-
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
900
|
-
}
|
|
901
|
-
// Live file is torn/invalid — roll back to the last-known-good backup before giving up.
|
|
902
|
-
const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost");
|
|
903
|
-
if (bak.kind === "usable") return bak.store;
|
|
904
|
-
const quarantineOptions: QuarantineOptions = {};
|
|
905
|
-
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
906
|
-
const dest = await quarantineCorrupt(this.filePath, "unparseable / unexpected shape", quarantineOptions);
|
|
907
|
-
return this.startEmpty(`was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
private plain(store: InternalStoreFile<E>): StoreFile<E> {
|
|
911
|
-
return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
async load(): Promise<StoreFile<E>> {
|
|
915
|
-
return this.plain(await this.loadInternal());
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
/**
|
|
919
|
-
* The same tolerant read as {@link load}, plus whether it saw every row. A missing file with no backup is
|
|
920
|
-
* complete, and so is a restore from a valid backup. Rows hidden as invalid, a quarantine that started the
|
|
921
|
-
* store empty, or a backup that exists but could not be used while the live file is absent are not. A foreign
|
|
922
|
-
* version or an I/O error on the live file still throws, exactly as it does for `load`.
|
|
923
|
-
*/
|
|
924
|
-
async loadChecked(): Promise<StoreRead<E>> {
|
|
925
|
-
const store = await this.loadInternal();
|
|
926
|
-
const reasons = [store[UNREAD_REASON], this.invalidEntriesNote(store)].filter((reason): reason is string => typeof reason === "string");
|
|
927
|
-
return { file: this.plain(store), complete: reasons.length === 0, reasons };
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
/** Read without recovery, quarantine, warnings or writes; invalid rows make editing unsafe. */
|
|
931
|
-
async inspectStrict(): Promise<StoreSnapshot<E>> {
|
|
932
|
-
let raw: string | undefined;
|
|
933
|
-
try {
|
|
934
|
-
raw = await readTextFileBounded(this.filePath, this.maxBytes);
|
|
935
|
-
} catch (err) {
|
|
936
|
-
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
937
|
-
try {
|
|
938
|
-
await lstat(`${this.filePath}.bak`);
|
|
939
|
-
throw new Error("memory store is missing with a recoverable backup; repair before optimizing");
|
|
940
|
-
} catch (backupError) {
|
|
941
|
-
if ((backupError as NodeJS.ErrnoException).code !== "ENOENT") throw backupError;
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
const store: InternalStoreFile<E> | null = raw === undefined ? this.empty() : this.parseStore(raw);
|
|
945
|
-
if (!store || (store[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) {
|
|
946
|
-
throw new Error("memory store is corrupt or contains invalid entries; repair before optimizing");
|
|
947
|
-
}
|
|
948
|
-
const fingerprint = createHash("sha256").update(JSON.stringify([this.filePath, raw ?? null])).digest("hex");
|
|
949
|
-
return { store: { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] }, fingerprint };
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
/** Strict one-file CAS. A stale preview and a no-op leave live bytes and backups untouched. */
|
|
953
|
-
async compareAndUpdate(fingerprint: string, mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
|
|
954
|
-
return withFileLock(`${this.filePath}.lock`, async (token) => {
|
|
955
|
-
const current = await this.inspectStrict();
|
|
956
|
-
if (current.fingerprint !== fingerprint) throw new StoreConflictError();
|
|
957
|
-
const previousEntries = JSON.stringify(current.store.entries);
|
|
958
|
-
const entries = mutate(current.store.entries);
|
|
959
|
-
if (JSON.stringify(entries) === previousEntries) return current.store;
|
|
960
|
-
if (!Number.isSafeInteger(current.store.sequence + 1)) throw new Error("memory store sequence exhausted");
|
|
961
|
-
const next = { ...current.store, entries, sequence: current.store.sequence + 1, updatedAt: new Date(this.now()).toISOString() };
|
|
962
|
-
const serialized = this.serializeStore(next);
|
|
963
|
-
const validated = this.parseStore(serialized);
|
|
964
|
-
if (!validated || (validated[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) throw new Error("invalid memory store update");
|
|
965
|
-
if ((await readLockToken(`${this.filePath}.lock`)) !== token) throw new StoreConflictError();
|
|
966
|
-
await atomicWriteFile(this.filePath, serialized, { backupIf: () => true, maxBackupBytes: this.maxBytes });
|
|
967
|
-
return next;
|
|
968
|
-
});
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
private serializeStore(next: InternalStoreFile<E>): string {
|
|
972
|
-
const invalidEntries = next[PRESERVED_INVALID_ENTRIES] ?? [];
|
|
973
|
-
const count = next.entries.length + invalidEntries.length;
|
|
974
|
-
if (count > this.maxEntries) throw new StoreCapacityError("entries", count, this.maxEntries);
|
|
975
|
-
const persisted = invalidEntries.length > 0 ? { ...next, entries: [...next.entries, ...invalidEntries] } : next;
|
|
976
|
-
const serialized = `${JSON.stringify(persisted, null, 2)}\n`;
|
|
977
|
-
const bytes = Buffer.byteLength(serialized, "utf8");
|
|
978
|
-
if (bytes > this.maxBytes) throw new StoreCapacityError("bytes", bytes, this.maxBytes);
|
|
979
|
-
return serialized;
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
/** Atomically apply `mutate` to the current entries and persist. Returns the committed store. */
|
|
983
|
-
async update(mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
|
|
984
|
-
const next = await casUpdate<InternalStoreFile<E>>({
|
|
985
|
-
storePath: this.filePath,
|
|
986
|
-
load: (token) => this.loadInternal(token),
|
|
987
|
-
mutate: (current) => ({ ...current, updatedAt: new Date(this.now()).toISOString(), entries: mutate(current.entries) }),
|
|
988
|
-
serialize: (next) => this.serializeStore(next),
|
|
989
|
-
// Only refresh the .bak from a live file that still parses — never let a torn file we just
|
|
990
|
-
// recovered from .bak overwrite that good backup.
|
|
991
|
-
backupIf: (raw) => {
|
|
992
|
-
try {
|
|
993
|
-
return this.parseStore(raw) !== null;
|
|
994
|
-
} catch {
|
|
995
|
-
return false;
|
|
996
|
-
}
|
|
997
|
-
},
|
|
998
|
-
maxBackupBytes: this.maxBytes,
|
|
999
|
-
});
|
|
1000
|
-
return { version: next.version, updatedAt: next.updatedAt, sequence: next.sequence, entries: [...next.entries] };
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Durable, cross-OS, concurrency-safe JSON persistence for pi-persona-mind's stores.
|
|
3
|
+
*
|
|
4
|
+
* A store is one JSON file rewritten in full. Without care, a crash mid-write leaves a torn
|
|
5
|
+
* file that loads as a silent empty store (memory vanishes with no signal), and two writers
|
|
6
|
+
* race with last-writer-wins. These primitives prevent both, using only the Node stdlib — no
|
|
7
|
+
* native binding, no `flock`/`lockf` (so it works on Windows, unlike the POSIX-lock stores in
|
|
8
|
+
* the Pi memory ecosystem):
|
|
9
|
+
*
|
|
10
|
+
* 1. {@link atomicWriteFile} — temp-in-same-dir → fsync → atomic rename. A crash before the
|
|
11
|
+
* rename leaves the prior file intact; never a partially-written store.
|
|
12
|
+
* 2. {@link casUpdate} — the load→mutate→write runs inside a per-file advisory lockfile
|
|
13
|
+
* (`wx`/O_EXCL create, polled, with dead-local recovery for a crashed holder and an ownership
|
|
14
|
+
* token so a stolen hold is never wrongly released). No committed write is lost.
|
|
15
|
+
* 3. {@link quarantineCorrupt} — a file that fails validation is moved aside to `*.corrupt-N`
|
|
16
|
+
* (never silently replaced with empty, which would present absence as current fact).
|
|
17
|
+
*
|
|
18
|
+
* The pattern is adapted from OpenLore's `atomic-store.ts` (clay-good/openlore, MIT).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { constants as fsConstants } from "node:fs";
|
|
22
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
23
|
+
import { copyFile, link, lstat, mkdir, open, rename, rmdir, unlink } from "node:fs/promises";
|
|
24
|
+
import { hostname } from "node:os";
|
|
25
|
+
import { performance } from "node:perf_hooks";
|
|
26
|
+
import { basename, dirname, join } from "node:path";
|
|
27
|
+
|
|
28
|
+
/** Every persisted store carries the monotonic compare-and-swap counter. */
|
|
29
|
+
export interface StoreFile<E> {
|
|
30
|
+
version: number;
|
|
31
|
+
updatedAt: string;
|
|
32
|
+
/** Monotonic write counter: orders writes and lets an external reader detect change. */
|
|
33
|
+
sequence: number;
|
|
34
|
+
entries: E[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A tolerant read together with whether it saw every row. `complete` is false when the result may be
|
|
39
|
+
* missing rows that exist on disk: rows hidden as invalid, a file quarantined to start empty, or an
|
|
40
|
+
* existing backup that could not be used while the live file is absent. `reasons` says why.
|
|
41
|
+
*/
|
|
42
|
+
export interface StoreRead<E> {
|
|
43
|
+
file: StoreFile<E>;
|
|
44
|
+
complete: boolean;
|
|
45
|
+
reasons: string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface StoreSnapshot<E> {
|
|
49
|
+
store: StoreFile<E>;
|
|
50
|
+
/** Binds the exact live bytes and store path, including same-sequence replacements. */
|
|
51
|
+
fingerprint: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class StoreConflictError extends Error {
|
|
55
|
+
constructor() { super("memory store changed since preview; inspect and preview again"); this.name = "StoreConflictError"; }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Defensive defaults for out-of-band/corrupt stores. Normal stores are far smaller than these. */
|
|
59
|
+
export const DEFAULT_STORE_MAX_BYTES = 4 * 1024 * 1024;
|
|
60
|
+
export const DEFAULT_STORE_MAX_ENTRIES = 10_000;
|
|
61
|
+
|
|
62
|
+
// Lock tokens are process-local sequence values. Temp names use cryptographic randomness and are
|
|
63
|
+
// still opened with O_EXCL so a pre-created symlink can never be followed by a writer.
|
|
64
|
+
let lockSeq = 0;
|
|
65
|
+
|
|
66
|
+
// Invalid raw entries are retained only inside an update's private state. They are never returned by
|
|
67
|
+
// JsonStore.load(), but the next atomic rewrite can put them back verbatim instead of silently
|
|
68
|
+
// erasing data that the current validator does not understand yet.
|
|
69
|
+
const PRESERVED_INVALID_ENTRIES: unique symbol = Symbol("preservedInvalidEntries");
|
|
70
|
+
// Set on an empty store that stands in for data which exists but could not be read, so loadChecked()
|
|
71
|
+
// can tell it from a store that is genuinely empty. Never persisted.
|
|
72
|
+
const UNREAD_REASON: unique symbol = Symbol("unreadReason");
|
|
73
|
+
type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[]; [UNREAD_REASON]?: string };
|
|
74
|
+
|
|
75
|
+
/** What the `.bak` sidecar offers: nothing, a valid store, or a file that exists but cannot be used. */
|
|
76
|
+
type BackupRead<E> = { kind: "absent" } | { kind: "usable"; store: InternalStoreFile<E> } | { kind: "unusable"; reason: string };
|
|
77
|
+
|
|
78
|
+
export interface AtomicWriteOptions {
|
|
79
|
+
/** Refresh the `.bak` sidecar from the current live file only when this returns true for its
|
|
80
|
+
* bytes. Guards against copying a torn file — one that load() just recovered FROM `.bak` — over
|
|
81
|
+
* the only good backup, which would destroy the sole recoverable copy. Absent ⇒ always refresh. */
|
|
82
|
+
backupIf?: (currentRaw: string) => boolean;
|
|
83
|
+
/** Maximum live-file bytes read when evaluating `backupIf`; oversized files are not backed up. */
|
|
84
|
+
maxBackupBytes?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type BoundedReadFailureKind = "bytes" | "entries" | "path";
|
|
88
|
+
|
|
89
|
+
export class BoundedReadFailure extends Error {
|
|
90
|
+
readonly kind: BoundedReadFailureKind;
|
|
91
|
+
|
|
92
|
+
constructor(kind: BoundedReadFailureKind, message: string) {
|
|
93
|
+
super(message);
|
|
94
|
+
this.kind = kind;
|
|
95
|
+
this.name = "BoundedReadFailure";
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Thrown when a store envelope carries a version this build does not implement. It is deliberately
|
|
101
|
+
* NOT a corruption signal: a store written by another version is intact, just unreadable here, so it
|
|
102
|
+
* must be left in place (never quarantined, never overwritten) until a build that understands it —
|
|
103
|
+
* or a migration — runs. Failing loudly is the only non-destructive answer available.
|
|
104
|
+
*/
|
|
105
|
+
export class StoreVersionError extends Error {
|
|
106
|
+
readonly found: number;
|
|
107
|
+
readonly expected: number;
|
|
108
|
+
|
|
109
|
+
constructor(found: number, expected: number) {
|
|
110
|
+
super(`mind store version ${found} was written by a different pi-persona-mind build (this one reads version ${expected}); the file is left untouched`);
|
|
111
|
+
this.found = found;
|
|
112
|
+
this.expected = expected;
|
|
113
|
+
this.name = "StoreVersionError";
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Thrown before an update writes a store that the next bounded load would reject. */
|
|
118
|
+
export class StoreCapacityError extends Error {
|
|
119
|
+
readonly kind: "bytes" | "entries";
|
|
120
|
+
readonly actual: number;
|
|
121
|
+
readonly limit: number;
|
|
122
|
+
|
|
123
|
+
constructor(kind: "bytes" | "entries", actual: number, limit: number) {
|
|
124
|
+
super(`mind store capacity: ${kind} ${actual} exceeds limit ${limit}`);
|
|
125
|
+
this.kind = kind;
|
|
126
|
+
this.actual = actual;
|
|
127
|
+
this.limit = limit;
|
|
128
|
+
this.name = "StoreCapacityError";
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const noFollow = (fsConstants as { O_NOFOLLOW?: number }).O_NOFOLLOW;
|
|
133
|
+
const readFlags: string | number = noFollow === undefined ? "r" : fsConstants.O_RDONLY | noFollow;
|
|
134
|
+
|
|
135
|
+
function sameFile(a: { dev: number; ino: number }, b: { dev: number; ino: number }): boolean {
|
|
136
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const LOCK_POLL_MS = 25;
|
|
140
|
+
const LOCK_MAX_WAIT_MS = 30_000;
|
|
141
|
+
const REPLACE_MAX_WAIT_MS = 30_000;
|
|
142
|
+
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
|
143
|
+
|
|
144
|
+
type LockStats = { dev: number; ino: number };
|
|
145
|
+
|
|
146
|
+
export interface FileLockOptions {
|
|
147
|
+
/** Internal seam used to prove cleanup when closing a newly-created lock handle fails. */
|
|
148
|
+
close?: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function unlinkIfSameFile(path: string, expected: LockStats): Promise<void> {
|
|
152
|
+
try {
|
|
153
|
+
const current = await lstat(path);
|
|
154
|
+
if (sameFile(expected, current)) await unlink(path).catch(() => {});
|
|
155
|
+
} catch {
|
|
156
|
+
/* the failed acquisition may already have been cleaned up */
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Create a lockfile and clean up its inode if writing or closing the handle fails. */
|
|
161
|
+
async function createLockFile(
|
|
162
|
+
lockPath: string,
|
|
163
|
+
token: string,
|
|
164
|
+
closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void> = (handle) => handle.close(),
|
|
165
|
+
): Promise<void> {
|
|
166
|
+
const fh = await open(lockPath, "wx");
|
|
167
|
+
let created: LockStats | undefined;
|
|
168
|
+
try {
|
|
169
|
+
created = await fh.stat();
|
|
170
|
+
await fh.writeFile(token);
|
|
171
|
+
await closeHandle(fh);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
// A failed write can leave an empty/partial lock that no waiter can safely attribute. Close
|
|
174
|
+
// the descriptor when possible, then remove only the inode this acquisition created.
|
|
175
|
+
await fh.close().catch(() => {});
|
|
176
|
+
if (created) await unlinkIfSameFile(lockPath, created);
|
|
177
|
+
throw err;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Read at most one byte beyond the fstat-observed size, rejecting symlinks, replacements, and floods. */
|
|
182
|
+
export async function readTextFileBounded(path: string, maxBytes: number): Promise<string> {
|
|
183
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("store maxBytes must be a positive safe integer");
|
|
184
|
+
let listed;
|
|
185
|
+
try {
|
|
186
|
+
listed = await lstat(path);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
if (listed.isSymbolicLink()) throw new BoundedReadFailure("path", "store path is a symbolic link");
|
|
191
|
+
if (!listed.isFile()) throw new BoundedReadFailure("path", "store path is not a regular file");
|
|
192
|
+
|
|
193
|
+
let fh;
|
|
194
|
+
try {
|
|
195
|
+
fh = await open(path, readFlags);
|
|
196
|
+
} catch (err) {
|
|
197
|
+
if ((err as NodeJS.ErrnoException).code === "ELOOP") {
|
|
198
|
+
throw new BoundedReadFailure("path", "store path is a symbolic link");
|
|
199
|
+
}
|
|
200
|
+
throw err;
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
const opened = await fh.stat();
|
|
204
|
+
if (!opened.isFile() || !sameFile(listed, opened)) {
|
|
205
|
+
throw new BoundedReadFailure("path", "store path changed or is not a regular file");
|
|
206
|
+
}
|
|
207
|
+
const observedSize = opened.size;
|
|
208
|
+
if (!Number.isSafeInteger(observedSize) || observedSize > maxBytes) {
|
|
209
|
+
throw new BoundedReadFailure("bytes", `store file exceeds the ${maxBytes}-byte limit`);
|
|
210
|
+
}
|
|
211
|
+
const bytes = Buffer.allocUnsafe(observedSize + 1);
|
|
212
|
+
let offset = 0;
|
|
213
|
+
while (offset < bytes.length) {
|
|
214
|
+
const result = await fh.read(bytes, offset, bytes.length - offset, offset);
|
|
215
|
+
if (result.bytesRead === 0) break;
|
|
216
|
+
offset += result.bytesRead;
|
|
217
|
+
}
|
|
218
|
+
if (offset > observedSize) throw new BoundedReadFailure("bytes", "store file grew while it was being read");
|
|
219
|
+
const finalOpened = await fh.stat();
|
|
220
|
+
if (!finalOpened.isFile() || !sameFile(opened, finalOpened) || finalOpened.size !== observedSize || offset !== observedSize) {
|
|
221
|
+
throw new BoundedReadFailure("path", "store file changed or was truncated while it was being read");
|
|
222
|
+
}
|
|
223
|
+
const current = await lstat(path);
|
|
224
|
+
if (current.isSymbolicLink() || !current.isFile() || !sameFile(opened, current) || current.size !== observedSize) {
|
|
225
|
+
throw new BoundedReadFailure("path", "store path changed while it was being read");
|
|
226
|
+
}
|
|
227
|
+
return bytes.subarray(0, offset).toString("utf8");
|
|
228
|
+
} finally {
|
|
229
|
+
await fh.close();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const MAX_LOCK_TOKEN_BYTES = 1024;
|
|
234
|
+
|
|
235
|
+
async function openRandomTemp(dir: string, base: string): Promise<{ path: string; handle: Awaited<ReturnType<typeof open>> }> {
|
|
236
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
237
|
+
const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
|
|
238
|
+
try {
|
|
239
|
+
return { path, handle: await open(path, "wx") };
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
throw new Error(`mind store: could not allocate a unique temporary file beside ${base}`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function copyToRandomTemp(source: string, dir: string, base: string): Promise<string> {
|
|
248
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
249
|
+
const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
|
|
250
|
+
try {
|
|
251
|
+
await copyFile(source, path, fsConstants.COPYFILE_EXCL);
|
|
252
|
+
return path;
|
|
253
|
+
} catch (err) {
|
|
254
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
throw new Error(`mind store: could not allocate a unique backup temporary file beside ${base}`);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Replace a destination path without ever opening/following an existing destination symlink. */
|
|
261
|
+
async function replacePath(staged: string, destination: string): Promise<void> {
|
|
262
|
+
const started = performance.now();
|
|
263
|
+
try {
|
|
264
|
+
await rename(staged, destination);
|
|
265
|
+
return;
|
|
266
|
+
} catch (err) {
|
|
267
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
268
|
+
if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
|
|
269
|
+
}
|
|
270
|
+
// Windows may reject rename over a live destination while another process still has an open
|
|
271
|
+
// handle. Keep the staged bytes in place and retry the remove/rename sequence until that handle
|
|
272
|
+
// closes. The destination identity is checked before unlinking so a concurrent replacement is
|
|
273
|
+
// never removed by a stale retry.
|
|
274
|
+
for (;;) {
|
|
275
|
+
let observed;
|
|
276
|
+
try {
|
|
277
|
+
observed = await lstat(destination);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
280
|
+
}
|
|
281
|
+
if (observed) {
|
|
282
|
+
let current;
|
|
283
|
+
try {
|
|
284
|
+
current = await lstat(destination);
|
|
285
|
+
} catch (err) {
|
|
286
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
287
|
+
throw err;
|
|
288
|
+
}
|
|
289
|
+
if (!sameFile(observed, current)) continue;
|
|
290
|
+
try {
|
|
291
|
+
await unlink(destination);
|
|
292
|
+
} catch (err) {
|
|
293
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
294
|
+
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
|
|
295
|
+
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
296
|
+
await sleep(LOCK_POLL_MS);
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
await rename(staged, destination);
|
|
302
|
+
return;
|
|
303
|
+
} catch (err) {
|
|
304
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
305
|
+
if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
|
|
306
|
+
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
307
|
+
await sleep(LOCK_POLL_MS);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Replace the live store atomically. Windows rejects rename-over-destination while a reader still
|
|
314
|
+
* holds the destination open; retry the SAME rename (without unlinking the committed file) until
|
|
315
|
+
* that short-lived reader closes. The old or new file is therefore always present.
|
|
316
|
+
*/
|
|
317
|
+
async function replaceLivePath(staged: string, destination: string): Promise<void> {
|
|
318
|
+
const started = performance.now();
|
|
319
|
+
for (;;) {
|
|
320
|
+
try {
|
|
321
|
+
await rename(staged, destination);
|
|
322
|
+
return;
|
|
323
|
+
} catch (err) {
|
|
324
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
325
|
+
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
|
|
326
|
+
if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
|
|
327
|
+
await sleep(LOCK_POLL_MS);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function refreshBackup(source: string, destination: string): Promise<void> {
|
|
333
|
+
const listed = await lstat(source);
|
|
334
|
+
if (!listed.isFile()) return;
|
|
335
|
+
const staged = await copyToRandomTemp(source, dirname(destination), basename(destination));
|
|
336
|
+
let replaced = false;
|
|
337
|
+
try {
|
|
338
|
+
const current = await lstat(source);
|
|
339
|
+
if (!current.isFile() || !sameFile(listed, current)) return;
|
|
340
|
+
await replacePath(staged, destination);
|
|
341
|
+
replaced = true;
|
|
342
|
+
} finally {
|
|
343
|
+
if (!replaced) await unlink(staged).catch(() => {});
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Lock metadata is trusted only when it is a tiny regular file; never read an attacker-sized token. */
|
|
348
|
+
async function readLockToken(lockPath: string): Promise<string | null> {
|
|
349
|
+
let listed;
|
|
350
|
+
try {
|
|
351
|
+
listed = await lstat(lockPath);
|
|
352
|
+
if (!listed.isFile()) return null;
|
|
353
|
+
const fh = await open(lockPath, readFlags);
|
|
354
|
+
try {
|
|
355
|
+
const opened = await fh.stat();
|
|
356
|
+
if (!opened.isFile() || !sameFile(listed, opened) || opened.size > MAX_LOCK_TOKEN_BYTES) return null;
|
|
357
|
+
const bytes = Buffer.alloc(MAX_LOCK_TOKEN_BYTES);
|
|
358
|
+
const result = await fh.read(bytes, 0, MAX_LOCK_TOKEN_BYTES, 0);
|
|
359
|
+
if (result.bytesRead !== opened.size) return null;
|
|
360
|
+
const current = await lstat(lockPath);
|
|
361
|
+
if (!current.isFile() || !sameFile(opened, current) || current.size !== opened.size) return null;
|
|
362
|
+
return bytes.subarray(0, result.bytesRead).toString("utf8");
|
|
363
|
+
} finally {
|
|
364
|
+
await fh.close();
|
|
365
|
+
}
|
|
366
|
+
} catch {
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Write `data` to `path` atomically: to a sibling temp file, flushed to disk (`fsync`), then
|
|
373
|
+
* moved into place with a single atomic `rename`. A crash before the rename leaves the previous
|
|
374
|
+
* file untouched. The directory fsync is best-effort — Windows rejects it, and the data fsync
|
|
375
|
+
* already bounds the loss.
|
|
376
|
+
*/
|
|
377
|
+
export async function atomicWriteFile(path: string, data: string, opts: AtomicWriteOptions = {}): Promise<void> {
|
|
378
|
+
const dir = dirname(path);
|
|
379
|
+
await mkdir(dir, { recursive: true });
|
|
380
|
+
const temp = await openRandomTemp(dir, basename(path));
|
|
381
|
+
const tmp = temp.path;
|
|
382
|
+
let renamed = false;
|
|
383
|
+
try {
|
|
384
|
+
const fh = temp.handle;
|
|
385
|
+
try {
|
|
386
|
+
await fh.writeFile(data, "utf-8");
|
|
387
|
+
await fh.sync();
|
|
388
|
+
} finally {
|
|
389
|
+
await fh.close();
|
|
390
|
+
}
|
|
391
|
+
// Preserve the current (known-good) file as a last-known-good sidecar BEFORE we overwrite it,
|
|
392
|
+
// so a later torn/truncated live file can be rolled back to it (JsonStore.load consults .bak
|
|
393
|
+
// before quarantining). But never clobber a good .bak with a live file that isn't itself good
|
|
394
|
+
// (a torn file we just recovered FROM .bak): that would destroy the only recoverable copy.
|
|
395
|
+
try {
|
|
396
|
+
if (!opts.backupIf) {
|
|
397
|
+
await refreshBackup(path, `${path}.bak`);
|
|
398
|
+
} else {
|
|
399
|
+
const current = await readTextFileBounded(path, opts.maxBackupBytes ?? DEFAULT_STORE_MAX_BYTES);
|
|
400
|
+
if (opts.backupIf(current)) await refreshBackup(path, `${path}.bak`);
|
|
401
|
+
}
|
|
402
|
+
} catch {
|
|
403
|
+
/* no current file, unsafe path, or oversized current file — nothing to preserve */
|
|
404
|
+
}
|
|
405
|
+
await replaceLivePath(tmp, path);
|
|
406
|
+
renamed = true;
|
|
407
|
+
} finally {
|
|
408
|
+
if (!renamed) await unlink(tmp).catch(() => {});
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
const dh = await open(dir, "r");
|
|
412
|
+
try {
|
|
413
|
+
await dh.sync();
|
|
414
|
+
} finally {
|
|
415
|
+
await dh.close();
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
/* directory fsync unsupported (e.g. Windows) — skip */
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Dead-lock recovery is itself a critical section. The directory gate is process-wide (not merely
|
|
423
|
+
// an in-memory promise), and contenders check it before every acquisition attempt. A recovering
|
|
424
|
+
// process keeps the gate until it has installed its replacement token, so another process can never
|
|
425
|
+
// observe the old dead lock removed and enter the callback during the hand-off window.
|
|
426
|
+
const recoveryTails = new Map<string, Promise<void>>();
|
|
427
|
+
async function withRecoveryGate<T>(lockPath: string, fn: () => Promise<T>): Promise<T> {
|
|
428
|
+
const previous = recoveryTails.get(lockPath) ?? Promise.resolve();
|
|
429
|
+
let release!: () => void;
|
|
430
|
+
const current = new Promise<void>((resolve) => {
|
|
431
|
+
release = resolve;
|
|
432
|
+
});
|
|
433
|
+
recoveryTails.set(lockPath, current);
|
|
434
|
+
await previous;
|
|
435
|
+
try {
|
|
436
|
+
return await fn();
|
|
437
|
+
} finally {
|
|
438
|
+
release();
|
|
439
|
+
if (recoveryTails.get(lockPath) === current) recoveryTails.delete(lockPath);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function recoveryGatePath(lockPath: string): string {
|
|
444
|
+
return `${lockPath}.recovery`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async function recoveryGateExists(lockPath: string): Promise<boolean> {
|
|
448
|
+
try {
|
|
449
|
+
await lstat(recoveryGatePath(lockPath));
|
|
450
|
+
return true;
|
|
451
|
+
} catch (err) {
|
|
452
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
453
|
+
return true; // an unreadable gate is treated as held: fail closed, never race recovery
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Is the lock held by a LOCAL process that is already dead? The lock token is `host:pid-seq`; only
|
|
459
|
+
* when the host matches ours can we probe the pid (`process.kill(pid, 0)`: ESRCH ⇒ gone). A token
|
|
460
|
+
* from another machine (network FS) or an unparseable/legacy one returns false and is never
|
|
461
|
+
* stealable by age: without a trustworthy owner identity, time alone cannot distinguish a crashed
|
|
462
|
+
* process from a slow-but-alive one.
|
|
463
|
+
*/
|
|
464
|
+
function tokenHolderIsDeadLocal(content: string): boolean {
|
|
465
|
+
const match = /^([^:\r\n]+):([0-9]+)-([0-9]+)$/.exec(content);
|
|
466
|
+
if (!match || match[1] !== hostname()) return false;
|
|
467
|
+
const pid = Number(match[2]);
|
|
468
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(Number(match[3]))) return false;
|
|
469
|
+
try {
|
|
470
|
+
process.kill(pid, 0);
|
|
471
|
+
return false; // exists (alive)
|
|
472
|
+
} catch (err) {
|
|
473
|
+
return (err as NodeJS.ErrnoException).code === "ESRCH"; // ESRCH ⇒ dead; EPERM ⇒ alive
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Recover a dead lock while holding a cross-process gate. The replacement lock is created before
|
|
479
|
+
* the gate is released; this is the key ordering that prevents a second process from deleting a
|
|
480
|
+
* fresh lock after observing the same old dead token. A recovery process that itself crashes leaves
|
|
481
|
+
* the gate behind; waiters fail closed after the normal bounded wait instead of guessing that a
|
|
482
|
+
* potentially live recovery owner is dead.
|
|
483
|
+
*/
|
|
484
|
+
async function recoverDeadLocalLock(
|
|
485
|
+
lockPath: string,
|
|
486
|
+
token: string,
|
|
487
|
+
closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>,
|
|
488
|
+
): Promise<boolean> {
|
|
489
|
+
return withRecoveryGate(lockPath, async () => {
|
|
490
|
+
const gate = recoveryGatePath(lockPath);
|
|
491
|
+
try {
|
|
492
|
+
await mkdir(gate);
|
|
493
|
+
} catch (err) {
|
|
494
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
495
|
+
// Windows may report EPERM while a contender's removed gate is still pending
|
|
496
|
+
// deletion. We acquired nothing: retry through the caller's bounded contention
|
|
497
|
+
// wait, without removing the gate or inspecting/replacing the canonical token.
|
|
498
|
+
if (code === "EEXIST" || (process.platform === "win32" && code === "EPERM")) return false;
|
|
499
|
+
throw err;
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
const observed = await readLockToken(lockPath);
|
|
503
|
+
if (observed === null || !tokenHolderIsDeadLocal(observed)) return false;
|
|
504
|
+
// Re-read immediately before removal while every other contender is required to honor `gate`.
|
|
505
|
+
if ((await readLockToken(lockPath)) !== observed) return false;
|
|
506
|
+
await unlink(lockPath);
|
|
507
|
+
// Acquire the canonical lock before releasing the recovery gate. If this fails, the caller
|
|
508
|
+
// will continue polling; importantly, no other contender can enter during this hand-off.
|
|
509
|
+
await createLockFile(lockPath, token, closeHandle);
|
|
510
|
+
return true;
|
|
511
|
+
} finally {
|
|
512
|
+
await rmdir(gate).catch(() => {});
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Thrown internally when the commit lock was stolen mid-critical-section; {@link casUpdate} re-acquires. */
|
|
518
|
+
class LockLostError extends Error {}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Run `fn` while holding a per-file advisory lock (exclusive-create lockfile, polled, with dead-local
|
|
522
|
+
* recovery for a crashed holder). The lock carries an ownership token — passed to `fn` so it can
|
|
523
|
+
* re-verify ownership before committing — and is released only if still ours, so a hold stolen after
|
|
524
|
+
* proving its local owner is dead is never wrongly deleted. Foreign, malformed, or otherwise
|
|
525
|
+
* unprobeable locks fail closed after the bounded wait instead of being stolen by age.
|
|
526
|
+
*/
|
|
527
|
+
export async function withFileLock<T>(lockPath: string, fn: (token: string) => Promise<T>, options: FileLockOptions = {}): Promise<T> {
|
|
528
|
+
await mkdir(dirname(lockPath), { recursive: true });
|
|
529
|
+
const token = `${hostname()}:${process.pid}-${lockSeq++}`;
|
|
530
|
+
const start = performance.now();
|
|
531
|
+
const closeHandle = options.close ?? ((handle: Awaited<ReturnType<typeof open>>) => handle.close());
|
|
532
|
+
for (;;) {
|
|
533
|
+
if (await recoveryGateExists(lockPath)) {
|
|
534
|
+
if (performance.now() - start > LOCK_MAX_WAIT_MS) {
|
|
535
|
+
throw new Error(
|
|
536
|
+
`mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
|
|
537
|
+
`(recovery gate is held; retry the operation)`,
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
await sleep(LOCK_POLL_MS);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
await createLockFile(lockPath, token, closeHandle);
|
|
545
|
+
break;
|
|
546
|
+
} catch (err) {
|
|
547
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
548
|
+
if (code !== "EEXIST") {
|
|
549
|
+
// Windows can report EPERM, rather than EEXIST, when another process has the
|
|
550
|
+
// lockfile open. Treat it as contention only when the path can be observed; a
|
|
551
|
+
// genuine permission failure on an absent/inaccessible path must still surface.
|
|
552
|
+
if (code !== "EPERM") throw err;
|
|
553
|
+
try {
|
|
554
|
+
await lstat(lockPath);
|
|
555
|
+
} catch (probeErr) {
|
|
556
|
+
// On Windows an open racing with a concurrent unlink can report EPERM even
|
|
557
|
+
// though the path has already vanished. Retry the acquisition; surfacing that
|
|
558
|
+
// transient error would strand otherwise live writers.
|
|
559
|
+
if ((probeErr as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
560
|
+
throw err;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// A crashed LOCAL holder is stolen at once (no 10s wait).
|
|
564
|
+
if (await recoverDeadLocalLock(lockPath, token, closeHandle)) {
|
|
565
|
+
break;
|
|
566
|
+
}
|
|
567
|
+
// A LIVE local holder is genuinely mid-critical-section, while a foreign or malformed
|
|
568
|
+
// token is unprobeable. Never time-steal either case: age cannot prove that the owner is
|
|
569
|
+
// dead, and stealing could let both writers pass their ownership checks and lose a commit.
|
|
570
|
+
if (performance.now() - start > LOCK_MAX_WAIT_MS) {
|
|
571
|
+
throw new Error(
|
|
572
|
+
`mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
|
|
573
|
+
`(sustained write contention) — retry the operation`,
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
await sleep(LOCK_POLL_MS);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
try {
|
|
580
|
+
return await fn(token);
|
|
581
|
+
} finally {
|
|
582
|
+
try {
|
|
583
|
+
if ((await readLockToken(lockPath)) === token) await unlink(lockPath).catch(() => {});
|
|
584
|
+
} catch {
|
|
585
|
+
/* lock already gone */
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Atomically read-modify-write a sequenced JSON store. The load→mutate→write runs inside the
|
|
592
|
+
* per-store lock, so the lock (not an optimistic sequence guard) is the serialization point:
|
|
593
|
+
* `mutate` always runs against the freshest on-disk store and a competing write cannot interleave.
|
|
594
|
+
* `mutate` MUST be a pure merge over the loaded store; every writer MUST go through this function.
|
|
595
|
+
*/
|
|
596
|
+
export async function casUpdate<T extends { sequence: number }>(opts: {
|
|
597
|
+
storePath: string;
|
|
598
|
+
load: (token?: string) => Promise<T>;
|
|
599
|
+
mutate: (current: T) => T;
|
|
600
|
+
serialize: (next: T) => string;
|
|
601
|
+
/** Forwarded to atomicWriteFile: gate the `.bak` refresh on the current live file being valid. */
|
|
602
|
+
backupIf?: (currentRaw: string) => boolean;
|
|
603
|
+
/** Forwarded to atomicWriteFile: bound the live bytes inspected for `.bak` refresh. */
|
|
604
|
+
maxBackupBytes?: number;
|
|
605
|
+
}): Promise<T> {
|
|
606
|
+
const lockPath = `${opts.storePath}.lock`;
|
|
607
|
+
for (let attempt = 0; ; attempt++) {
|
|
608
|
+
try {
|
|
609
|
+
return await withFileLock(lockPath, async (token) => {
|
|
610
|
+
const current = await opts.load(token);
|
|
611
|
+
const merged = opts.mutate(current);
|
|
612
|
+
const next: T = { ...merged, sequence: current.sequence + 1 };
|
|
613
|
+
// Re-verify ownership before committing: recovery or a post-crash dual-steal could have
|
|
614
|
+
// handed the lock to another writer while we loaded/mutated — writing now would overwrite
|
|
615
|
+
// their committed entry with our stale snapshot. If we no longer own the lock, re-acquire.
|
|
616
|
+
const owner = await readLockToken(lockPath);
|
|
617
|
+
if (owner !== token) throw new LockLostError();
|
|
618
|
+
const writeOptions: AtomicWriteOptions = {};
|
|
619
|
+
if (opts.backupIf) writeOptions.backupIf = opts.backupIf;
|
|
620
|
+
if (opts.maxBackupBytes !== undefined) writeOptions.maxBackupBytes = opts.maxBackupBytes;
|
|
621
|
+
await atomicWriteFile(opts.storePath, opts.serialize(next), writeOptions);
|
|
622
|
+
return next;
|
|
623
|
+
});
|
|
624
|
+
} catch (err) {
|
|
625
|
+
if (err instanceof LockLostError && attempt < 5) continue; // re-acquire and retry
|
|
626
|
+
throw err;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export interface QuarantineOptions {
|
|
632
|
+
/** Existing store-lock ownership, used internally when the caller already holds the lock. */
|
|
633
|
+
lockToken?: string;
|
|
634
|
+
/** Test seam executed after the hard-link claim and before the source is removed. */
|
|
635
|
+
beforeRemove?: () => Promise<void>;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async function quarantineUnderLock(path: string, opts: QuarantineOptions): Promise<string | null> {
|
|
639
|
+
const lockPath = `${path}.lock`;
|
|
640
|
+
for (let n = 0; ; n++) {
|
|
641
|
+
const dest = `${path}.corrupt-${n}`;
|
|
642
|
+
let original;
|
|
643
|
+
try {
|
|
644
|
+
original = await lstat(path);
|
|
645
|
+
} catch (err) {
|
|
646
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
647
|
+
throw err;
|
|
648
|
+
}
|
|
649
|
+
try {
|
|
650
|
+
await link(path, dest);
|
|
651
|
+
} catch (err) {
|
|
652
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
653
|
+
if (code === "EEXIST") continue;
|
|
654
|
+
if (code === "ENOENT") return null; // already moved by a concurrent loader
|
|
655
|
+
if (code !== "EPERM" && code !== "ENOSYS" && code !== "EXDEV" && code !== "EMLINK") throw err;
|
|
656
|
+
// Filesystems without hard links use rename, but still revalidate the source and lock first.
|
|
657
|
+
if (opts.beforeRemove) await opts.beforeRemove();
|
|
658
|
+
const current = await lstat(path);
|
|
659
|
+
if (!sameFile(original, current) || (opts.lockToken !== undefined && (await readLockToken(lockPath)) !== opts.lockToken)) return null;
|
|
660
|
+
let claimed = false;
|
|
661
|
+
try {
|
|
662
|
+
await rename(path, dest);
|
|
663
|
+
claimed = true;
|
|
664
|
+
return dest;
|
|
665
|
+
} finally {
|
|
666
|
+
if (!claimed) await unlink(dest).catch(() => {});
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
if (opts.beforeRemove) await opts.beforeRemove();
|
|
671
|
+
const current = await lstat(path);
|
|
672
|
+
const claim = await lstat(dest);
|
|
673
|
+
const ownsLock = opts.lockToken === undefined || (await readLockToken(lockPath)) === opts.lockToken;
|
|
674
|
+
if (!sameFile(original, current) || !sameFile(original, claim) || !ownsLock) {
|
|
675
|
+
await unlink(dest).catch(() => {});
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
await unlink(path);
|
|
679
|
+
return dest;
|
|
680
|
+
} catch (err) {
|
|
681
|
+
await unlink(dest).catch(() => {});
|
|
682
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
683
|
+
throw err;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Move a store that failed validation aside to `${path}.corrupt-<n>` (first free suffix, derived
|
|
690
|
+
* from disk not wall-clock so recovery is reproducible), instead of silently substituting empty.
|
|
691
|
+
* Quarantine is serialized by the same per-store lock used by updates, and the hard-link claim is
|
|
692
|
+
* revalidated before removal so a concurrent atomic replacement can never be unlinked.
|
|
693
|
+
*/
|
|
694
|
+
export async function quarantineCorrupt(path: string, reason: string, opts: QuarantineOptions = {}): Promise<string | null> {
|
|
695
|
+
void reason;
|
|
696
|
+
if (opts.lockToken !== undefined) {
|
|
697
|
+
try {
|
|
698
|
+
return await quarantineUnderLock(path, opts);
|
|
699
|
+
} catch {
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
try {
|
|
704
|
+
return await withFileLock(`${path}.lock`, async (token) => quarantineUnderLock(path, { ...opts, lockToken: token }));
|
|
705
|
+
} catch {
|
|
706
|
+
return null; // could not move it aside — caller degrades to empty, loudly
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
export interface JsonStoreOptions<E> {
|
|
711
|
+
version: number;
|
|
712
|
+
/** Validate one raw entry; return the typed entry, or null to drop it (schema drift). */
|
|
713
|
+
validateEntry: (raw: unknown) => E | null;
|
|
714
|
+
/** Maximum bytes read from or written to a live or backup store. Defaults to {@link DEFAULT_STORE_MAX_BYTES}. */
|
|
715
|
+
maxBytes?: number;
|
|
716
|
+
/** Maximum entries accepted from a store wrapper. Defaults to {@link DEFAULT_STORE_MAX_ENTRIES}. */
|
|
717
|
+
maxEntries?: number;
|
|
718
|
+
/** Wall clock for `updatedAt` (injectable for tests). Default Date.now. */
|
|
719
|
+
now?: () => number;
|
|
720
|
+
/** Surfacing for recovery events (quarantine). Default: none. */
|
|
721
|
+
onWarn?: (message: string) => void;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* A typed, durable store of entries in one JSON file. Load degrades safely (missing → empty;
|
|
726
|
+
* torn/invalid shape → quarantine + empty; individual invalid entries → hidden and preserved).
|
|
727
|
+
* Update is serialized and atomic. The generic `E` is the entry type; the file wraps `E[]` with
|
|
728
|
+
* version and the CAS sequence.
|
|
729
|
+
*/
|
|
730
|
+
export class JsonStore<E> {
|
|
731
|
+
readonly filePath: string;
|
|
732
|
+
private readonly opts: JsonStoreOptions<E>;
|
|
733
|
+
private readonly now: () => number;
|
|
734
|
+
private readonly onWarn: (message: string) => void;
|
|
735
|
+
private readonly maxBytes: number;
|
|
736
|
+
private readonly maxEntries: number;
|
|
737
|
+
|
|
738
|
+
constructor(
|
|
739
|
+
filePath: string,
|
|
740
|
+
opts: JsonStoreOptions<E>,
|
|
741
|
+
) {
|
|
742
|
+
this.filePath = filePath;
|
|
743
|
+
this.opts = opts;
|
|
744
|
+
this.now = opts.now ?? Date.now;
|
|
745
|
+
this.onWarn = opts.onWarn ?? (() => {});
|
|
746
|
+
this.maxBytes = opts.maxBytes ?? DEFAULT_STORE_MAX_BYTES;
|
|
747
|
+
this.maxEntries = opts.maxEntries ?? DEFAULT_STORE_MAX_ENTRIES;
|
|
748
|
+
if (!Number.isSafeInteger(this.maxBytes) || this.maxBytes <= 0) throw new RangeError("mind store maxBytes must be a positive safe integer");
|
|
749
|
+
if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries <= 0) throw new RangeError("mind store maxEntries must be a positive safe integer");
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
private empty(): StoreFile<E> {
|
|
753
|
+
return { version: this.opts.version, updatedAt: new Date(this.now()).toISOString(), sequence: 0, entries: [] };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Parse + validate raw store bytes into a StoreFile, or null on unparseable JSON / wrong shape. */
|
|
757
|
+
private parseStore(raw: string): InternalStoreFile<E> | null {
|
|
758
|
+
let parsed: unknown;
|
|
759
|
+
try {
|
|
760
|
+
parsed = JSON.parse(raw);
|
|
761
|
+
} catch {
|
|
762
|
+
return null;
|
|
763
|
+
}
|
|
764
|
+
if (!parsed || typeof parsed !== "object" || !Array.isArray((parsed as { entries?: unknown }).entries)) return null;
|
|
765
|
+
const obj = parsed as Partial<StoreFile<unknown>>;
|
|
766
|
+
if (obj.version !== this.opts.version) {
|
|
767
|
+
// A well-formed envelope naming another version is a different build's store, not corruption:
|
|
768
|
+
// surface it and leave the file alone. An absent/garbage version is envelope corruption.
|
|
769
|
+
if (typeof obj.version === "number" && Number.isSafeInteger(obj.version) && obj.version > 0) throw new StoreVersionError(obj.version, this.opts.version);
|
|
770
|
+
return null;
|
|
771
|
+
}
|
|
772
|
+
if (typeof obj.updatedAt !== "string" || !Number.isFinite(Date.parse(obj.updatedAt))) return null;
|
|
773
|
+
if (typeof obj.sequence !== "number" || !Number.isSafeInteger(obj.sequence) || obj.sequence < 0) return null;
|
|
774
|
+
const rawEntries = obj.entries as unknown[];
|
|
775
|
+
if (rawEntries.length > this.maxEntries) {
|
|
776
|
+
throw new BoundedReadFailure("entries", `store file exceeds the ${this.maxEntries}-entry limit`);
|
|
777
|
+
}
|
|
778
|
+
const entries: E[] = [];
|
|
779
|
+
const invalidEntries: unknown[] = [];
|
|
780
|
+
for (const rawEntry of rawEntries) {
|
|
781
|
+
const e = this.opts.validateEntry(rawEntry);
|
|
782
|
+
if (e !== null) entries.push(e);
|
|
783
|
+
else invalidEntries.push(rawEntry);
|
|
784
|
+
}
|
|
785
|
+
const store: InternalStoreFile<E> = {
|
|
786
|
+
version: obj.version,
|
|
787
|
+
updatedAt: obj.updatedAt,
|
|
788
|
+
sequence: obj.sequence,
|
|
789
|
+
entries,
|
|
790
|
+
};
|
|
791
|
+
if (invalidEntries.length > 0) store[PRESERVED_INVALID_ENTRIES] = invalidEntries;
|
|
792
|
+
return store;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
private async restoreLive(store: InternalStoreFile<E>): Promise<void> {
|
|
796
|
+
const invalidEntries = store[PRESERVED_INVALID_ENTRIES] ?? [];
|
|
797
|
+
const persisted = invalidEntries.length > 0 ? { ...store, entries: [...store.entries, ...invalidEntries] } : store;
|
|
798
|
+
await atomicWriteFile(this.filePath, `${JSON.stringify(persisted, null, 2)}\n`, {
|
|
799
|
+
backupIf: () => false,
|
|
800
|
+
maxBackupBytes: this.maxBytes,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** A missing backup is normal; one that exists but cannot be used is not, and is never repaired or moved. */
|
|
805
|
+
private async readBak(): Promise<BackupRead<E>> {
|
|
806
|
+
try {
|
|
807
|
+
const store = this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
|
|
808
|
+
return store ? { kind: "usable", store } : { kind: "unusable", reason: "unparseable or unexpected shape" };
|
|
809
|
+
} catch (err) {
|
|
810
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { kind: "absent" };
|
|
811
|
+
return { kind: "unusable", reason: err instanceof Error ? err.message : String(err) };
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** Restore the last-known-good `.bak` over the live path. Only an unusable backup warns; an absent one is silent. */
|
|
816
|
+
private async recoverFromBak(reason: string): Promise<BackupRead<E>> {
|
|
817
|
+
const bak = await this.readBak();
|
|
818
|
+
if (bak.kind === "unusable") this.onWarn(`mind store: ${this.filePath}.bak rejected — ${bak.reason}`);
|
|
819
|
+
if (bak.kind !== "usable") return bak;
|
|
820
|
+
this.onWarn(`mind store: ${this.filePath} ${reason}; recovered from ${this.filePath}.bak`);
|
|
821
|
+
this.warnInvalidEntries(bak.store);
|
|
822
|
+
await this.restoreLive(bak.store);
|
|
823
|
+
return bak;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** Empty stand-in for data that exists but was not read, flagged so loadChecked() reports it incomplete. */
|
|
827
|
+
private unreadEmpty(reason: string): InternalStoreFile<E> {
|
|
828
|
+
const store: InternalStoreFile<E> = this.empty();
|
|
829
|
+
store[UNREAD_REASON] = reason;
|
|
830
|
+
return store;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** An unreadable live file was set aside: announce it and start empty, flagged incomplete. */
|
|
834
|
+
private startEmpty(reason: string): InternalStoreFile<E> {
|
|
835
|
+
this.onWarn(`mind store: ${this.filePath} ${reason}`);
|
|
836
|
+
return this.unreadEmpty(reason);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
private invalidEntriesNote(store: InternalStoreFile<E>): string | null {
|
|
840
|
+
const count = store[PRESERVED_INVALID_ENTRIES]?.length ?? 0;
|
|
841
|
+
return count === 0 ? null : `contained ${count} invalid entr${count === 1 ? "y" : "ies"}; preserved raw and hidden from consumers`;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
private warnInvalidEntries(store: InternalStoreFile<E>): void {
|
|
845
|
+
const note = this.invalidEntriesNote(store);
|
|
846
|
+
if (note !== null) this.onWarn(`mind store: ${this.filePath} ${note}`);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
private async recoverBoundedFailure(failure: BoundedReadFailure, lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
850
|
+
if (lockToken === undefined) {
|
|
851
|
+
// Keep healthy/missing reads non-blocking. A bounded failure is re-read under the same
|
|
852
|
+
// store lock before quarantine so a writer that repaired the path wins the race safely.
|
|
853
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
854
|
+
}
|
|
855
|
+
const bak = await this.recoverFromBak(`rejected — ${failure.message}`);
|
|
856
|
+
if (bak.kind === "usable") return bak.store;
|
|
857
|
+
const quarantineOptions: QuarantineOptions = {};
|
|
858
|
+
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
859
|
+
const dest = await quarantineCorrupt(this.filePath, failure.message, quarantineOptions);
|
|
860
|
+
return this.startEmpty(`rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
private async loadInternal(lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
864
|
+
let raw: string;
|
|
865
|
+
try {
|
|
866
|
+
raw = await readTextFileBounded(this.filePath, this.maxBytes);
|
|
867
|
+
} catch (err) {
|
|
868
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
869
|
+
if (lockToken === undefined) {
|
|
870
|
+
// Missing was only an optimistic observation: a writer may repair and commit while this reader
|
|
871
|
+
// waits. Unless there is no backup at all, re-read live state under its lock before restoring.
|
|
872
|
+
if ((await this.readBak()).kind === "absent") return this.empty();
|
|
873
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
874
|
+
}
|
|
875
|
+
const bak = await this.recoverFromBak("missing");
|
|
876
|
+
if (bak.kind === "usable") return bak.store;
|
|
877
|
+
// Only an absent backup makes this tier genuinely empty. One that exists but cannot be used leaves
|
|
878
|
+
// the tier unread: the rows it holds may be exactly the ones a caller needs to see. The backup
|
|
879
|
+
// warning has already been given by recoverFromBak.
|
|
880
|
+
return bak.kind === "unusable" ? this.unreadEmpty(`has no live file and its backup ${this.filePath}.bak could not be used (${bak.reason}); the tier was not read`) : this.empty();
|
|
881
|
+
}
|
|
882
|
+
if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
|
|
883
|
+
throw err;
|
|
884
|
+
}
|
|
885
|
+
let parsed: InternalStoreFile<E> | null;
|
|
886
|
+
try {
|
|
887
|
+
parsed = this.parseStore(raw);
|
|
888
|
+
} catch (err) {
|
|
889
|
+
if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
|
|
890
|
+
throw err;
|
|
891
|
+
}
|
|
892
|
+
if (parsed) {
|
|
893
|
+
this.warnInvalidEntries(parsed);
|
|
894
|
+
return parsed;
|
|
895
|
+
}
|
|
896
|
+
if (lockToken === undefined) {
|
|
897
|
+
// The first read was only an optimistic check. Re-read while holding the update lock before
|
|
898
|
+
// deciding whether the path is still corrupt and may be quarantined.
|
|
899
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
900
|
+
}
|
|
901
|
+
// Live file is torn/invalid — roll back to the last-known-good backup before giving up.
|
|
902
|
+
const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost");
|
|
903
|
+
if (bak.kind === "usable") return bak.store;
|
|
904
|
+
const quarantineOptions: QuarantineOptions = {};
|
|
905
|
+
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
906
|
+
const dest = await quarantineCorrupt(this.filePath, "unparseable / unexpected shape", quarantineOptions);
|
|
907
|
+
return this.startEmpty(`was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
private plain(store: InternalStoreFile<E>): StoreFile<E> {
|
|
911
|
+
return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
async load(): Promise<StoreFile<E>> {
|
|
915
|
+
return this.plain(await this.loadInternal());
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* The same tolerant read as {@link load}, plus whether it saw every row. A missing file with no backup is
|
|
920
|
+
* complete, and so is a restore from a valid backup. Rows hidden as invalid, a quarantine that started the
|
|
921
|
+
* store empty, or a backup that exists but could not be used while the live file is absent are not. A foreign
|
|
922
|
+
* version or an I/O error on the live file still throws, exactly as it does for `load`.
|
|
923
|
+
*/
|
|
924
|
+
async loadChecked(): Promise<StoreRead<E>> {
|
|
925
|
+
const store = await this.loadInternal();
|
|
926
|
+
const reasons = [store[UNREAD_REASON], this.invalidEntriesNote(store)].filter((reason): reason is string => typeof reason === "string");
|
|
927
|
+
return { file: this.plain(store), complete: reasons.length === 0, reasons };
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/** Read without recovery, quarantine, warnings or writes; invalid rows make editing unsafe. */
|
|
931
|
+
async inspectStrict(): Promise<StoreSnapshot<E>> {
|
|
932
|
+
let raw: string | undefined;
|
|
933
|
+
try {
|
|
934
|
+
raw = await readTextFileBounded(this.filePath, this.maxBytes);
|
|
935
|
+
} catch (err) {
|
|
936
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
937
|
+
try {
|
|
938
|
+
await lstat(`${this.filePath}.bak`);
|
|
939
|
+
throw new Error("memory store is missing with a recoverable backup; repair before optimizing");
|
|
940
|
+
} catch (backupError) {
|
|
941
|
+
if ((backupError as NodeJS.ErrnoException).code !== "ENOENT") throw backupError;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
const store: InternalStoreFile<E> | null = raw === undefined ? this.empty() : this.parseStore(raw);
|
|
945
|
+
if (!store || (store[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) {
|
|
946
|
+
throw new Error("memory store is corrupt or contains invalid entries; repair before optimizing");
|
|
947
|
+
}
|
|
948
|
+
const fingerprint = createHash("sha256").update(JSON.stringify([this.filePath, raw ?? null])).digest("hex");
|
|
949
|
+
return { store: { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] }, fingerprint };
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/** Strict one-file CAS. A stale preview and a no-op leave live bytes and backups untouched. */
|
|
953
|
+
async compareAndUpdate(fingerprint: string, mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
|
|
954
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => {
|
|
955
|
+
const current = await this.inspectStrict();
|
|
956
|
+
if (current.fingerprint !== fingerprint) throw new StoreConflictError();
|
|
957
|
+
const previousEntries = JSON.stringify(current.store.entries);
|
|
958
|
+
const entries = mutate(current.store.entries);
|
|
959
|
+
if (JSON.stringify(entries) === previousEntries) return current.store;
|
|
960
|
+
if (!Number.isSafeInteger(current.store.sequence + 1)) throw new Error("memory store sequence exhausted");
|
|
961
|
+
const next = { ...current.store, entries, sequence: current.store.sequence + 1, updatedAt: new Date(this.now()).toISOString() };
|
|
962
|
+
const serialized = this.serializeStore(next);
|
|
963
|
+
const validated = this.parseStore(serialized);
|
|
964
|
+
if (!validated || (validated[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) throw new Error("invalid memory store update");
|
|
965
|
+
if ((await readLockToken(`${this.filePath}.lock`)) !== token) throw new StoreConflictError();
|
|
966
|
+
await atomicWriteFile(this.filePath, serialized, { backupIf: () => true, maxBackupBytes: this.maxBytes });
|
|
967
|
+
return next;
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
private serializeStore(next: InternalStoreFile<E>): string {
|
|
972
|
+
const invalidEntries = next[PRESERVED_INVALID_ENTRIES] ?? [];
|
|
973
|
+
const count = next.entries.length + invalidEntries.length;
|
|
974
|
+
if (count > this.maxEntries) throw new StoreCapacityError("entries", count, this.maxEntries);
|
|
975
|
+
const persisted = invalidEntries.length > 0 ? { ...next, entries: [...next.entries, ...invalidEntries] } : next;
|
|
976
|
+
const serialized = `${JSON.stringify(persisted, null, 2)}\n`;
|
|
977
|
+
const bytes = Buffer.byteLength(serialized, "utf8");
|
|
978
|
+
if (bytes > this.maxBytes) throw new StoreCapacityError("bytes", bytes, this.maxBytes);
|
|
979
|
+
return serialized;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/** Atomically apply `mutate` to the current entries and persist. Returns the committed store. */
|
|
983
|
+
async update(mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
|
|
984
|
+
const next = await casUpdate<InternalStoreFile<E>>({
|
|
985
|
+
storePath: this.filePath,
|
|
986
|
+
load: (token) => this.loadInternal(token),
|
|
987
|
+
mutate: (current) => ({ ...current, updatedAt: new Date(this.now()).toISOString(), entries: mutate(current.entries) }),
|
|
988
|
+
serialize: (next) => this.serializeStore(next),
|
|
989
|
+
// Only refresh the .bak from a live file that still parses — never let a torn file we just
|
|
990
|
+
// recovered from .bak overwrite that good backup.
|
|
991
|
+
backupIf: (raw) => {
|
|
992
|
+
try {
|
|
993
|
+
return this.parseStore(raw) !== null;
|
|
994
|
+
} catch {
|
|
995
|
+
return false;
|
|
996
|
+
}
|
|
997
|
+
},
|
|
998
|
+
maxBackupBytes: this.maxBytes,
|
|
999
|
+
});
|
|
1000
|
+
return { version: next.version, updatedAt: next.updatedAt, sequence: next.sequence, entries: [...next.entries] };
|
|
1001
|
+
}
|
|
1002
|
+
}
|