@milaboratories/pl-middle-layer 1.67.6 → 1.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -2
- package/dist/middle_layer/build_stamp.cjs +34 -0
- package/dist/middle_layer/build_stamp.cjs.map +1 -0
- package/dist/middle_layer/build_stamp.js +34 -0
- package/dist/middle_layer/build_stamp.js.map +1 -0
- package/dist/middle_layer/index.d.ts +3 -2
- package/dist/middle_layer/middle_layer.cjs +48 -0
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +19 -0
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +48 -0
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/ops.cjs +8 -2
- package/dist/middle_layer/ops.cjs.map +1 -1
- package/dist/middle_layer/ops.d.ts +35 -2
- package/dist/middle_layer/ops.d.ts.map +1 -1
- package/dist/middle_layer/ops.js +8 -2
- package/dist/middle_layer/ops.js.map +1 -1
- package/dist/middle_layer/project.cjs +163 -8
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +51 -1
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +165 -11
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/middle_layer/tree_snapshot_store.cjs +283 -0
- package/dist/middle_layer/tree_snapshot_store.cjs.map +1 -0
- package/dist/middle_layer/tree_snapshot_store.d.ts +143 -0
- package/dist/middle_layer/tree_snapshot_store.d.ts.map +1 -0
- package/dist/middle_layer/tree_snapshot_store.js +280 -0
- package/dist/middle_layer/tree_snapshot_store.js.map +1 -0
- package/package.json +10 -10
- package/src/middle_layer/build_stamp.ts +36 -0
- package/src/middle_layer/index.ts +1 -0
- package/src/middle_layer/middle_layer.ts +77 -0
- package/src/middle_layer/ops.ts +46 -1
- package/src/middle_layer/project.ts +234 -14
- package/src/middle_layer/project_failsafe.test.ts +47 -0
- package/src/middle_layer/tree_snapshot_scenarios.test.ts +337 -0
- package/src/middle_layer/tree_snapshot_store.test.ts +331 -0
- package/src/middle_layer/tree_snapshot_store.ts +419 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
const require_build_stamp = require("./build_stamp.cjs");
|
|
3
|
+
let node_path = require("node:path");
|
|
4
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
5
|
+
let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
|
|
6
|
+
let node_fs_promises = require("node:fs/promises");
|
|
7
|
+
node_fs_promises = require_runtime.__toESM(node_fs_promises, 1);
|
|
8
|
+
let _milaboratories_pl_client = require("@milaboratories/pl-client");
|
|
9
|
+
let _milaboratories_pl_tree = require("@milaboratories/pl-tree");
|
|
10
|
+
let node_crypto = require("node:crypto");
|
|
11
|
+
//#region src/middle_layer/tree_snapshot_store.ts
|
|
12
|
+
function initialStat() {
|
|
13
|
+
return {
|
|
14
|
+
reads: 0,
|
|
15
|
+
hits: 0,
|
|
16
|
+
restores: 0,
|
|
17
|
+
misses: {
|
|
18
|
+
absent: 0,
|
|
19
|
+
unreadable: 0,
|
|
20
|
+
"session-rotated": 0,
|
|
21
|
+
"not-a-snapshot": 0,
|
|
22
|
+
"unknown-schema": 0,
|
|
23
|
+
truncated: 0,
|
|
24
|
+
checksum: 0,
|
|
25
|
+
malformed: 0
|
|
26
|
+
},
|
|
27
|
+
writes: 0,
|
|
28
|
+
writeFailures: 0,
|
|
29
|
+
bytesWritten: 0,
|
|
30
|
+
discarded: 0,
|
|
31
|
+
evicted: 0,
|
|
32
|
+
evictedForSize: 0,
|
|
33
|
+
bytesEvicted: 0,
|
|
34
|
+
millisReading: 0,
|
|
35
|
+
millisWriting: 0
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const FILE_PREFIX = "tree.";
|
|
39
|
+
const FILE_SUFFIX = ".plts";
|
|
40
|
+
/** Keeps a filename to characters every filesystem we target accepts. */
|
|
41
|
+
function safe(part) {
|
|
42
|
+
return part.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
43
|
+
}
|
|
44
|
+
/** Names this class writes: a finished snapshot, or the staging file of a write killed before
|
|
45
|
+
* its rename. The directory is caller-supplied and only defaults to one of ours, so nothing
|
|
46
|
+
* failing this is ever deleted, by the purge or by the startup eviction. */
|
|
47
|
+
function isOurFile(name) {
|
|
48
|
+
if (!name.startsWith(FILE_PREFIX)) return false;
|
|
49
|
+
return name.endsWith(FILE_SUFFIX) || name.includes(`${FILE_SUFFIX}.tmp.`);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Snapshots of project tree mirrors on the local filesystem.
|
|
53
|
+
*
|
|
54
|
+
* A snapshot is addressed by backend instance, authenticated user, root resource, build stamp
|
|
55
|
+
* and snapshot schema version. Everything except the root goes into the *scope*, which is
|
|
56
|
+
* fixed for the lifetime of a client; the root distinguishes one project from another, so
|
|
57
|
+
* there is one file per project per user per backend, rewritten in place.
|
|
58
|
+
*
|
|
59
|
+
* The session is deliberately not part of the key. It is witnessed inside the file and
|
|
60
|
+
* compared on read: a snapshot from an ended session is a miss, but the file is kept, because
|
|
61
|
+
* its bodies remain valid indefinitely and only its signatures have died. Deleting it would
|
|
62
|
+
* destroy the evidence a future signature refresh would repair.
|
|
63
|
+
*/
|
|
64
|
+
var TreeSnapshotStore = class TreeSnapshotStore {
|
|
65
|
+
ops;
|
|
66
|
+
scope;
|
|
67
|
+
stat = initialStat();
|
|
68
|
+
constructor(ops, scope) {
|
|
69
|
+
this.ops = ops;
|
|
70
|
+
this.scope = scope;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Builds a store for the given client, or returns undefined when nothing should be
|
|
74
|
+
* persisted for it.
|
|
75
|
+
*
|
|
76
|
+
* Returns undefined for an impersonated client: reading and writing under `asUser` would
|
|
77
|
+
* leave another user's mirror at rest under the admin's identity, usable only if the admin
|
|
78
|
+
* returned to that exact root. One condition removes both the hygiene question and the
|
|
79
|
+
* orphan one.
|
|
80
|
+
*/
|
|
81
|
+
static create(pl, ops) {
|
|
82
|
+
if (!ops.enabled) {
|
|
83
|
+
ops.logger.info("tree snapshots are disabled by configuration");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (pl.conf.asUser !== void 0) {
|
|
87
|
+
ops.logger.info("tree snapshots are disabled while the client is opened as another user");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const identity = (0, node_crypto.createHash)("sha256").update([
|
|
91
|
+
pl.conf.hostAndPort,
|
|
92
|
+
pl.serverInfo.instanceId ?? "",
|
|
93
|
+
pl.authUser ?? ""
|
|
94
|
+
].join("\0")).digest("hex").slice(0, 16);
|
|
95
|
+
return new TreeSnapshotStore(ops, `${_milaboratories_pl_tree.PERSISTED_TREE_SCHEMA_VERSION}.${safe(require_build_stamp.ML_BUILD_STAMP)}.${identity}`);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Removes this class's files from the snapshot directory. Run when snapshots are switched
|
|
99
|
+
* off, so a user who turns the kill switch off because the disk is full or unwritable
|
|
100
|
+
* actually gets the space back, rather than leaving up to the size ceiling stranded there
|
|
101
|
+
* indefinitely.
|
|
102
|
+
*
|
|
103
|
+
* Deliberately keyed on the setting rather than on "there is no store": a store is also
|
|
104
|
+
* absent for an impersonated client, and deleting there would destroy the operator's own
|
|
105
|
+
* snapshots from their ordinary sessions. Never throws.
|
|
106
|
+
*/
|
|
107
|
+
static async purge(dir, logger) {
|
|
108
|
+
try {
|
|
109
|
+
for (const name of await node_fs_promises.default.readdir(dir)) {
|
|
110
|
+
if (!isOurFile(name)) continue;
|
|
111
|
+
await node_fs_promises.default.rm(node_path.default.join(dir, name), { force: true }).catch(() => {});
|
|
112
|
+
}
|
|
113
|
+
await node_fs_promises.default.rmdir(dir).catch(() => {});
|
|
114
|
+
} catch (e) {
|
|
115
|
+
if (e?.code === "ENOENT") return;
|
|
116
|
+
logger.warn(`failed to clear the tree snapshot directory: ${e instanceof Error ? e.message : String(e)}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
getStats() {
|
|
120
|
+
return this.stat;
|
|
121
|
+
}
|
|
122
|
+
fileFor(root) {
|
|
123
|
+
const { globalId } = (0, _milaboratories_pl_client.parseSignedResourceId)(root);
|
|
124
|
+
return node_path.default.join(this.ops.dir, `${FILE_PREFIX}${this.scope}.${globalId}${FILE_SUFFIX}`);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Reads the snapshot for a project root, or reports why there is nothing to restore.
|
|
128
|
+
*
|
|
129
|
+
* `root` is the id as resolved in the current session. Its signature is what the stored
|
|
130
|
+
* witness is compared against, so a rotated session is detected without inflating the
|
|
131
|
+
* payload, and no separate session lookup is needed anywhere.
|
|
132
|
+
*/
|
|
133
|
+
async read(root) {
|
|
134
|
+
const started = Date.now();
|
|
135
|
+
this.stat.reads++;
|
|
136
|
+
try {
|
|
137
|
+
const file = this.fileFor(root);
|
|
138
|
+
let bytes;
|
|
139
|
+
try {
|
|
140
|
+
bytes = await node_fs_promises.default.readFile(file);
|
|
141
|
+
} catch (e) {
|
|
142
|
+
const absent = e?.code === "ENOENT";
|
|
143
|
+
if (!absent) this.ops.logger.warn(`tree snapshot exists but could not be read: ${e instanceof Error ? e.message : String(e)}`);
|
|
144
|
+
return this.miss(absent ? "absent" : "unreadable");
|
|
145
|
+
}
|
|
146
|
+
const header = (0, _milaboratories_pl_tree.readPersistedTreeHeader)(bytes);
|
|
147
|
+
if (!header.ok) return this.miss(header.reason);
|
|
148
|
+
const { signature } = (0, _milaboratories_pl_client.parseSignedResourceId)(root);
|
|
149
|
+
if (!Buffer.from(header.value.witness).equals(Buffer.from(signature))) return this.miss("session-rotated");
|
|
150
|
+
const decoded = await (0, _milaboratories_pl_tree.decodePersistedTree)(bytes);
|
|
151
|
+
if (!decoded.ok) return this.miss(decoded.reason);
|
|
152
|
+
const now = /* @__PURE__ */ new Date();
|
|
153
|
+
await node_fs_promises.default.utimes(file, now, now).catch(() => {});
|
|
154
|
+
this.stat.hits++;
|
|
155
|
+
return {
|
|
156
|
+
ok: true,
|
|
157
|
+
tree: decoded.value
|
|
158
|
+
};
|
|
159
|
+
} finally {
|
|
160
|
+
this.stat.millisReading += Date.now() - started;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
miss(miss) {
|
|
164
|
+
this.stat.misses[miss]++;
|
|
165
|
+
return {
|
|
166
|
+
ok: false,
|
|
167
|
+
miss
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/** Recorded by the caller once it knows the tree accepted the snapshot. The store cannot
|
|
171
|
+
* tell on its own: it hands over bytes, and whether they become a tree is the tree's call. */
|
|
172
|
+
noteRestored() {
|
|
173
|
+
this.stat.restores++;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Writes a snapshot, replacing any previous one for the same project.
|
|
177
|
+
*
|
|
178
|
+
* Never throws and never rejects: a write is an optimisation, and a full disk or a
|
|
179
|
+
* permissions problem must not fail the operation that triggered it. Staged and renamed
|
|
180
|
+
* into place, so a process killed mid-write leaves the previous snapshot rather than a torn
|
|
181
|
+
* one.
|
|
182
|
+
*/
|
|
183
|
+
async write(root, snapshot, ops = {}) {
|
|
184
|
+
const started = Date.now();
|
|
185
|
+
try {
|
|
186
|
+
const bytes = await (0, _milaboratories_pl_tree.encodePersistedTree)(snapshot, { compress: ops.compress });
|
|
187
|
+
await (0, _milaboratories_ts_helpers.ensureDirExists)(this.ops.dir);
|
|
188
|
+
const file = this.fileFor(root);
|
|
189
|
+
await (0, _milaboratories_ts_helpers.createPathAtomically)(this.ops.logger, file, async (tempPath) => {
|
|
190
|
+
await node_fs_promises.default.writeFile(tempPath, bytes, { flag: "wx" });
|
|
191
|
+
});
|
|
192
|
+
this.stat.writes++;
|
|
193
|
+
this.stat.bytesWritten += bytes.length;
|
|
194
|
+
return true;
|
|
195
|
+
} catch (e) {
|
|
196
|
+
this.stat.writeFailures++;
|
|
197
|
+
this.ops.logger.warn(`failed to write tree snapshot: ${e instanceof Error ? e.message : String(e)}`);
|
|
198
|
+
return false;
|
|
199
|
+
} finally {
|
|
200
|
+
this.stat.millisWriting += Date.now() - started;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** Deletes the snapshot for a project. Used by the fail-safe, when a restored tree turns
|
|
204
|
+
* out not to match what the backend will serve. Never throws. */
|
|
205
|
+
async discard(root) {
|
|
206
|
+
try {
|
|
207
|
+
await node_fs_promises.default.rm(this.fileFor(root), { force: true });
|
|
208
|
+
this.stat.discarded++;
|
|
209
|
+
} catch (e) {
|
|
210
|
+
this.ops.logger.warn(`failed to discard tree snapshot: ${e instanceof Error ? e.message : String(e)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Startup housekeeping. Drops every snapshot outside the current scope (another build,
|
|
215
|
+
* backend, user or schema version), then trims what is left to the size ceiling, least
|
|
216
|
+
* recently written first.
|
|
217
|
+
*
|
|
218
|
+
* Modification time stands in for recency of use: an open project is rewritten
|
|
219
|
+
* periodically, so the file's age tracks how recently the project was worked on. Read times
|
|
220
|
+
* would be a truer signal but atime is unreliable across platforms and mount options.
|
|
221
|
+
*
|
|
222
|
+
* Runs at startup only, so the ceiling bounds what a session starts with rather than capping
|
|
223
|
+
* it throughout: a long session opening many projects can exceed it until the next launch.
|
|
224
|
+
*
|
|
225
|
+
* Never throws: an unusable cache directory should cost the cache, not the startup.
|
|
226
|
+
*/
|
|
227
|
+
async evict() {
|
|
228
|
+
try {
|
|
229
|
+
await (0, _milaboratories_ts_helpers.ensureDirExists)(this.ops.dir);
|
|
230
|
+
const names = await node_fs_promises.default.readdir(this.ops.dir);
|
|
231
|
+
const current = [];
|
|
232
|
+
for (const name of names) {
|
|
233
|
+
const file = node_path.default.join(this.ops.dir, name);
|
|
234
|
+
const inScope = name.startsWith(`${FILE_PREFIX}${this.scope}.`) && name.endsWith(FILE_SUFFIX);
|
|
235
|
+
if (!inScope && !isOurFile(name)) continue;
|
|
236
|
+
let size = 0;
|
|
237
|
+
let mtimeMs = 0;
|
|
238
|
+
try {
|
|
239
|
+
const stat = await node_fs_promises.default.stat(file);
|
|
240
|
+
if (!stat.isFile()) continue;
|
|
241
|
+
size = stat.size;
|
|
242
|
+
mtimeMs = stat.mtimeMs;
|
|
243
|
+
} catch {
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (inScope) {
|
|
247
|
+
current.push({
|
|
248
|
+
file,
|
|
249
|
+
size,
|
|
250
|
+
mtimeMs
|
|
251
|
+
});
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
await this.remove(file, size, false);
|
|
255
|
+
}
|
|
256
|
+
const ceiling = this.ops.maxSizeBytes;
|
|
257
|
+
let total = current.reduce((sum, e) => sum + e.size, 0);
|
|
258
|
+
if (total <= ceiling) return;
|
|
259
|
+
current.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
260
|
+
for (const entry of current) {
|
|
261
|
+
if (total <= ceiling) break;
|
|
262
|
+
if (await this.remove(entry.file, entry.size, true)) total -= entry.size;
|
|
263
|
+
}
|
|
264
|
+
} catch (e) {
|
|
265
|
+
this.ops.logger.warn(`tree snapshot eviction failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async remove(file, size, forSize) {
|
|
269
|
+
try {
|
|
270
|
+
await node_fs_promises.default.rm(file, { force: true });
|
|
271
|
+
this.stat.evicted++;
|
|
272
|
+
this.stat.bytesEvicted += size;
|
|
273
|
+
if (forSize) this.stat.evictedForSize++;
|
|
274
|
+
return true;
|
|
275
|
+
} catch {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
//#endregion
|
|
281
|
+
exports.TreeSnapshotStore = TreeSnapshotStore;
|
|
282
|
+
|
|
283
|
+
//# sourceMappingURL=tree_snapshot_store.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tree_snapshot_store.cjs","names":["PERSISTED_TREE_SCHEMA_VERSION","ML_BUILD_STAMP","fsp","path"],"sources":["../../src/middle_layer/tree_snapshot_store.ts"],"sourcesContent":["import type { PersistedTree, PersistedTreeReadFailure } from \"@milaboratories/pl-tree\";\nimport {\n decodePersistedTree,\n encodePersistedTree,\n PERSISTED_TREE_SCHEMA_VERSION,\n readPersistedTreeHeader,\n} from \"@milaboratories/pl-tree\";\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { parseSignedResourceId } from \"@milaboratories/pl-client\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { createPathAtomically, ensureDirExists } from \"@milaboratories/ts-helpers\";\nimport { createHash } from \"node:crypto\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { ML_BUILD_STAMP } from \"./build_stamp\";\n\n/** Why a read did not produce a tree to restore from. Counted rather than inferred, because\n * \"no snapshot\" and \"a snapshot we refused\" are very different things when a warm reopen\n * fails to be warm and someone has to work out why. */\nexport type TreeSnapshotMiss =\n /** No file for this key: a first open, or the key moved (new build, new backend, new user). */\n | \"absent\"\n /** A file is there but could not be opened at all: permissions, a bad mount, an I/O error.\n * Distinct from `absent` because a first open and a broken cache directory need different\n * answers from whoever reads the counters. */\n | \"unreadable\"\n /** File exists, but its signatures belong to a session that has ended. Kept, not deleted. */\n | \"session-rotated\"\n /** File exists and could not be read. Carries the codec's reason. */\n | PersistedTreeReadFailure;\n\nexport type TreeSnapshotStat = {\n reads: number;\n /** Snapshots read successfully. A hit is not yet a warm open: the tree can still refuse to\n * apply it, which is what {@link restores} counts. */\n hits: number;\n /** Snapshots actually applied as a tree's initial state. This is the number that says a\n * reopen was warm. */\n restores: number;\n /** Miss counts by reason. */\n misses: Record<TreeSnapshotMiss, number>;\n writes: number;\n writeFailures: number;\n bytesWritten: number;\n /** Snapshots deleted by the fail-safe after a restored tree failed its first refresh. */\n discarded: number;\n /** Files removed at startup, and how many of those were dropped for being over the ceiling\n * rather than for belonging to another build, backend or user. */\n evicted: number;\n evictedForSize: number;\n bytesEvicted: number;\n millisReading: number;\n millisWriting: number;\n};\n\nfunction initialStat(): TreeSnapshotStat {\n return {\n reads: 0,\n hits: 0,\n restores: 0,\n misses: {\n absent: 0,\n unreadable: 0,\n \"session-rotated\": 0,\n \"not-a-snapshot\": 0,\n \"unknown-schema\": 0,\n truncated: 0,\n checksum: 0,\n malformed: 0,\n },\n writes: 0,\n writeFailures: 0,\n bytesWritten: 0,\n discarded: 0,\n evicted: 0,\n evictedForSize: 0,\n bytesEvicted: 0,\n millisReading: 0,\n millisWriting: 0,\n };\n}\n\nexport type TreeSnapshotStoreOps = {\n /** Directory holding the snapshots. One file per project. */\n readonly dir: string;\n /** Total bytes the directory may occupy after startup eviction. */\n readonly maxSizeBytes: number;\n readonly logger: MiLogger;\n};\n\nconst FILE_PREFIX = \"tree.\";\nconst FILE_SUFFIX = \".plts\";\n\n/** Keeps a filename to characters every filesystem we target accepts. */\nfunction safe(part: string): string {\n return part.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/** Names this class writes: a finished snapshot, or the staging file of a write killed before\n * its rename. The directory is caller-supplied and only defaults to one of ours, so nothing\n * failing this is ever deleted, by the purge or by the startup eviction. */\nfunction isOurFile(name: string): boolean {\n if (!name.startsWith(FILE_PREFIX)) return false;\n return name.endsWith(FILE_SUFFIX) || name.includes(`${FILE_SUFFIX}.tmp.`);\n}\n\n/**\n * Snapshots of project tree mirrors on the local filesystem.\n *\n * A snapshot is addressed by backend instance, authenticated user, root resource, build stamp\n * and snapshot schema version. Everything except the root goes into the *scope*, which is\n * fixed for the lifetime of a client; the root distinguishes one project from another, so\n * there is one file per project per user per backend, rewritten in place.\n *\n * The session is deliberately not part of the key. It is witnessed inside the file and\n * compared on read: a snapshot from an ended session is a miss, but the file is kept, because\n * its bodies remain valid indefinitely and only its signatures have died. Deleting it would\n * destroy the evidence a future signature refresh would repair.\n */\nexport class TreeSnapshotStore {\n private readonly stat = initialStat();\n\n private constructor(\n private readonly ops: TreeSnapshotStoreOps,\n /** Identifies backend, user, build and schema. Same for every project in this session. */\n private readonly scope: string,\n ) {}\n\n /**\n * Builds a store for the given client, or returns undefined when nothing should be\n * persisted for it.\n *\n * Returns undefined for an impersonated client: reading and writing under `asUser` would\n * leave another user's mirror at rest under the admin's identity, usable only if the admin\n * returned to that exact root. One condition removes both the hygiene question and the\n * orphan one.\n */\n public static create(\n pl: PlClient,\n ops: TreeSnapshotStoreOps & { readonly enabled: boolean },\n ): TreeSnapshotStore | undefined {\n if (!ops.enabled) {\n ops.logger.info(\"tree snapshots are disabled by configuration\");\n return undefined;\n }\n if (pl.conf.asUser !== undefined) {\n ops.logger.info(\"tree snapshots are disabled while the client is opened as another user\");\n return undefined;\n }\n\n // The backend *instance*, not merely its address: instanceId rotates whenever the backend\n // resets its database, which is exactly the case where the same address starts serving a\n // different state under reused global ids. Without it, a reset at a fixed address (a local\n // backend, whose working directory does not move) would be a key hit, and the only thing\n // left to catch it would be the witness, which is empty on both sides on a backend that\n // predates resource signatures.\n //\n // Hashed rather than spelled out: a login can be an email and an address can carry\n // characters a filename cannot. The hash only has to be stable and to differ when any part\n // differs, both of which it does. The NUL separator keeps the parts unambiguous.\n const identity = createHash(\"sha256\")\n .update([pl.conf.hostAndPort, pl.serverInfo.instanceId ?? \"\", pl.authUser ?? \"\"].join(\"\\0\"))\n .digest(\"hex\")\n .slice(0, 16);\n\n const scope = `${PERSISTED_TREE_SCHEMA_VERSION}.${safe(ML_BUILD_STAMP)}.${identity}`;\n return new TreeSnapshotStore(ops, scope);\n }\n\n /**\n * Removes this class's files from the snapshot directory. Run when snapshots are switched\n * off, so a user who turns the kill switch off because the disk is full or unwritable\n * actually gets the space back, rather than leaving up to the size ceiling stranded there\n * indefinitely.\n *\n * Deliberately keyed on the setting rather than on \"there is no store\": a store is also\n * absent for an impersonated client, and deleting there would destroy the operator's own\n * snapshots from their ordinary sessions. Never throws.\n */\n public static async purge(dir: string, logger: MiLogger): Promise<void> {\n try {\n // Deliberately NOT a recursive delete of `dir`. The path is caller-supplied and only\n // defaults to a directory of ours, so removing it wholesale would let a misconfigured\n // `treeSnapshotPath` take an unrelated directory with it, at the exact moment the user\n // reached for a switch labelled \"my disk is troublesome\". Only files this class writes\n // are removed, then the directory itself if that emptied it.\n for (const name of await fsp.readdir(dir)) {\n if (!isOurFile(name)) continue;\n await fsp.rm(path.join(dir, name), { force: true }).catch(() => {});\n }\n await fsp.rmdir(dir).catch(() => {\n // Still holds something that is not ours; leaving it is the point.\n });\n } catch (e: unknown) {\n if ((e as NodeJS.ErrnoException | null)?.code === \"ENOENT\") return;\n logger.warn(\n `failed to clear the tree snapshot directory: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n public getStats(): Readonly<TreeSnapshotStat> {\n return this.stat;\n }\n\n private fileFor(root: SignedResourceId): string {\n // The root's global id, not the signed form: the signature changes every session while\n // the file must not.\n const { globalId } = parseSignedResourceId(root);\n return path.join(this.ops.dir, `${FILE_PREFIX}${this.scope}.${globalId}${FILE_SUFFIX}`);\n }\n\n /**\n * Reads the snapshot for a project root, or reports why there is nothing to restore.\n *\n * `root` is the id as resolved in the current session. Its signature is what the stored\n * witness is compared against, so a rotated session is detected without inflating the\n * payload, and no separate session lookup is needed anywhere.\n */\n public async read(\n root: SignedResourceId,\n ): Promise<{ ok: true; tree: PersistedTree } | { ok: false; miss: TreeSnapshotMiss }> {\n const started = Date.now();\n this.stat.reads++;\n try {\n const file = this.fileFor(root);\n let bytes: Buffer;\n try {\n bytes = await fsp.readFile(file);\n } catch (e: unknown) {\n // A missing file and an unreadable one both mean a cold open, but they are different\n // problems: one is an ordinary first open, the other is a cache directory that needs\n // attention, and the counters are the only place that difference is visible.\n const absent = (e as NodeJS.ErrnoException | null)?.code === \"ENOENT\";\n if (!absent)\n this.ops.logger.warn(\n `tree snapshot exists but could not be read: ${e instanceof Error ? e.message : String(e)}`,\n );\n return this.miss(absent ? \"absent\" : \"unreadable\");\n }\n\n const header = readPersistedTreeHeader(bytes);\n if (!header.ok) return this.miss(header.reason);\n\n // On a backend predating resource signatures both sides are empty and always match,\n // which is right: without signatures the ids are not session-bound in the first place.\n const { signature } = parseSignedResourceId(root);\n if (!Buffer.from(header.value.witness).equals(Buffer.from(signature)))\n // Kept, not deleted. See the class comment.\n return this.miss(\"session-rotated\");\n\n const decoded = await decodePersistedTree(bytes);\n if (!decoded.ok) return this.miss(decoded.reason);\n\n // Touched on a hit so the modification time tracks last *use*, which is what the size\n // trim is supposed to order by. Without this, a project reopened every day but never\n // changed is never rewritten, and so ages out ahead of one touched once and abandoned.\n const now = new Date();\n await fsp.utimes(file, now, now).catch(() => {\n // Ordering the trim is not worth failing a hit over.\n });\n\n this.stat.hits++;\n return { ok: true, tree: decoded.value };\n } finally {\n this.stat.millisReading += Date.now() - started;\n }\n }\n\n private miss(miss: TreeSnapshotMiss): { ok: false; miss: TreeSnapshotMiss } {\n this.stat.misses[miss]++;\n return { ok: false, miss };\n }\n\n /** Recorded by the caller once it knows the tree accepted the snapshot. The store cannot\n * tell on its own: it hands over bytes, and whether they become a tree is the tree's call. */\n public noteRestored(): void {\n this.stat.restores++;\n }\n\n /**\n * Writes a snapshot, replacing any previous one for the same project.\n *\n * Never throws and never rejects: a write is an optimisation, and a full disk or a\n * permissions problem must not fail the operation that triggered it. Staged and renamed\n * into place, so a process killed mid-write leaves the previous snapshot rather than a torn\n * one.\n */\n public async write(\n root: SignedResourceId,\n snapshot: PersistedTree,\n ops: { compress?: boolean } = {},\n ): Promise<boolean> {\n const started = Date.now();\n try {\n const bytes = await encodePersistedTree(snapshot, { compress: ops.compress });\n await ensureDirExists(this.ops.dir);\n\n const file = this.fileFor(root);\n await createPathAtomically(this.ops.logger, file, async (tempPath) => {\n // \"wx\" so a colliding temp name fails instead of overwriting another writer's file.\n await fsp.writeFile(tempPath, bytes, { flag: \"wx\" });\n });\n\n this.stat.writes++;\n this.stat.bytesWritten += bytes.length;\n return true;\n } catch (e: unknown) {\n this.stat.writeFailures++;\n this.ops.logger.warn(\n `failed to write tree snapshot: ${e instanceof Error ? e.message : String(e)}`,\n );\n return false;\n } finally {\n this.stat.millisWriting += Date.now() - started;\n }\n }\n\n /** Deletes the snapshot for a project. Used by the fail-safe, when a restored tree turns\n * out not to match what the backend will serve. Never throws. */\n public async discard(root: SignedResourceId): Promise<void> {\n try {\n await fsp.rm(this.fileFor(root), { force: true });\n this.stat.discarded++;\n } catch (e: unknown) {\n this.ops.logger.warn(\n `failed to discard tree snapshot: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n /**\n * Startup housekeeping. Drops every snapshot outside the current scope (another build,\n * backend, user or schema version), then trims what is left to the size ceiling, least\n * recently written first.\n *\n * Modification time stands in for recency of use: an open project is rewritten\n * periodically, so the file's age tracks how recently the project was worked on. Read times\n * would be a truer signal but atime is unreliable across platforms and mount options.\n *\n * Runs at startup only, so the ceiling bounds what a session starts with rather than capping\n * it throughout: a long session opening many projects can exceed it until the next launch.\n *\n * Never throws: an unusable cache directory should cost the cache, not the startup.\n */\n public async evict(): Promise<void> {\n try {\n await ensureDirExists(this.ops.dir);\n const names = await fsp.readdir(this.ops.dir);\n\n const current: { file: string; size: number; mtimeMs: number }[] = [];\n\n for (const name of names) {\n const file = path.join(this.ops.dir, name);\n\n // Anything of ours not addressed to the current scope goes: another build, backend,\n // user or schema version, and also the staging files of a write that was killed\n // before its rename, which end in `.tmp.<hex>` rather than the suffix.\n const inScope =\n name.startsWith(`${FILE_PREFIX}${this.scope}.`) && name.endsWith(FILE_SUFFIX);\n\n // Out of scope is not the same as ours to delete: a `treeSnapshotPath` pointed at an\n // existing or shared directory would otherwise have every file in it removed at\n // startup. Same rule as `purge`, for the same reason.\n if (!inScope && !isOurFile(name)) continue;\n\n let size = 0;\n let mtimeMs = 0;\n try {\n const stat = await fsp.stat(file);\n if (!stat.isFile()) continue;\n size = stat.size;\n mtimeMs = stat.mtimeMs;\n } catch {\n continue; // vanished under us, or unreadable: nothing to account for\n }\n\n if (inScope) {\n current.push({ file, size, mtimeMs });\n continue;\n }\n\n await this.remove(file, size, false);\n }\n\n const ceiling = this.ops.maxSizeBytes;\n let total = current.reduce((sum, e) => sum + e.size, 0);\n if (total <= ceiling) return;\n\n // Oldest first, so the projects a user is actually working on are the ones that survive.\n current.sort((a, b) => a.mtimeMs - b.mtimeMs);\n for (const entry of current) {\n if (total <= ceiling) break;\n // Only a file that actually went stops counting against the ceiling. Subtracting\n // regardless would let one undeletable file end the trim early and leave the directory\n // over its limit.\n if (await this.remove(entry.file, entry.size, true)) total -= entry.size;\n }\n } catch (e: unknown) {\n this.ops.logger.warn(\n `tree snapshot eviction failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n private async remove(file: string, size: number, forSize: boolean): Promise<boolean> {\n try {\n await fsp.rm(file, { force: true });\n this.stat.evicted++;\n this.stat.bytesEvicted += size;\n if (forSize) this.stat.evictedForSize++;\n return true;\n } catch {\n // A file we cannot delete is not worth failing startup over; it will be reconsidered\n // on the next one.\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAuDA,SAAS,cAAgC;CACvC,OAAO;EACL,OAAO;EACP,MAAM;EACN,UAAU;EACV,QAAQ;GACN,QAAQ;GACR,YAAY;GACZ,mBAAmB;GACnB,kBAAkB;GAClB,kBAAkB;GAClB,WAAW;GACX,UAAU;GACV,WAAW;EACb;EACA,QAAQ;EACR,eAAe;EACf,cAAc;EACd,WAAW;EACX,SAAS;EACT,gBAAgB;EAChB,cAAc;EACd,eAAe;EACf,eAAe;CACjB;AACF;AAUA,MAAM,cAAc;AACpB,MAAM,cAAc;;AAGpB,SAAS,KAAK,MAAsB;CAClC,OAAO,KAAK,QAAQ,mBAAmB,GAAG;AAC5C;;;;AAKA,SAAS,UAAU,MAAuB;CACxC,IAAI,C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KAAK;GACV,KAAK,KAAK,gBAAgB;GAC1B,IAAI,SAAS,KAAK,KAAK;GACvB,OAAO;EACT,QAAQ;GAGN,OAAO;EACT;CACF;AACF"}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { MiLogger } from "@milaboratories/ts-helpers";
|
|
2
|
+
import { PlClient, SignedResourceId } from "@milaboratories/pl-client";
|
|
3
|
+
import { PersistedTree, PersistedTreeReadFailure } from "@milaboratories/pl-tree";
|
|
4
|
+
//#region src/middle_layer/tree_snapshot_store.d.ts
|
|
5
|
+
/** Why a read did not produce a tree to restore from. Counted rather than inferred, because
|
|
6
|
+
* "no snapshot" and "a snapshot we refused" are very different things when a warm reopen
|
|
7
|
+
* fails to be warm and someone has to work out why. */
|
|
8
|
+
export type TreeSnapshotMiss =
|
|
9
|
+
/** No file for this key: a first open, or the key moved (new build, new backend, new user). */
|
|
10
|
+
"absent" |
|
|
11
|
+
/** A file is there but could not be opened at all: permissions, a bad mount, an I/O error.
|
|
12
|
+
* Distinct from `absent` because a first open and a broken cache directory need different
|
|
13
|
+
* answers from whoever reads the counters. */
|
|
14
|
+
"unreadable" |
|
|
15
|
+
/** File exists, but its signatures belong to a session that has ended. Kept, not deleted. */
|
|
16
|
+
"session-rotated" |
|
|
17
|
+
/** File exists and could not be read. Carries the codec's reason. */
|
|
18
|
+
PersistedTreeReadFailure;
|
|
19
|
+
export type TreeSnapshotStat = {
|
|
20
|
+
reads: number;
|
|
21
|
+
/** Snapshots read successfully. A hit is not yet a warm open: the tree can still refuse to
|
|
22
|
+
* apply it, which is what {@link restores} counts. */
|
|
23
|
+
hits: number;
|
|
24
|
+
/** Snapshots actually applied as a tree's initial state. This is the number that says a
|
|
25
|
+
* reopen was warm. */
|
|
26
|
+
restores: number;
|
|
27
|
+
/** Miss counts by reason. */
|
|
28
|
+
misses: Record<TreeSnapshotMiss, number>;
|
|
29
|
+
writes: number;
|
|
30
|
+
writeFailures: number;
|
|
31
|
+
bytesWritten: number;
|
|
32
|
+
/** Snapshots deleted by the fail-safe after a restored tree failed its first refresh. */
|
|
33
|
+
discarded: number;
|
|
34
|
+
/** Files removed at startup, and how many of those were dropped for being over the ceiling
|
|
35
|
+
* rather than for belonging to another build, backend or user. */
|
|
36
|
+
evicted: number;
|
|
37
|
+
evictedForSize: number;
|
|
38
|
+
bytesEvicted: number;
|
|
39
|
+
millisReading: number;
|
|
40
|
+
millisWriting: number;
|
|
41
|
+
};
|
|
42
|
+
export type TreeSnapshotStoreOps = {
|
|
43
|
+
/** Directory holding the snapshots. One file per project. */
|
|
44
|
+
readonly dir: string;
|
|
45
|
+
/** Total bytes the directory may occupy after startup eviction. */
|
|
46
|
+
readonly maxSizeBytes: number;
|
|
47
|
+
readonly logger: MiLogger;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Snapshots of project tree mirrors on the local filesystem.
|
|
51
|
+
*
|
|
52
|
+
* A snapshot is addressed by backend instance, authenticated user, root resource, build stamp
|
|
53
|
+
* and snapshot schema version. Everything except the root goes into the *scope*, which is
|
|
54
|
+
* fixed for the lifetime of a client; the root distinguishes one project from another, so
|
|
55
|
+
* there is one file per project per user per backend, rewritten in place.
|
|
56
|
+
*
|
|
57
|
+
* The session is deliberately not part of the key. It is witnessed inside the file and
|
|
58
|
+
* compared on read: a snapshot from an ended session is a miss, but the file is kept, because
|
|
59
|
+
* its bodies remain valid indefinitely and only its signatures have died. Deleting it would
|
|
60
|
+
* destroy the evidence a future signature refresh would repair.
|
|
61
|
+
*/
|
|
62
|
+
export declare class TreeSnapshotStore {
|
|
63
|
+
private readonly ops;
|
|
64
|
+
/** Identifies backend, user, build and schema. Same for every project in this session. */
|
|
65
|
+
private readonly scope;
|
|
66
|
+
private readonly stat;
|
|
67
|
+
private constructor();
|
|
68
|
+
/**
|
|
69
|
+
* Builds a store for the given client, or returns undefined when nothing should be
|
|
70
|
+
* persisted for it.
|
|
71
|
+
*
|
|
72
|
+
* Returns undefined for an impersonated client: reading and writing under `asUser` would
|
|
73
|
+
* leave another user's mirror at rest under the admin's identity, usable only if the admin
|
|
74
|
+
* returned to that exact root. One condition removes both the hygiene question and the
|
|
75
|
+
* orphan one.
|
|
76
|
+
*/
|
|
77
|
+
static create(pl: PlClient, ops: TreeSnapshotStoreOps & {
|
|
78
|
+
readonly enabled: boolean;
|
|
79
|
+
}): TreeSnapshotStore | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Removes this class's files from the snapshot directory. Run when snapshots are switched
|
|
82
|
+
* off, so a user who turns the kill switch off because the disk is full or unwritable
|
|
83
|
+
* actually gets the space back, rather than leaving up to the size ceiling stranded there
|
|
84
|
+
* indefinitely.
|
|
85
|
+
*
|
|
86
|
+
* Deliberately keyed on the setting rather than on "there is no store": a store is also
|
|
87
|
+
* absent for an impersonated client, and deleting there would destroy the operator's own
|
|
88
|
+
* snapshots from their ordinary sessions. Never throws.
|
|
89
|
+
*/
|
|
90
|
+
static purge(dir: string, logger: MiLogger): Promise<void>;
|
|
91
|
+
getStats(): Readonly<TreeSnapshotStat>;
|
|
92
|
+
private fileFor;
|
|
93
|
+
/**
|
|
94
|
+
* Reads the snapshot for a project root, or reports why there is nothing to restore.
|
|
95
|
+
*
|
|
96
|
+
* `root` is the id as resolved in the current session. Its signature is what the stored
|
|
97
|
+
* witness is compared against, so a rotated session is detected without inflating the
|
|
98
|
+
* payload, and no separate session lookup is needed anywhere.
|
|
99
|
+
*/
|
|
100
|
+
read(root: SignedResourceId): Promise<{
|
|
101
|
+
ok: true;
|
|
102
|
+
tree: PersistedTree;
|
|
103
|
+
} | {
|
|
104
|
+
ok: false;
|
|
105
|
+
miss: TreeSnapshotMiss;
|
|
106
|
+
}>;
|
|
107
|
+
private miss;
|
|
108
|
+
/** Recorded by the caller once it knows the tree accepted the snapshot. The store cannot
|
|
109
|
+
* tell on its own: it hands over bytes, and whether they become a tree is the tree's call. */
|
|
110
|
+
noteRestored(): void;
|
|
111
|
+
/**
|
|
112
|
+
* Writes a snapshot, replacing any previous one for the same project.
|
|
113
|
+
*
|
|
114
|
+
* Never throws and never rejects: a write is an optimisation, and a full disk or a
|
|
115
|
+
* permissions problem must not fail the operation that triggered it. Staged and renamed
|
|
116
|
+
* into place, so a process killed mid-write leaves the previous snapshot rather than a torn
|
|
117
|
+
* one.
|
|
118
|
+
*/
|
|
119
|
+
write(root: SignedResourceId, snapshot: PersistedTree, ops?: {
|
|
120
|
+
compress?: boolean;
|
|
121
|
+
}): Promise<boolean>;
|
|
122
|
+
/** Deletes the snapshot for a project. Used by the fail-safe, when a restored tree turns
|
|
123
|
+
* out not to match what the backend will serve. Never throws. */
|
|
124
|
+
discard(root: SignedResourceId): Promise<void>;
|
|
125
|
+
/**
|
|
126
|
+
* Startup housekeeping. Drops every snapshot outside the current scope (another build,
|
|
127
|
+
* backend, user or schema version), then trims what is left to the size ceiling, least
|
|
128
|
+
* recently written first.
|
|
129
|
+
*
|
|
130
|
+
* Modification time stands in for recency of use: an open project is rewritten
|
|
131
|
+
* periodically, so the file's age tracks how recently the project was worked on. Read times
|
|
132
|
+
* would be a truer signal but atime is unreliable across platforms and mount options.
|
|
133
|
+
*
|
|
134
|
+
* Runs at startup only, so the ceiling bounds what a session starts with rather than capping
|
|
135
|
+
* it throughout: a long session opening many projects can exceed it until the next launch.
|
|
136
|
+
*
|
|
137
|
+
* Never throws: an unusable cache directory should cost the cache, not the startup.
|
|
138
|
+
*/
|
|
139
|
+
evict(): Promise<void>;
|
|
140
|
+
private remove;
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//# sourceMappingURL=tree_snapshot_store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tree_snapshot_store.d.ts","names":[],"sources":["../../src/middle_layer/tree_snapshot_store.ts"],"mappings":";;;;;;;YAmBY;;;;;;;;;;AAUR;YAEQ;EACV;;;EAGA;;;EAGA;;EAEA,QAAQ,OAAO;EACf;EACA;EACA;;EAEA;;;EAGA;EACA;EACA;EACA;EACA;;YA8BU;;WAED;;WAEA;WACA,QAAQ;;;;;;;;;;;;;;;qBAgCN;mBAIQ;;mBAEA;mBALF;UAEV;;;;;;;;;;SAeO,OACZ,IAAI,UACJ,KAAK;aAAkC;MACtC;;;;;;;;;;;SAuCiB,MAAM,aAAa,QAAQ,WAAW;EAsBnD,YAAY,SAAS;UAIpB;;;;;;;;EAcK,KACX,MAAM,mBACL;IAAU;IAAU,MAAM;;IAAoB;IAAW,MAAM;;UAgD1D;;;EAOD;;;;;;;;;EAYM,MACX,MAAM,kBACN,UAAU,eACV;IAAO;MACN;;;EA4BU,QAAQ,MAAM,mBAAmB;;;;;;;;;;;;;;;EAyBjC,SAAS;UA4DR"}
|