@johnhenry/sitefile 0.0.7 → 0.0.9

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +104 -1
  2. package/README.md +12 -1
  3. package/lib/src/attest.d.ts +12 -3
  4. package/lib/src/attest.js +15 -10
  5. package/lib/src/bake.js +2 -1
  6. package/lib/src/base-image.d.ts +2 -0
  7. package/lib/src/base-image.js +8 -0
  8. package/lib/src/bucket-follow.d.ts +22 -0
  9. package/lib/src/bucket-follow.js +65 -0
  10. package/lib/src/bucket.d.ts +270 -0
  11. package/lib/src/bucket.js +1130 -0
  12. package/lib/src/cache-limit.d.ts +3 -3
  13. package/lib/src/cache-limit.js +21 -0
  14. package/lib/src/cli/bucket.d.ts +2 -0
  15. package/lib/src/cli/bucket.js +312 -0
  16. package/lib/src/cli/build-image.js +4 -2
  17. package/lib/src/cli/images.js +8 -5
  18. package/lib/src/cli/index.d.ts +1 -1
  19. package/lib/src/cli/index.js +13 -2
  20. package/lib/src/cli/serve-worker.js +63 -11
  21. package/lib/src/cli/servers.js +117 -29
  22. package/lib/src/cli/up.js +2 -0
  23. package/lib/src/cli/watch.d.ts +2 -0
  24. package/lib/src/cli/watch.js +2 -1
  25. package/lib/src/cli.js +6 -3
  26. package/lib/src/dictionary.d.ts +1 -7
  27. package/lib/src/dictionary.js +1 -35
  28. package/lib/src/executor.d.ts +16 -5
  29. package/lib/src/executor.js +127 -58
  30. package/lib/src/index.d.ts +2 -0
  31. package/lib/src/index.js +2 -0
  32. package/lib/src/mime-type.d.ts +6 -0
  33. package/lib/src/mime-type.js +20 -0
  34. package/lib/src/nfc.d.ts +6 -0
  35. package/lib/src/nfc.js +10 -0
  36. package/lib/src/oci.d.ts +65 -1
  37. package/lib/src/oci.js +104 -10
  38. package/lib/src/paths.d.ts +2 -6
  39. package/lib/src/paths.js +2 -8
  40. package/lib/src/plugins/env.d.ts +20 -0
  41. package/lib/src/plugins/env.js +37 -0
  42. package/lib/src/plugins/exec.d.ts +1 -1
  43. package/lib/src/plugins/exec.js +3 -2
  44. package/lib/src/plugins/host.js +3 -2
  45. package/lib/src/precompress.d.ts +6 -0
  46. package/lib/src/precompress.js +6 -0
  47. package/lib/src/recipe.d.ts +37 -0
  48. package/lib/src/recipe.js +96 -0
  49. package/lib/src/registry-ops.d.ts +5 -1
  50. package/lib/src/registry-ops.js +69 -45
  51. package/lib/src/request-path.d.ts +10 -0
  52. package/lib/src/request-path.js +42 -0
  53. package/lib/src/serve-dictionary.d.ts +11 -0
  54. package/lib/src/serve-dictionary.js +45 -0
  55. package/lib/src/serve-rules.js +1 -1
  56. package/lib/src/server.d.ts +16 -229
  57. package/lib/src/server.js +135 -795
  58. package/lib/src/servers.d.ts +25 -0
  59. package/lib/src/servers.js +62 -2
  60. package/lib/src/site-core.d.ts +368 -0
  61. package/lib/src/site-core.js +1065 -0
  62. package/lib/src/site-handler.d.ts +14 -0
  63. package/lib/src/site-handler.js +32 -0
  64. package/lib/src/store.d.ts +31 -2
  65. package/lib/src/store.js +140 -21
  66. package/lib/src/wbn.d.ts +1 -6
  67. package/lib/src/wbn.js +2 -18
  68. package/package.json +5 -1
@@ -0,0 +1,1130 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { constants as C, promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { sha256 } from './digest.js';
5
+ import { SitefileError } from './errors.js';
6
+ import { foldCase, nfc } from './paths.js';
7
+ import { windowsProblem } from './portable.js';
8
+ import { makeFile, Tree } from './tree.js';
9
+ /**
10
+ * Buckets: named, mutable file trees owned by the store (docs/CLI.md, "Buckets"). Twin: rust/src/bucket.rs.
11
+ *
12
+ * $SITEFILE_HOME/buckets/<name>/ the files, plain (what `serve bucket:<name>` serves)
13
+ * $SITEFILE_HOME/buckets/.meta/<name>.json {"created": "<iso>"}, beside the tree and never in it
14
+ * $SITEFILE_HOME/buckets/.tmp/ files being written (renamed into place when whole)
15
+ * $SITEFILE_HOME/buckets/.staging/ a `--batch` tree being built, swapped in with two renames
16
+ * $SITEFILE_HOME/buckets/.swap/ the journal and the displaced tree of a swap in progress (never swept)
17
+ *
18
+ * Every change holds the store lock. A file is written to `.tmp` and renamed into place, so a reader sees
19
+ * the old file or the new one, never half of it. Nothing here follows a symbolic link, and a file with
20
+ * more than one hard link is never read: a bucket directory another program has planted links in is
21
+ * refused, not read through.
22
+ */
23
+ export const BUCKET_NAME_MAX = 63;
24
+ /** What `bucket put` accepts from stdin or a file unless `--max-bytes` says otherwise. */
25
+ export const DEFAULT_PUT_MAX_BYTES = 256 * 1024 * 1024;
26
+ /** A path segment's longest UTF-8 length, and a whole path's. */
27
+ const SEGMENT_MAX = 255;
28
+ const PATH_MAX = 1024;
29
+ const NAME_RE = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
30
+ const code = (e) => e?.code;
31
+ // ------------------------------------------------------------ names and paths
32
+ /** Validate a bucket name (`E_USAGE`). The grammar is lowercase on purpose: two names never differ only in case. */
33
+ export function checkBucketName(name) {
34
+ if (name.length === 0 || name.length > BUCKET_NAME_MAX || !NAME_RE.test(name)) {
35
+ throw new SitefileError('E_USAGE', `invalid bucket name '${name}' (lowercase letters, digits, '.', '_' and '-' between them, at most ${BUCKET_NAME_MAX} characters)`);
36
+ }
37
+ const why = windowsProblem(`/${name}`);
38
+ if (why !== undefined)
39
+ throw new SitefileError('E_USAGE', `invalid bucket name '${name}': ${why}`);
40
+ return name;
41
+ }
42
+ /**
43
+ * The segments of a path inside a bucket (`a/b/c.txt`), NFC. Refused: NUL, backslashes, `..` and `.`, a leading
44
+ * `/` (absolute), empty segments, names Windows cannot hold, and over-long names. A single trailing `/` is
45
+ * dropped (the caller decides whether a directory is fine).
46
+ */
47
+ export function checkBucketPath(raw) {
48
+ const p = nfc(raw);
49
+ if (p.includes('\0'))
50
+ throw new SitefileError('E_PATH', 'bucket path contains a NUL byte');
51
+ if (p.includes('\\'))
52
+ throw new SitefileError('E_PATH', `bucket path '${p}' must not contain a backslash`);
53
+ if (p.startsWith('/'))
54
+ throw new SitefileError('E_PATH_ESCAPE', `bucket path '${p}' must be relative to the bucket (no leading '/')`);
55
+ const body = p.endsWith('/') ? p.slice(0, -1) : p;
56
+ if (body === '')
57
+ return [];
58
+ const segs = body.split('/');
59
+ for (const s of segs) {
60
+ if (s === '..')
61
+ throw new SitefileError('E_PATH_ESCAPE', `bucket path '${p}' must not contain '..'`);
62
+ if (s === '')
63
+ throw new SitefileError('E_PATH', `bucket path '${p}' has an empty segment`);
64
+ if (s === '.')
65
+ throw new SitefileError('E_PATH', `bucket path '${p}' must not contain '.' segments`);
66
+ if (Buffer.byteLength(s) > SEGMENT_MAX)
67
+ throw new SitefileError('E_PATH', `bucket path '${p}' has a segment longer than ${SEGMENT_MAX} bytes`);
68
+ }
69
+ if (Buffer.byteLength(body) > PATH_MAX)
70
+ throw new SitefileError('E_PATH', `bucket path '${p}' is longer than ${PATH_MAX} bytes`);
71
+ const why = windowsProblem(`/${body}`);
72
+ if (why !== undefined)
73
+ throw new SitefileError('E_PATH_PORTABLE', `bucket path '${p}' cannot be extracted on Windows: ${why}`);
74
+ return segs;
75
+ }
76
+ /** `name/path/inside` → its name and the segments of what follows the first `/` (none for a bare name). */
77
+ export function splitBucketRef(arg) {
78
+ const i = arg.indexOf('/');
79
+ const name = checkBucketName(i === -1 ? arg : arg.slice(0, i));
80
+ if (i === -1)
81
+ return { name, segs: [], slash: false };
82
+ return { name, segs: checkBucketPath(arg.slice(i + 1)), slash: true };
83
+ }
84
+ /** `bucket:<name>[/prefix]` as `serve` and the servers file write it, or undefined when `arg` is not one. */
85
+ export function parseBucketSource(arg) {
86
+ if (!arg.startsWith('bucket:'))
87
+ return undefined;
88
+ const { name, segs } = splitBucketRef(arg.slice(7));
89
+ return { name, prefix: segs.length > 0 ? segs.join('/') : undefined };
90
+ }
91
+ export const bucketLabel = (name, prefix) => `bucket:${name}${prefix !== undefined ? `/${prefix}` : ''}`;
92
+ const shownPath = (segs) => `/${segs.join('/')}`;
93
+ const bucketPathOf = (name, segs) => `bucket:${name}${shownPath(segs)}`;
94
+ // ------------------------------------------------------------ the file system
95
+ const modeOf = (st) => (st.mode & 0o111 ? 0o755 : 0o644);
96
+ /** What the tests may hook and count (never set in production). */
97
+ export const bucketHooks = {};
98
+ /** Thrown by a test's `bucketHooks.crash`: the swap stops where it is and leaves everything as a crash would. */
99
+ export class SwapCrash extends Error {
100
+ }
101
+ export const bucketStats = { fileReads: 0 };
102
+ /** The most bytes `serve`, `snapshot` and `restore` hold in memory for a bucket unless `--max-bytes` says otherwise. */
103
+ export const DEFAULT_LOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024;
104
+ async function lstatOrUndefined(p) {
105
+ try {
106
+ return await fs.lstat(p);
107
+ }
108
+ catch (e) {
109
+ if (code(e) === 'ENOENT' || code(e) === 'ENOTDIR')
110
+ return undefined;
111
+ throw e;
112
+ }
113
+ }
114
+ /** A file that vanished or changed between being listed and being read: the whole read is tried again. */
115
+ export class BucketRace extends SitefileError {
116
+ }
117
+ /** The sentence for a link planted in a bucket (`ls`, `serve`, `snapshot`, `put`, `restore` say the same). */
118
+ const linkSentence = (name, rel) => `bucket '${name}' has a link at ${rel}: remove it with "sitefile bucket rm ${name}${rel}"`;
119
+ const symlinkError = (what) => new SitefileError('E_PATH_ESCAPE', `${what} is a symbolic link; a bucket never follows symbolic links`);
120
+ const hardlinkError = (what, n) => new SitefileError('E_HARDLINK', `${what} has ${n} hard links and may alias a file outside the bucket; a bucket never reads such a file`);
121
+ const specialError = (what) => new SitefileError('E_UNSUPPORTED_FILE', `${what} is not a regular file or directory (sockets, fifos and devices are not supported)`);
122
+ /**
123
+ * The bytes and mode of a regular file with one link. It is opened without following a symbolic link and without
124
+ * blocking (a FIFO swapped in after `st` was taken must not hang the command, which may hold the store lock), and
125
+ * the open file must still be the one `st` described. On Windows there is no `O_NOFOLLOW`, no FIFO in a directory
126
+ * and no stable inode here: a reparse point swapped in is caught by the file-type and link-count checks only.
127
+ */
128
+ export async function readRegular(file, st, what) {
129
+ if (st.isSymbolicLink())
130
+ throw symlinkError(what);
131
+ if (!st.isFile())
132
+ throw specialError(what);
133
+ if (st.nlink > 1)
134
+ throw hardlinkError(what, st.nlink);
135
+ let fh;
136
+ try {
137
+ fh = await fs.open(file, C.O_RDONLY | (C.O_NOFOLLOW ?? 0) | (C.O_NONBLOCK ?? 0));
138
+ }
139
+ catch (e) {
140
+ if (code(e) === 'ELOOP')
141
+ throw symlinkError(what);
142
+ if (code(e) === 'ENOENT')
143
+ throw new BucketRace('E_NOT_FOUND', `${what} vanished while it was being read`);
144
+ throw e;
145
+ }
146
+ try {
147
+ const now = await fh.stat();
148
+ // The path must still be the file we looked at (a swap between the check and the open is refused).
149
+ if (!now.isFile() || now.nlink > 1 || (process.platform !== 'win32' && (now.ino !== st.ino || now.dev !== st.dev))) {
150
+ throw new BucketRace('E_PATH_ESCAPE', `${what} changed while it was being read`);
151
+ }
152
+ if (process.platform === 'win32') {
153
+ // No O_NOFOLLOW and no dev here: the handle must be the file the path names now (NTFS reports its 64-bit file
154
+ // index as ino, exact with bigint) and the one that was listed (size and mtime).
155
+ const [h, p] = [await fh.stat({ bigint: true }), await fs.lstat(file, { bigint: true })];
156
+ if (!p.isFile() || h.ino !== p.ino || h.size !== p.size || h.mtimeNs !== p.mtimeNs || h.size !== BigInt(st.size) || now.mtimeMs !== st.mtimeMs) {
157
+ throw new BucketRace('E_PATH_ESCAPE', `${what} changed while it was being read`);
158
+ }
159
+ }
160
+ // At most the size that was listed, plus one byte to notice a file that grew: the size cap holds whatever happens
161
+ // after the listing (a file that changed size is read again from a fresh listing, and counted there).
162
+ const buf = Buffer.allocUnsafeSlow(st.size + 1);
163
+ let n = 0;
164
+ for (;;) {
165
+ const { bytesRead } = await fh.read(buf, n, buf.length - n, n);
166
+ if (bytesRead === 0)
167
+ break;
168
+ n += bytesRead;
169
+ if (n === buf.length)
170
+ break;
171
+ }
172
+ if (n !== st.size)
173
+ throw new BucketRace('E_PATH_ESCAPE', `${what} changed while it was being read`);
174
+ bucketStats.fileReads++;
175
+ return { bytes: new Uint8Array(buf.buffer, buf.byteOffset, n), mode: modeOf(now) };
176
+ }
177
+ finally {
178
+ await fh.close();
179
+ }
180
+ }
181
+ const warned = new Set();
182
+ /** A warning, once per message and process. */
183
+ function warnOnce(message) {
184
+ if (warned.has(message))
185
+ return;
186
+ warned.add(message);
187
+ (bucketHooks.warn ?? ((m) => void process.stderr.write(`warning: ${m}\n`)))(message);
188
+ }
189
+ /** Whether `n` is a bucket name in full (grammar, length, reserved names): checked before any path is built from a name read off the disk. */
190
+ function isBucketName(n) {
191
+ try {
192
+ checkBucketName(n);
193
+ return true;
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ }
199
+ /** Every read of a bucket file goes through here: the hook (tests), then the one guarded open. */
200
+ async function readEntry(e, what) {
201
+ await bucketHooks.beforeRead?.(e.file);
202
+ return readRegular(e.file, e.st, what);
203
+ }
204
+ const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
205
+ const stampOf = (st) => `${st.size}:${st.mtimeMs}:${st.ctimeMs}:${st.ino}`;
206
+ /**
207
+ * Every file under `dir` (a real directory) with `lstat` only, as bucket-relative paths: nothing is read, so the cost is
208
+ * proportional to the number of entries. A file or directory that vanishes during the walk is skipped. Symbolic links
209
+ * and hard-linked files are errors that say which link to remove, special files are `E_UNSUPPORTED_FILE`, and two names
210
+ * that differ only in Unicode normalization are `E_PATH_COLLISION`. `o.dirs` receives every directory, empty ones too.
211
+ */
212
+ export async function scanDirectory(dir, name, relBase, o = {}) {
213
+ const out = [];
214
+ const root = await fs.lstat(dir);
215
+ const walk = async (real, rel) => {
216
+ let names;
217
+ try {
218
+ names = (await fs.readdir(real)).sort(byName);
219
+ }
220
+ catch (e) {
221
+ if (code(e) === 'ENOENT' && rel.length > 0)
222
+ return; // removed while we walked
223
+ throw e;
224
+ }
225
+ const seen = new Set();
226
+ for (const raw of names) {
227
+ const n = nfc(raw);
228
+ const childRel = [...rel, n];
229
+ const full = shownPath([...relBase, ...childRel]);
230
+ if (seen.has(n))
231
+ throw new SitefileError('E_PATH_COLLISION', `'bucket:${name}${full}' names more than one file in the bucket: their names differ only in Unicode normalization (NFC/NFD); rename one`);
232
+ seen.add(n);
233
+ const child = path.join(real, raw);
234
+ const st = await lstatOrUndefined(child);
235
+ if (st === undefined)
236
+ continue;
237
+ if (st.isSymbolicLink())
238
+ throw new SitefileError('E_PATH_ESCAPE', linkSentence(name, full));
239
+ if (st.isDirectory()) {
240
+ o.dirs?.push(shownPath(childRel));
241
+ await walk(child, childRel);
242
+ }
243
+ else if (st.isFile()) {
244
+ if (st.nlink > 1)
245
+ throw new SitefileError('E_HARDLINK', linkSentence(name, full));
246
+ out.push({ path: shownPath(childRel), size: st.size, mode: modeOf(st), file: child, st, stamp: stampOf(st) });
247
+ }
248
+ else
249
+ throw specialError(`'bucket:${name}${full}'`);
250
+ }
251
+ };
252
+ await walk(dir, []);
253
+ // Entries that vanished are skipped, but not because the whole directory moved away (a `--batch` swap): the walk is
254
+ // only good if the directory is still the one it started in.
255
+ const after = await lstatOrUndefined(dir);
256
+ if (after === undefined || after.ino !== root.ino || after.dev !== root.dev)
257
+ throw new BucketRace('E_NOT_FOUND', `bucket '${name}' vanished while it was being read`);
258
+ return out;
259
+ }
260
+ const foldPath = (p) => p.split('/').map((s) => foldCase(nfc(s))).join('/');
261
+ const EMPTY = new Uint8Array(0);
262
+ /** What a swap's staging directory is called: the journal may name nothing else. */
263
+ const STAGE_TOKEN = /^[a-f0-9]{16,64}$/;
264
+ /** A staged tree belongs to a bucket by its name: `.staging/<bucket>.<token>`. */
265
+ const stageName = (name, token) => `${name}.${token}`;
266
+ /**
267
+ * Flush a file or a directory to disk. A failed flush is an error (EIO, ENOSPC, EMFILE, EACCES ...): the swap that
268
+ * needs it stops before its first rename. The one thing tolerated, identically in the Rust port, is a directory that
269
+ * cannot be opened or flushed because the file system or the platform has no such thing (EINVAL, ENOTSUP, EISDIR,
270
+ * EBADF, EPERM: Windows, some network file systems): there the rename is as durable as the file system makes it, and
271
+ * recovery does not depend on the journal (docs/CLI.md, "Buckets"). A file is never excused.
272
+ */
273
+ const DIR_CANNOT_FLUSH = ['EINVAL', 'ENOTSUP', 'EISDIR', 'EBADF', 'EPERM'];
274
+ async function fsyncPath(p, dir = false) {
275
+ bucketHooks.flush?.(p);
276
+ let fh;
277
+ try {
278
+ // FlushFileBuffers needs write access to the handle: a file is opened for it on Windows (a directory cannot be opened there).
279
+ fh = await fs.open(p, process.platform === 'win32' && !dir ? 'r+' : 'r');
280
+ }
281
+ catch (e) {
282
+ if (dir && DIR_CANNOT_FLUSH.includes(code(e) ?? ''))
283
+ return;
284
+ throw e;
285
+ }
286
+ try {
287
+ await fh.sync();
288
+ }
289
+ catch (e) {
290
+ if (!(dir && DIR_CANNOT_FLUSH.includes(code(e) ?? '')))
291
+ throw e;
292
+ }
293
+ finally {
294
+ await fh.close();
295
+ }
296
+ }
297
+ const fsyncDir = (p) => fsyncPath(p, true);
298
+ /** Flush every file and directory under `dir`, then `dir`. */
299
+ async function fsyncTree(dir) {
300
+ for (const e of await fs.readdir(dir, { withFileTypes: true }))
301
+ if (e.isDirectory())
302
+ await fsyncTree(path.join(dir, e.name));
303
+ await fsyncDir(dir);
304
+ }
305
+ /** Write a staged file, flush it, and only then give it its final mode (a read-only file cannot be flushed on Windows). */
306
+ async function writeStaged(file, bytes, mode) {
307
+ await fs.writeFile(file, bytes, { mode: 0o600 });
308
+ await fsyncPath(file);
309
+ await fs.chmod(file, mode);
310
+ }
311
+ export class Buckets {
312
+ store;
313
+ root;
314
+ constructor(store) {
315
+ this.store = store;
316
+ this.root = path.join(store.home, 'buckets');
317
+ }
318
+ static open(store) {
319
+ return new Buckets(store);
320
+ }
321
+ dirOf(name) {
322
+ return path.join(this.root, checkBucketName(name));
323
+ }
324
+ metaFile(name) {
325
+ return path.join(this.root, '.meta', `${name}.json`);
326
+ }
327
+ get tmpDir() {
328
+ return path.join(this.root, '.tmp');
329
+ }
330
+ get stagingDir() {
331
+ return path.join(this.root, '.staging');
332
+ }
333
+ /** `.swap/<name>.json` is the journal of a `--batch` swap, `.swap/<name>.old` the displaced tree: the sweep never touches either. */
334
+ get swapDir() {
335
+ return path.join(this.root, '.swap');
336
+ }
337
+ journalOf(name) {
338
+ return path.join(this.swapDir, `${name}.json`);
339
+ }
340
+ oldOf(name) {
341
+ return path.join(this.swapDir, `${name}.old`);
342
+ }
343
+ async scratch(dir) {
344
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
345
+ return path.join(dir, randomBytes(8).toString('hex'));
346
+ }
347
+ // -------------------------------------------------------- an interrupted swap
348
+ /**
349
+ * A `--batch` swap is: build the new tree in `.staging/<bucket>.<token>`, journal `.swap/<name>.json` = `{"token": "<hex>"}`
350
+ * (data only: every path is derived from the bucket name and a token matching /^[a-f0-9]{16,64}$/, never read from
351
+ * the journal), rename the bucket to `.swap/<name>.old`, rename the staged tree to the bucket, remove the journal,
352
+ * remove `.old`. Durability, in this order: every staged file and directory is fsynced; the journal is written to a
353
+ * temporary file, fsynced, renamed, and `.swap` is fsynced, all BEFORE the first bucket rename (else power loss could
354
+ * keep that rename and lose the journal); after each rename that matters the directories it changed are fsynced (the
355
+ * bucket's parent and `.swap` after the first, the parent and `.staging` after the second, `.swap` after the
356
+ * journal's removal). Windows cannot fsync a directory: files are flushed (FlushFileBuffers) and NTFS journals its
357
+ * own metadata, but the order of two renames across a power loss is not guaranteed there; recovery below does not
358
+ * depend on the journal for that reason.
359
+ *
360
+ * Recovery runs under the lock before anything else touches the bucket, and decides from the directory state
361
+ * (J journal, D bucket directory, O `.swap/<name>.old`, S the staged tree `.staging/<name>.<token>`):
362
+ *
363
+ * J D O S action
364
+ * - - - . nothing (no such bucket)
365
+ * - y - . nothing
366
+ * - y y . keep O: a leftover of a finished swap; only the next successful swap of this bucket, or
367
+ * `bucket rm`, removes it, never create or a sweep
368
+ * - - y . put O back as D (power loss kept the first rename and lost the journal)
369
+ * y y - . the swap never began or was rolled back: remove S and J
370
+ * y y y . the swap finished: remove O, S and J
371
+ * y - y . the new tree was never placed: put O back as D, remove S and J (rolled back, not finished)
372
+ * y - - y O is gone and D is not there: the complete staged tree becomes D, J is removed
373
+ * y - - - nothing left to restore: remove J
374
+ *
375
+ * `bucket rm` runs the other way round: it recovers, then removes O, J and every S of the bucket and fsyncs `.swap`
376
+ * and `.staging`, failing loudly if it cannot, and only then renames D away, so a crash inside it leaves D (or
377
+ * nothing), never an O that the next command would put back: a removed bucket cannot come back with old contents.
378
+ * No removal of an O, J or S is ever ignored.
379
+ *
380
+ * A journal that is unreadable, empty, garbage or not UTF-8 names no token: the state is decided from D, O and J's
381
+ * existence alone. Running recovery again changes nothing.
382
+ */
383
+ async needsRecovery(name) {
384
+ if ((await lstatOrUndefined(this.journalOf(name))) !== undefined)
385
+ return true;
386
+ return (await lstatOrUndefined(this.oldOf(name))) !== undefined && (await lstatOrUndefined(this.dirOf(name))) === undefined;
387
+ }
388
+ /** Recover for a writer: under the lock, before it works on the bucket. */
389
+ async recover(name) {
390
+ if (!(await this.needsRecovery(name)))
391
+ return;
392
+ await this.store.withLock(() => this.recoverLocked(name));
393
+ }
394
+ /**
395
+ * Recover for a reader: an intact bucket (its directory is there) is served as it is, leftovers and all, so a read
396
+ * never writes (the store may be read-only). Only a bucket whose directory is missing is recovered, which needs
397
+ * the lock (it also waits for a swap in progress); if that is impossible the read fails and says why.
398
+ */
399
+ async recoverForRead(name) {
400
+ if (!(await this.needsRecovery(name)))
401
+ return;
402
+ if ((await lstatOrUndefined(this.dirOf(name))) !== undefined)
403
+ return;
404
+ try {
405
+ await this.store.withLock(() => this.recoverLocked(name));
406
+ }
407
+ catch (e) {
408
+ if (e instanceof SitefileError && e.code === 'E_STORE') {
409
+ throw new SitefileError('E_STORE', `bucket '${name}' needs the recovery of an interrupted swap, which needs the store lock: ${e.message}`, undefined, { cause: e });
410
+ }
411
+ throw e;
412
+ }
413
+ }
414
+ /** {@link recover} for a caller that holds the lock. */
415
+ async recoverLocked(name) {
416
+ const journal = this.journalOf(name);
417
+ const dir = this.dirOf(name);
418
+ const old = this.oldOf(name);
419
+ let hasJournal = false;
420
+ let token;
421
+ try {
422
+ const bytes = await fs.readFile(journal);
423
+ hasJournal = true;
424
+ try {
425
+ const t = JSON.parse(new TextDecoder('utf-8').decode(bytes))?.token;
426
+ if (typeof t === 'string' && STAGE_TOKEN.test(t))
427
+ token = t;
428
+ }
429
+ catch {
430
+ /* unreadable, empty, garbage or not UTF-8: no token */
431
+ }
432
+ }
433
+ catch (e) {
434
+ if (code(e) === 'ENOENT')
435
+ hasJournal = false;
436
+ else
437
+ hasJournal = (await lstatOrUndefined(journal)) !== undefined;
438
+ }
439
+ const stage = token === undefined ? undefined : path.join(this.stagingDir, stageName(name, token));
440
+ const hasDir = (await lstatOrUndefined(dir)) !== undefined;
441
+ const hasOld = (await lstatOrUndefined(old)) !== undefined;
442
+ if (!hasDir && hasOld) {
443
+ await renameRetry(old, dir);
444
+ await fsyncDir(this.root);
445
+ await fsyncDir(this.swapDir);
446
+ }
447
+ else if (!hasDir && hasJournal && stage !== undefined && (await lstatOrUndefined(stage)) !== undefined) {
448
+ await renameRetry(stage, dir);
449
+ await fsyncDir(this.root);
450
+ await fsyncDir(this.stagingDir);
451
+ }
452
+ if (hasJournal) {
453
+ if (hasDir && hasOld)
454
+ await fs.rm(old, { recursive: true, force: true });
455
+ if (stage !== undefined)
456
+ await fs.rm(stage, { recursive: true, force: true });
457
+ await fs.rm(journal, { force: true });
458
+ await fsyncDir(this.swapDir);
459
+ }
460
+ }
461
+ /** A swap of this bucket has begun and not ended (a reader that finds the bucket missing waits for it). */
462
+ async swapPending(name) {
463
+ return (await lstatOrUndefined(this.journalOf(name))) !== undefined;
464
+ }
465
+ /**
466
+ * Run a read of the bucket. A `--batch` swap in progress (or interrupted) is waited for or recovered first, and a
467
+ * read that is cut by a swap (the bucket's directory is another one now, or missing during the swap) is repeated,
468
+ * bounded: a reader sees the old tree or the new one, whatever kind of read it is.
469
+ */
470
+ async reading(name, fn) {
471
+ for (let i = 0;; i++) {
472
+ await this.recoverForRead(name);
473
+ const before = await lstatOrUndefined(this.dirOf(name));
474
+ try {
475
+ return await fn();
476
+ }
477
+ catch (e) {
478
+ const missing = (e instanceof SitefileError && e.code === 'E_NOT_FOUND') || e instanceof BucketRace || code(e) === 'ENOENT' || code(e) === 'ENOTDIR';
479
+ if (i < 8 && missing) {
480
+ const after = await lstatOrUndefined(this.dirOf(name));
481
+ const moved = before !== undefined && (after === undefined || after.ino !== before.ino || after.dev !== before.dev);
482
+ if (moved || (await this.swapPending(name)))
483
+ continue;
484
+ }
485
+ throw e;
486
+ }
487
+ }
488
+ }
489
+ /** What is at the bucket's name: a directory, a link (planted: `rm` may remove it), or nothing. */
490
+ async kindOf(name) {
491
+ const st = await lstatOrUndefined(this.dirOf(name));
492
+ return st === undefined ? undefined : st.isSymbolicLink() ? 'link' : 'dir';
493
+ }
494
+ /** The bucket's directory when it exists as a real directory (never a symbolic link), else `E_NOT_FOUND`. */
495
+ async realDir(name) {
496
+ const dir = this.dirOf(name);
497
+ const st = await lstatOrUndefined(dir);
498
+ if (st === undefined)
499
+ throw new SitefileError('E_NOT_FOUND', `no such bucket: ${name}`);
500
+ if (st.isSymbolicLink())
501
+ throw symlinkError(`bucket '${name}'`);
502
+ if (!st.isDirectory())
503
+ throw new SitefileError('E_STORE', `bucket '${name}' is not a directory`);
504
+ return dir;
505
+ }
506
+ /**
507
+ * The directory at `segs` below the bucket, each component checked with `lstat`: a symbolic link anywhere on
508
+ * the way is refused. A component is found by its NFC spelling, as the readers do.
509
+ */
510
+ resolveDirectory(name, segs) {
511
+ return this.reading(name, () => this.resolveDir(name, segs));
512
+ }
513
+ async resolveDir(name, segs) {
514
+ let cur = await this.realDir(name);
515
+ for (let i = 0; i < segs.length; i++) {
516
+ const seg = segs[i];
517
+ const hit = (await fs.readdir(cur)).find((e) => nfc(e) === seg);
518
+ if (hit === undefined)
519
+ throw new SitefileError('E_NOT_FOUND', `no such path in bucket '${name}': ${shownPath(segs.slice(0, i + 1))}`);
520
+ const next = path.join(cur, hit);
521
+ const st = await fs.lstat(next);
522
+ if (st.isSymbolicLink())
523
+ throw symlinkError(`'${bucketPathOf(name, segs.slice(0, i + 1))}'`);
524
+ if (!st.isDirectory())
525
+ throw new SitefileError('E_NOT_FOUND', `'${bucketPathOf(name, segs.slice(0, i + 1))}' is not a directory`);
526
+ cur = next;
527
+ }
528
+ return cur;
529
+ }
530
+ // -------------------------------------------------------- create, list, remove
531
+ async create(name) {
532
+ this.dirOf(name);
533
+ await fs.mkdir(this.root, { recursive: true, mode: 0o700 });
534
+ await this.store.withLock(async () => {
535
+ await this.recoverLocked(name);
536
+ await this.sweepScratch();
537
+ if ((await lstatOrUndefined(this.dirOf(name))) !== undefined)
538
+ throw new SitefileError('E_CONFLICT', `bucket '${name}' already exists`);
539
+ await fs.mkdir(path.join(this.root, '.meta'), { recursive: true, mode: 0o700 });
540
+ await fs.mkdir(this.dirOf(name), { mode: 0o755 });
541
+ const tmp = await this.scratch(this.tmpDir);
542
+ await fs.writeFile(tmp, JSON.stringify({ created: new Date().toISOString() }) + '\n', { mode: 0o600 });
543
+ await fs.rename(tmp, this.metaFile(name));
544
+ });
545
+ }
546
+ /**
547
+ * Delete the scratch files an interrupted write left (older than an hour). The caller holds the lock, and has
548
+ * recovered the bucket it works on: only `.tmp` and `.staging` are swept, never `.swap`, where a swap in progress
549
+ * keeps the tree it displaced.
550
+ */
551
+ async sweepScratch() {
552
+ // Every journaled bucket is recovered first (a staged tree may be the only copy of one that is waiting to roll
553
+ // forward), and whatever a journal still names is never swept, even when its bucket cannot be recovered now.
554
+ const named = new Set();
555
+ for (const j of await fs.readdir(this.swapDir).catch(() => [])) {
556
+ if (!j.endsWith('.json') || !isBucketName(j.slice(0, -5)))
557
+ continue;
558
+ const n = j.slice(0, -5);
559
+ try {
560
+ await this.recoverLocked(n);
561
+ }
562
+ catch {
563
+ /* its journal and staged tree stay, and are protected below */
564
+ }
565
+ const token = await this.journalToken(n);
566
+ if (token !== undefined)
567
+ named.add(stageName(n, token));
568
+ }
569
+ for (const d of [this.tmpDir, this.stagingDir]) {
570
+ for (const n of await fs.readdir(d).catch(() => [])) {
571
+ if (d === this.stagingDir && named.has(n))
572
+ continue;
573
+ const st = await lstatOrUndefined(path.join(d, n));
574
+ if (!st || Date.now() - st.mtimeMs <= 3_600_000)
575
+ continue;
576
+ // Best effort, per entry: a leftover that cannot be removed (permissions, a busy file) is reported once and left,
577
+ // it must not stop every writer of every bucket from then on.
578
+ try {
579
+ await fs.rm(path.join(d, n), { recursive: true, force: true });
580
+ }
581
+ catch (e) {
582
+ warnOnce(`cannot remove the old scratch entry '${path.join(d, n)}': ${e.message}; it is left in place`);
583
+ }
584
+ }
585
+ }
586
+ }
587
+ /** The token a journal names, if it names one: data, never a path. */
588
+ async journalToken(name) {
589
+ try {
590
+ const bytes = await fs.readFile(this.journalOf(name));
591
+ const t = JSON.parse(new TextDecoder('utf-8').decode(bytes))?.token;
592
+ return typeof t === 'string' && STAGE_TOKEN.test(t) ? t : undefined;
593
+ }
594
+ catch {
595
+ return undefined;
596
+ }
597
+ }
598
+ async createdOf(name) {
599
+ try {
600
+ const j = JSON.parse(await fs.readFile(this.metaFile(name), 'utf8'));
601
+ if (typeof j.created === 'string')
602
+ return j.created;
603
+ }
604
+ catch {
605
+ /* fall through */
606
+ }
607
+ return (await fs.stat(this.dirOf(name))).mtime.toISOString();
608
+ }
609
+ async stats(name) {
610
+ return this.reading(name, async () => {
611
+ const entries = await scanDirectory(await this.realDir(name), name, []);
612
+ return { files: entries.length, size: entries.reduce((n, e) => n + e.size, 0) };
613
+ });
614
+ }
615
+ /** Every bucket; one that cannot be read (a link planted in it) carries a `problem` and the others are listed all the same. */
616
+ async list() {
617
+ const out = [];
618
+ const problem = (name, e) => {
619
+ out.push({ name, created: '', files: 0, size: 0, problem: e instanceof SitefileError ? e.message : e.message });
620
+ };
621
+ // A swap entry is recovered like a read would; one that cannot be (or whose name is no bucket name) is a problem of
622
+ // its own, not of the listing.
623
+ for (const j of await fs.readdir(this.swapDir).catch(() => [])) {
624
+ const base = j.endsWith('.json') ? j.slice(0, -5) : j.endsWith('.old') ? j.slice(0, -4) : '';
625
+ if (base === '')
626
+ continue;
627
+ if (!isBucketName(base)) {
628
+ problem(j, new SitefileError('E_STORE', `the swap entry '${j.length > 80 ? `${j.slice(0, 77)}...` : j}' does not name a bucket: remove it by hand from ${this.swapDir}`));
629
+ continue;
630
+ }
631
+ try {
632
+ await this.recoverForRead(base);
633
+ }
634
+ catch (e) {
635
+ problem(base, new SitefileError('E_STORE', `bucket '${base}' cannot be recovered from an interrupted swap: ${e.message}`));
636
+ }
637
+ }
638
+ for (const n of (await fs.readdir(this.root).catch(() => [])).sort(byName)) {
639
+ if (n.startsWith('.') || !isBucketName(n))
640
+ continue;
641
+ if (out.some((x) => x.name === n))
642
+ continue;
643
+ const st = await lstatOrUndefined(path.join(this.root, n));
644
+ if (!st?.isDirectory())
645
+ continue;
646
+ const created = await this.createdOf(n);
647
+ try {
648
+ const { files, size } = await this.stats(n);
649
+ out.push({ name: n, created, files, size });
650
+ }
651
+ catch (e) {
652
+ if (!(e instanceof SitefileError) || (e.code !== 'E_PATH_ESCAPE' && e.code !== 'E_HARDLINK'))
653
+ throw e;
654
+ out.push({ name: n, created, files: 0, size: 0, problem: e.message });
655
+ }
656
+ }
657
+ return out.sort((a, b) => byName(a.name, b.name));
658
+ }
659
+ /** Remove a bucket. The caller has already refused what should be refused (files, running servers). */
660
+ async remove(name) {
661
+ await this.store.withLock(async () => {
662
+ await this.recoverLocked(name);
663
+ const dir = this.dirOf(name);
664
+ const st = await lstatOrUndefined(dir);
665
+ if (st === undefined)
666
+ throw new SitefileError('E_NOT_FOUND', `no such bucket: ${name}`);
667
+ // A directory, or a link planted where the bucket should be: the link itself is removed, never its target.
668
+ if (!st.isSymbolicLink() && !st.isDirectory())
669
+ throw new SitefileError('E_STORE', `bucket '${name}' is not a directory`);
670
+ // First everything that could bring the bucket back: its displaced tree, its journal and its staged trees,
671
+ // durably. A crash from here on leaves the bucket (harmless) or nothing, never an `.old` to be put back.
672
+ await fs.rm(this.oldOf(name), { recursive: true, force: true });
673
+ await fs.rm(this.journalOf(name), { force: true });
674
+ for (const n of await fs.readdir(this.stagingDir).catch(() => [])) {
675
+ if (n.startsWith(`${name}.`) && STAGE_TOKEN.test(n.slice(name.length + 1)))
676
+ await fs.rm(path.join(this.stagingDir, n), { recursive: true, force: true });
677
+ }
678
+ await fsyncDir(this.swapDir).catch(async (e) => {
679
+ if ((await lstatOrUndefined(this.swapDir)) !== undefined)
680
+ throw e;
681
+ });
682
+ bucketHooks.crash?.('rm-cleaned');
683
+ let gone;
684
+ if (st.isSymbolicLink()) {
685
+ try {
686
+ await fs.unlink(dir);
687
+ }
688
+ catch (e) {
689
+ if (!['EPERM', 'EISDIR'].includes(code(e) ?? ''))
690
+ throw e;
691
+ await fs.rmdir(dir); // a directory link on Windows
692
+ }
693
+ }
694
+ else {
695
+ gone = await this.scratch(this.tmpDir);
696
+ await fs.rename(dir, gone); // out of sight at once, then deleted
697
+ }
698
+ // From here the bucket is gone: what goes wrong now is a leftover, and the error says so.
699
+ const left = (what, e) => new SitefileError('E_STORE', `bucket '${name}' IS removed, but ${what}: ${e.message}`, undefined, { cause: e });
700
+ try {
701
+ await fsyncDir(this.root);
702
+ bucketHooks.crash?.('rm-displaced');
703
+ }
704
+ catch (e) {
705
+ if (e instanceof SwapCrash)
706
+ throw e;
707
+ throw left('the removal may not be durable yet (the parent directory could not be flushed)', e);
708
+ }
709
+ try {
710
+ await fs.rm(this.metaFile(name), { force: true });
711
+ }
712
+ catch (e) {
713
+ throw left(`its metadata file '${this.metaFile(name)}' is left behind (delete it by hand)`, e);
714
+ }
715
+ if (gone !== undefined) {
716
+ try {
717
+ await fs.rm(gone, { recursive: true, force: true });
718
+ }
719
+ catch (e) {
720
+ throw left(`its files are left in '${gone}' (delete that directory by hand; a later write sweeps it after an hour)`, e);
721
+ }
722
+ }
723
+ });
724
+ }
725
+ // -------------------------------------------------------- reading
726
+ /** The files under `prefix` (a directory, or a single file), without their contents. */
727
+ listFiles(name, prefix) {
728
+ return this.reading(name, async () => {
729
+ const dir = await this.realDir(name);
730
+ if (prefix.length === 0)
731
+ return scanDirectory(dir, name, []);
732
+ const parent = await this.resolveDir(name, prefix.slice(0, -1));
733
+ const last = prefix[prefix.length - 1];
734
+ const hit = (await fs.readdir(parent)).find((e) => nfc(e) === last);
735
+ const shown = `'${bucketPathOf(name, prefix)}'`;
736
+ if (hit === undefined)
737
+ throw new SitefileError('E_NOT_FOUND', `no such path in bucket '${name}': ${shownPath(prefix)}`);
738
+ const file = path.join(parent, hit);
739
+ const st = await fs.lstat(file);
740
+ if (st.isSymbolicLink())
741
+ throw new SitefileError('E_PATH_ESCAPE', linkSentence(name, shownPath(prefix)));
742
+ if (st.isFile()) {
743
+ if (st.nlink > 1)
744
+ throw new SitefileError('E_HARDLINK', linkSentence(name, shownPath(prefix)));
745
+ return [{ path: shownPath(prefix), size: st.size, mode: modeOf(st), file, st, stamp: stampOf(st) }];
746
+ }
747
+ if (!st.isDirectory())
748
+ throw specialError(shown);
749
+ return (await scanDirectory(file, name, prefix)).map((e) => ({ ...e, path: shownPath(prefix) + e.path }));
750
+ });
751
+ }
752
+ /** One file's bytes, with the sandbox rules of every read. */
753
+ get(name, segs) {
754
+ return this.reading(name, async () => {
755
+ const shown = `'${bucketPathOf(name, segs)}'`;
756
+ const parent = await this.resolveDir(name, segs.slice(0, -1));
757
+ const last = segs[segs.length - 1];
758
+ const hit = (await fs.readdir(parent)).find((e) => nfc(e) === last);
759
+ if (hit === undefined)
760
+ throw new SitefileError('E_NOT_FOUND', `no such file in bucket '${name}': ${shownPath(segs)}`);
761
+ const file = path.join(parent, hit);
762
+ const st = await fs.lstat(file);
763
+ if (st.isDirectory())
764
+ throw new SitefileError('E_UNSUPPORTED_FILE', `${shown} is a directory, not a file`);
765
+ return readRegular(file, st, shown);
766
+ });
767
+ }
768
+ /**
769
+ * The tree of a bucket (or of a directory `prefix` of it, re-rooted): every file, hidden ones too, read through
770
+ * the sandbox. The origin of its files is `bucket:<name>`.
771
+ *
772
+ * Listing is by `lstat`; only files whose stamp (size, mtime, ctime, inode) differs from `o.cache` are read, and the
773
+ * others are the very nodes of the last load, so a reload holds the changed files once, not the bucket twice. The
774
+ * cache is replaced by the files of this load. More than `o.maxBytes` (default {@link DEFAULT_LOAD_MAX_BYTES}) is
775
+ * `E_TOO_LARGE` before any byte is read. `o.locked`: the caller holds the store lock (no recovery is attempted).
776
+ */
777
+ async loadTree(name, prefix = [], o = {}) {
778
+ const once = async () => {
779
+ for (let attempt = 0;; attempt++) {
780
+ try {
781
+ return await this.loadOnce(name, prefix, o);
782
+ }
783
+ catch (e) {
784
+ if (e instanceof BucketRace && attempt < 5)
785
+ continue; // a file changed under us: look again
786
+ throw e;
787
+ }
788
+ }
789
+ };
790
+ return o.locked ? once() : this.reading(name, once);
791
+ }
792
+ async loadOnce(name, prefix, o) {
793
+ const dir = await this.resolveDir(name, prefix);
794
+ const entries = await scanDirectory(dir, name, prefix);
795
+ const limit = o.maxBytes ?? DEFAULT_LOAD_MAX_BYTES;
796
+ const total = entries.reduce((n, e) => n + e.size, 0);
797
+ if (total > limit)
798
+ throw new SitefileError('E_TOO_LARGE', `bucket:${name}${prefix.length > 0 ? `/${prefix.join('/')}` : ''} holds ${total} bytes, more than the limit of ${limit} (--max-bytes raises it)`);
799
+ const origin = `bucket:${name}`;
800
+ const next = new Map();
801
+ for (const e of entries) {
802
+ const cached = o.cache?.get(e.path);
803
+ if (cached !== undefined && cached.stamp === e.stamp) {
804
+ next.set(e.path, cached);
805
+ continue;
806
+ }
807
+ const f = await readEntry(e, `'${origin}${shownPath([...prefix, ...e.path.slice(1).split('/')])}'`);
808
+ next.set(e.path, { stamp: e.stamp, node: makeFile(f.bytes, origin, f.mode) });
809
+ }
810
+ const tree = Tree.empty.withFiles([...next].map(([p, v]) => [p, v.node]), 'error');
811
+ if (o.cache) {
812
+ o.cache.clear();
813
+ for (const [p, v] of next)
814
+ o.cache.set(p, v);
815
+ }
816
+ return tree;
817
+ }
818
+ // -------------------------------------------------------- writing
819
+ /**
820
+ * Put one file. `source` yields its bytes (stdin, a file); it is staged in `.tmp` first (so a failed or
821
+ * oversized transfer changes nothing) and renamed into place under the lock.
822
+ */
823
+ async putFile(name, segs, source, mode, maxBytes) {
824
+ this.dirOf(name);
825
+ await this.recover(name);
826
+ await this.realDir(name);
827
+ await fs.mkdir(this.root, { recursive: true, mode: 0o700 });
828
+ const tmp = await this.scratch(this.tmpDir);
829
+ const hash = createHash('sha256');
830
+ let size = 0;
831
+ const fh = await fs.open(tmp, 'wx', 0o600);
832
+ try {
833
+ for await (const chunk of source) {
834
+ size += chunk.byteLength;
835
+ if (size > maxBytes)
836
+ throw new SitefileError('E_TOO_LARGE', `the input is larger than the limit of ${maxBytes} bytes (--max-bytes raises it)`);
837
+ hash.update(chunk);
838
+ await fh.write(chunk);
839
+ }
840
+ await fh.close();
841
+ await fs.chmod(tmp, mode & 0o111 ? 0o755 : 0o644);
842
+ const digest = `sha256:${hash.digest('hex')}`;
843
+ const result = await this.store.withLock(async () => {
844
+ await this.recoverLocked(name);
845
+ return this.place(name, segs, tmp, digest, size, mode & 0o111 ? 0o755 : 0o644);
846
+ });
847
+ return { result, size };
848
+ }
849
+ catch (e) {
850
+ await fh.close().catch(() => undefined);
851
+ throw e;
852
+ }
853
+ finally {
854
+ await fs.rm(tmp, { force: true });
855
+ }
856
+ }
857
+ /** The directory that will hold `segs`' last segment, created as needed, every step checked. The caller holds the lock. */
858
+ async prepareParent(name, segs, create) {
859
+ let cur = await this.realDir(name);
860
+ for (let i = 0; i < segs.length - 1; i++) {
861
+ const seg = segs[i];
862
+ const entries = await fs.readdir(cur);
863
+ const hit = this.matchEntry(entries, seg, segs, i);
864
+ if (hit === undefined) {
865
+ if (!create)
866
+ throw new SitefileError('E_NOT_FOUND', `no such path in bucket '${name}': ${shownPath(segs.slice(0, i + 1))}`);
867
+ cur = path.join(cur, seg);
868
+ await fs.mkdir(cur, { mode: 0o755 });
869
+ continue;
870
+ }
871
+ const next = path.join(cur, hit);
872
+ const st = await fs.lstat(next);
873
+ if (st.isSymbolicLink())
874
+ throw symlinkError(`'${bucketPathOf(name, segs.slice(0, i + 1))}'`);
875
+ if (!st.isDirectory())
876
+ throw new SitefileError('E_CONFLICT', `cannot write '${shownPath(segs)}': '${shownPath(segs.slice(0, i + 1))}' is a file`);
877
+ cur = next;
878
+ }
879
+ return cur;
880
+ }
881
+ /** The on-disk name of `seg` among `entries` (the same NFC name), `undefined` when absent; a name that differs only in case is `E_PATH_COLLISION`. */
882
+ matchEntry(entries, seg, segs, i) {
883
+ const exact = entries.find((e) => nfc(e) === seg);
884
+ if (exact !== undefined)
885
+ return exact;
886
+ const folded = foldCase(seg);
887
+ const other = entries.find((e) => foldCase(nfc(e)) === folded);
888
+ if (other !== undefined) {
889
+ throw new SitefileError('E_PATH_COLLISION', `'${shownPath(segs.slice(0, i + 1))}' differs only in case from '${shownPath([...segs.slice(0, i), nfc(other)])}'; case-insensitive file systems cannot hold both`);
890
+ }
891
+ return undefined;
892
+ }
893
+ /** Move the staged file `tmp` to `segs`: the one rename that makes it visible. The caller holds the lock. */
894
+ async place(name, segs, tmp, digest, size, mode) {
895
+ const parent = await this.prepareParent(name, segs, true);
896
+ const last = segs[segs.length - 1];
897
+ const hit = this.matchEntry(await fs.readdir(parent), last, segs, segs.length - 1);
898
+ const dest = path.join(parent, hit ?? last);
899
+ const st = hit === undefined ? undefined : await fs.lstat(dest);
900
+ let result = 'created';
901
+ if (st !== undefined) {
902
+ const shown = `'${bucketPathOf(name, segs)}'`;
903
+ if (st.isSymbolicLink())
904
+ throw symlinkError(shown);
905
+ if (st.isDirectory())
906
+ throw new SitefileError('E_CONFLICT', `cannot write '${shownPath(segs)}': it is a directory`);
907
+ if (!st.isFile())
908
+ throw specialError(shown);
909
+ result = 'replaced';
910
+ if (st.size === size && modeOf(st) === mode && st.nlink === 1) {
911
+ const have = await readRegular(dest, st, shown).catch(() => undefined);
912
+ if (have !== undefined && sha256(have.bytes) === digest)
913
+ return 'unchanged';
914
+ }
915
+ }
916
+ await renameRetry(tmp, dest);
917
+ return result;
918
+ }
919
+ /**
920
+ * Apply a bulk change. By default each file is written atomically on its own; with `batch` the whole
921
+ * resulting tree is built beside the bucket and swapped in (see {@link recover}), so a reader sees all of the
922
+ * change or none of it. **Nothing is written** when a conflict is found, and every conflict is found first: a file
923
+ * that would replace different content without `overwrite`, a file where a directory is (an empty one too), a name
924
+ * that differs only in case from a file or an empty directory, a file where a directory has to be. Existing files
925
+ * are listed by `lstat` and read only when a write names the same path, so the bucket is not held in memory.
926
+ */
927
+ async apply(name, change, o) {
928
+ return this.store.withLock(async () => {
929
+ await this.recoverLocked(name);
930
+ await this.sweepScratch();
931
+ const dir = await this.realDir(name);
932
+ const dirs = [];
933
+ const entries = await scanDirectory(dir, name, [], { dirs });
934
+ const existing = new Map(entries.map((e) => [e.path, e]));
935
+ const changing = [];
936
+ let unchanged = 0;
937
+ for (const [p, node] of change.writes) {
938
+ const have = existing.get(p);
939
+ if (have === undefined)
940
+ changing.push([p, node]);
941
+ else {
942
+ const same = have.size === node.bytes.byteLength && have.mode === node.mode && sha256((await readEntry(have, `'bucket:${name}${p}'`)).bytes) === node.digest;
943
+ if (same)
944
+ unchanged++;
945
+ else if (!o.overwrite)
946
+ throw new SitefileError('E_CONFLICT', `'${p}' in bucket '${name}' already holds different content; use --overwrite to replace it`);
947
+ else
948
+ changing.push([p, node]);
949
+ }
950
+ }
951
+ // Directories count too: an empty one is no file, but a file cannot take its place, nor differ from it only in case.
952
+ const dirAt = new Set(dirs);
953
+ const dirFold = new Map(dirs.map((d) => [foldPath(d), d]));
954
+ for (const [p] of changing) {
955
+ if (dirAt.has(p))
956
+ throw new SitefileError('E_CONFLICT', `cannot write '${p}': it is a directory`);
957
+ const segs = p.slice(1).split('/');
958
+ for (let i = 0; i < segs.length; i++) {
959
+ const q = `/${segs.slice(0, i + 1).join('/')}`;
960
+ const other = dirFold.get(foldPath(q));
961
+ if (other !== undefined && other !== q)
962
+ throw new SitefileError('E_PATH_COLLISION', `'${q}' differs only in case from '${other}'; case-insensitive file systems cannot hold both`);
963
+ }
964
+ }
965
+ // Path conflicts among files (a file where a directory is, names that differ only in case) too.
966
+ Tree.empty.withFiles(entries.map((e) => [e.path, makeFile(EMPTY, `bucket:${name}`, e.mode)]), 'error').withFiles(changing, 'overwrite');
967
+ const kept = new Set(change.writes.map(([p]) => p));
968
+ const removes = change.deleteOthers ? entries.map((e) => e.path).filter((p) => !kept.has(p)) : [];
969
+ if (o.batch)
970
+ await this.swapIn(name, dir, entries, changing, removes);
971
+ else {
972
+ for (const [p, node] of changing) {
973
+ const segs = checkBucketPath(p.slice(1));
974
+ const tmp = await this.scratch(this.tmpDir);
975
+ try {
976
+ await fs.writeFile(tmp, node.bytes, { mode: 0o600 });
977
+ await fs.chmod(tmp, node.mode);
978
+ await this.place(name, segs, tmp, node.digest, node.bytes.byteLength, node.mode);
979
+ }
980
+ finally {
981
+ await fs.rm(tmp, { force: true });
982
+ }
983
+ }
984
+ for (const p of removes)
985
+ await this.removeLocked(name, checkBucketPath(p.slice(1)), false);
986
+ }
987
+ return { written: changing.length, unchanged, removed: removes.length };
988
+ });
989
+ }
990
+ /**
991
+ * Build the new tree in `.staging` (unchanged files are copied from the bucket, changed ones written) and swap it
992
+ * for the bucket directory: journal, displace, place, unjournal. The caller holds the lock. Empty directories are
993
+ * not carried over (a tree has none).
994
+ */
995
+ async swapIn(name, dir, entries, changing, removes) {
996
+ const token = randomBytes(16).toString('hex'); // the operating system's random source
997
+ await fs.mkdir(this.stagingDir, { recursive: true, mode: 0o700 });
998
+ const stage = path.join(this.stagingDir, stageName(name, token));
999
+ await fs.mkdir(stage, { mode: 0o755 });
1000
+ let crashed = false;
1001
+ let journaled = false;
1002
+ let displaced = false;
1003
+ let placed = false;
1004
+ try {
1005
+ const drop = new Set(removes);
1006
+ const replaced = new Set(changing.map(([p]) => p));
1007
+ const at = (p) => path.join(stage, ...p.slice(1).split('/'));
1008
+ for (const e of entries) {
1009
+ if (drop.has(e.path) || replaced.has(e.path))
1010
+ continue;
1011
+ // Unchanged files are copied through the one guarded read (no link followed, no FIFO opened, same file as listed).
1012
+ const f = await readEntry(e, `'bucket:${name}${e.path}'`);
1013
+ await fs.mkdir(path.dirname(at(e.path)), { recursive: true, mode: 0o755 });
1014
+ await writeStaged(at(e.path), f.bytes, e.mode);
1015
+ }
1016
+ for (const [p, node] of changing) {
1017
+ await fs.mkdir(path.dirname(at(p)), { recursive: true, mode: 0o755 });
1018
+ await writeStaged(at(p), node.bytes, node.mode);
1019
+ }
1020
+ await fsyncTree(stage);
1021
+ await fsyncDir(this.stagingDir);
1022
+ const old = this.oldOf(name);
1023
+ const journal = this.journalOf(name);
1024
+ await fs.mkdir(this.swapDir, { recursive: true, mode: 0o700 });
1025
+ // Recovery has run and the bucket directory is there, so a `.old` is the leftover of a finished swap: this
1026
+ // successful swap is what removes it (never create, never a sweep).
1027
+ await fs.rm(old, { recursive: true, force: true });
1028
+ const jt = await this.scratch(this.tmpDir);
1029
+ const jh = await fs.open(jt, 'wx', 0o600);
1030
+ try {
1031
+ await jh.writeFile(JSON.stringify({ token }) + '\n');
1032
+ await jh.sync();
1033
+ }
1034
+ finally {
1035
+ await jh.close();
1036
+ }
1037
+ await fs.rename(jt, journal);
1038
+ journaled = true;
1039
+ await fsyncDir(this.swapDir);
1040
+ bucketHooks.crash?.('swap-journal');
1041
+ try {
1042
+ await renameRetry(dir, old);
1043
+ }
1044
+ catch (e) {
1045
+ await fs.rm(journal, { force: true });
1046
+ throw e;
1047
+ }
1048
+ displaced = true;
1049
+ await fsyncDir(this.root);
1050
+ await fsyncDir(this.swapDir);
1051
+ bucketHooks.crash?.('swap-displaced');
1052
+ try {
1053
+ await renameRetry(stage, dir);
1054
+ }
1055
+ catch (e) {
1056
+ await renameRetry(old, dir); // put the old tree back (the journal stays until it is)
1057
+ await fsyncDir(this.root);
1058
+ await fsyncDir(this.swapDir);
1059
+ await fs.rm(journal, { force: true });
1060
+ throw e;
1061
+ }
1062
+ placed = true;
1063
+ await fsyncDir(this.root);
1064
+ await fsyncDir(this.stagingDir);
1065
+ bucketHooks.crash?.('swap-placed');
1066
+ await fs.rm(journal, { force: true });
1067
+ await fsyncDir(this.swapDir);
1068
+ await fs.rm(old, { recursive: true, force: true });
1069
+ }
1070
+ catch (e) {
1071
+ if (e instanceof SwapCrash)
1072
+ crashed = true;
1073
+ else if (journaled && !placed) {
1074
+ // A flush or a rename failed before the new tree was in place: leave the bucket as it was, journal and all gone.
1075
+ if (displaced && (await lstatOrUndefined(dir)) === undefined)
1076
+ await renameRetry(this.oldOf(name), dir);
1077
+ await fs.rm(this.journalOf(name), { force: true });
1078
+ }
1079
+ throw e;
1080
+ }
1081
+ finally {
1082
+ if (!crashed)
1083
+ await fs.rm(stage, { recursive: true, force: true });
1084
+ }
1085
+ }
1086
+ /** Remove a file, or (with `recursive`) a directory and everything in it; empty parents go too. */
1087
+ async removePath(name, segs, recursive) {
1088
+ await this.store.withLock(async () => {
1089
+ await this.recoverLocked(name);
1090
+ await this.removeLocked(name, segs, recursive);
1091
+ });
1092
+ }
1093
+ async removeLocked(name, segs, recursive) {
1094
+ const parent = await this.prepareParent(name, segs, false);
1095
+ const last = segs[segs.length - 1];
1096
+ const hit = (await fs.readdir(parent)).find((e) => nfc(e) === last);
1097
+ if (hit === undefined)
1098
+ throw new SitefileError('E_NOT_FOUND', `no such path in bucket '${name}': ${shownPath(segs)}`);
1099
+ const target = path.join(parent, hit);
1100
+ const st = await fs.lstat(target);
1101
+ if (st.isDirectory()) {
1102
+ if (!recursive)
1103
+ throw new SitefileError('E_USAGE', `'${bucketPathOf(name, segs)}' is a directory; use -r to remove it and everything in it`);
1104
+ await fs.rm(target, { recursive: true });
1105
+ }
1106
+ else
1107
+ await fs.unlink(target); // a file, or a link: the link itself, never what it points at
1108
+ // Directories that became empty are not kept (a tree has no empty directories).
1109
+ const root = await this.realDir(name);
1110
+ for (let cur = parent; cur !== root; cur = path.dirname(cur)) {
1111
+ if ((await fs.readdir(cur)).length > 0)
1112
+ break;
1113
+ await fs.rmdir(cur);
1114
+ }
1115
+ }
1116
+ }
1117
+ /** Rename, retrying briefly where Windows refuses while a reader has a file open (the same on every rename of a swap, rollback included). */
1118
+ async function renameRetry(from, to) {
1119
+ for (let i = 0;; i++) {
1120
+ try {
1121
+ return await fs.rename(from, to);
1122
+ }
1123
+ catch (e) {
1124
+ if (i >= 20 || process.platform !== 'win32' || !['EPERM', 'EBUSY', 'EACCES'].includes(code(e) ?? ''))
1125
+ throw e;
1126
+ await new Promise((r) => setTimeout(r, 25 + Math.random() * 25));
1127
+ }
1128
+ }
1129
+ }
1130
+ //# sourceMappingURL=bucket.js.map