@nordhavnhq/beacon 0.7.0 → 0.8.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.
@@ -5,84 +5,219 @@ var fs = require('fs');
5
5
  var path = require('path');
6
6
 
7
7
  // src/file-store.ts
8
+
9
+ // src/file-cache.ts
10
+ var ATTACH = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-cache-attach/3");
8
11
  var SUFFIX = ".json";
9
12
  var CACHE_FILE = /^[0-9a-f]{64}\.json$/;
10
13
  var TEMP_FILE = /^[0-9a-f]{64}\.json\.\d+(\.[0-9a-f]+)?\.tmp$/;
14
+ var FOLDER = /^[0-9a-f]{16}$/;
15
+ var MARKER = ".beacon-cache";
16
+ var MARKER_TEXT = "A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\n";
11
17
  var TEMP_ORPHAN_MS = 6e4;
12
- var FileCacheStore = class {
13
- constructor(options) {
18
+ var STALE_MS = 30 * 24 * 36e5;
19
+ var TOUCH_MS = 24 * 36e5;
20
+ var FileCache = class {
21
+ constructor(options, deps) {
14
22
  /** Same order contract as `MemoryCacheStore`: oldest written first. */
15
23
  this.map = /* @__PURE__ */ new Map();
24
+ /** Read from disk on first use, not at construction: a client attaching first decides where from. */
25
+ this.loaded = false;
26
+ this.touchedAt = 0;
27
+ /** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */
28
+ this.warnTo = (...args) => console.warn(...args);
16
29
  if (!options?.dir) throw new Error("FileCacheStore: `dir` is required");
17
30
  this.dir = options.dir;
31
+ this.folder = options.dir;
18
32
  this.maxEntries = options.maxEntries ?? 500;
33
+ this.deps = deps;
19
34
  let warned = false;
20
35
  this.onError = options.onError ?? ((err) => {
21
36
  if (warned) return;
22
37
  warned = true;
23
- console.warn(`[@nordhavnhq/beacon] file cache at ${this.dir} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
38
+ this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
24
39
  });
25
- this.load();
40
+ this.ownWarning = options.onError === void 0;
26
41
  }
27
42
  get(key) {
43
+ this.ensureLoaded();
44
+ this.touch();
28
45
  return this.map.get(key);
29
46
  }
30
47
  set(key, entry) {
48
+ this.ensureLoaded();
31
49
  this.map.delete(key);
32
50
  this.map.set(key, entry);
33
51
  this.write(key, entry);
34
- while (this.map.size > this.maxEntries) {
35
- const oldest = this.map.keys().next().value;
36
- if (oldest === void 0) break;
37
- this.delete(oldest);
38
- }
52
+ this.evict();
39
53
  }
40
54
  delete(key) {
55
+ this.ensureLoaded();
41
56
  this.map.delete(key);
42
57
  this.remove(this.fileOf(key));
43
58
  }
44
59
  keys() {
60
+ this.ensureLoaded();
45
61
  return this.map.keys();
46
62
  }
47
63
  clear() {
64
+ this.ensureLoaded();
48
65
  this.map.clear();
49
- for (const name of this.list()) {
50
- if (CACHE_FILE.test(name)) this.remove(path.join(this.dir, name));
66
+ for (const name of this.list(this.folder)) {
67
+ if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name));
68
+ }
69
+ }
70
+ /**
71
+ * Moves the store into its folder (`<dir>/<hash>`) and reads that; copies
72
+ * the cache files of 0.7 in when asked and the folder is empty; then clears
73
+ * out folders of this store that went unused (`sweep`). Entries already
74
+ * read from `dir` itself are dropped from memory. A second client with the
75
+ * same identity finds it done; one with another identity is refused, as the
76
+ * store holds one site's entries.
77
+ */
78
+ [ATTACH](scope) {
79
+ const hash = this.deps.sha256(scope.identity).slice(0, 16);
80
+ if (this.hash !== void 0) {
81
+ return this.hash === hash && this.attached ? { ...this.attached, first: false } : void 0;
51
82
  }
83
+ if (this.ownWarning) this.warnTo = scope.warn;
84
+ this.hash = hash;
85
+ this.folder = this.deps.join(this.dir, hash);
86
+ this.map.clear();
87
+ this.loaded = false;
88
+ this.ensureLoaded();
89
+ this.mark();
90
+ const legacy = this.legacyFiles();
91
+ const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0;
92
+ this.sweep();
93
+ this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true };
94
+ return this.attached;
52
95
  }
53
96
  // ── Disk ────────────────────────────────────────────────────────────────────
54
97
  /** File name per key: a hash, as keys hold `/` and `:` and may be long. */
55
- fileOf(key) {
56
- return path.join(this.dir, crypto.createHash("sha256").update(key).digest("hex") + SUFFIX);
98
+ fileOf(key, folder = this.folder) {
99
+ return this.deps.join(folder, this.deps.sha256(key) + SUFFIX);
100
+ }
101
+ ensureLoaded() {
102
+ if (this.loaded) return;
103
+ this.loaded = true;
104
+ this.load();
57
105
  }
58
106
  /** Fills memory from disk, oldest file first so eviction order survives a restart. */
59
107
  load() {
60
108
  try {
61
- fs.mkdirSync(this.dir, { recursive: true });
109
+ this.deps.fs.mkdirSync(this.folder, { recursive: true });
62
110
  } catch (err) {
63
111
  this.fail(err);
64
112
  return;
65
113
  }
66
- const found = [];
67
- for (const name of this.list()) {
68
- const file = path.join(this.dir, name);
114
+ for (const name of this.list(this.folder)) {
69
115
  if (TEMP_FILE.test(name)) {
70
- if (this.orphaned(file)) this.remove(file);
71
- continue;
116
+ const file = this.deps.join(this.folder, name);
117
+ if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file);
72
118
  }
119
+ }
120
+ const found = this.readEntries(this.folder, (file) => this.remove(file));
121
+ for (const { key, entry } of found) this.map.set(key, entry);
122
+ this.evict();
123
+ }
124
+ /**
125
+ * The readable cache files in `folder`, oldest first. Files that are this
126
+ * store's by name but not a cache entry (half written, filed under another
127
+ * key) go to `bad`; anything else in `folder` is not looked at.
128
+ */
129
+ readEntries(folder, bad) {
130
+ const { fs } = this.deps;
131
+ const found = [];
132
+ for (const name of this.list(folder)) {
73
133
  if (!CACHE_FILE.test(name)) continue;
134
+ const file = this.deps.join(folder, name);
74
135
  try {
75
136
  const stored = JSON.parse(fs.readFileSync(file, "utf8"));
76
- if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key)) {
137
+ if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key, folder)) {
77
138
  throw new Error("not a cache file");
78
139
  }
79
140
  found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs });
80
141
  } catch {
81
- this.remove(file);
142
+ bad(file);
82
143
  }
83
144
  }
84
- found.sort((a, b) => a.mtime - b.mtime);
85
- for (const { key, entry } of found) this.map.set(key, entry);
145
+ return found.sort((a, b) => a.mtime - b.mtime);
146
+ }
147
+ /** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */
148
+ legacyFiles() {
149
+ return this.readEntries(this.dir, () => {
150
+ });
151
+ }
152
+ /**
153
+ * Copies the cache files of 0.7 into the (empty) folder, the newest
154
+ * `maxEntries` of them, so a site that restarts during an outage right after
155
+ * upgrading still has its content. Copied, not moved: a 0.7 process on the
156
+ * same directory (the old container during a redeploy) keeps its own.
157
+ */
158
+ adopt(legacy) {
159
+ const take = legacy.slice(-this.maxEntries);
160
+ for (const { key, entry } of take) {
161
+ this.map.set(key, entry);
162
+ this.write(key, entry);
163
+ }
164
+ return take.length;
165
+ }
166
+ /**
167
+ * At attach, in `dir`: removes the folders of this store that went unused
168
+ * for `STALE_MS`. A folder counts only when its name is a hash, it carries
169
+ * `MARKER`, and it holds nothing but cache files, temp files and the
170
+ * marker: then those go, and the folder. Anything else (a folder of the
171
+ * site's, another site's 0.7 cache files, a folder with one foreign file in
172
+ * it) is never touched, and neither is anything in `dir` itself.
173
+ *
174
+ * Silent on failure: this is tidying, not caching, and a folder another
175
+ * user owns is no reason to say the cache is unusable.
176
+ */
177
+ sweep() {
178
+ const { fs, join: join2 } = this.deps;
179
+ let entries;
180
+ try {
181
+ entries = fs.readdirSync(this.dir, { withFileTypes: true });
182
+ } catch {
183
+ return;
184
+ }
185
+ for (const entry of entries) {
186
+ if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue;
187
+ const folder = join2(this.dir, entry.name);
188
+ const marker = join2(folder, MARKER);
189
+ if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue;
190
+ this.quietly(() => {
191
+ const names = fs.readdirSync(folder);
192
+ if (!names.every((name) => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return;
193
+ for (const name of names) fs.rmSync(join2(folder, name), { force: true });
194
+ fs.rmdirSync(folder);
195
+ });
196
+ }
197
+ }
198
+ /** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */
199
+ mark() {
200
+ const marker = this.deps.join(this.folder, MARKER);
201
+ const now = /* @__PURE__ */ new Date();
202
+ this.touchedAt = now.getTime();
203
+ this.quietly(() => {
204
+ try {
205
+ this.deps.fs.utimesSync(marker, now, now);
206
+ } catch {
207
+ this.deps.fs.writeFileSync(marker, MARKER_TEXT);
208
+ }
209
+ });
210
+ }
211
+ /**
212
+ * Marks the folder as used, at most once per `TOUCH_MS`: a site whose
213
+ * content does not change writes nothing, and its folder must not look
214
+ * abandoned to the sweep of another site sharing `dir`.
215
+ */
216
+ touch() {
217
+ if (this.hash === void 0 || Date.now() - this.touchedAt < TOUCH_MS) return;
218
+ this.mark();
219
+ }
220
+ evict() {
86
221
  while (this.map.size > this.maxEntries) {
87
222
  const oldest = this.map.keys().next().value;
88
223
  if (oldest === void 0) break;
@@ -92,16 +227,36 @@ var FileCacheStore = class {
92
227
  /** Temp file plus rename, so a reader (or a crash) never sees half a file. */
93
228
  write(key, entry) {
94
229
  const file = this.fileOf(key);
95
- const tmp = `${file}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
230
+ const tmp = `${file}.${processId()}.${this.deps.randomHex(6)}.tmp`;
231
+ const stored = JSON.stringify({ v: 1, key, entry });
96
232
  try {
97
- const stored = { v: 1, key, entry };
98
- fs.writeFileSync(tmp, JSON.stringify(stored));
99
- fs.renameSync(tmp, file);
233
+ this.writeAt(tmp, file, stored);
100
234
  } catch (err) {
101
235
  this.remove(tmp);
102
236
  this.fail(err);
103
237
  }
104
238
  }
239
+ /**
240
+ * One write. A folder that is gone, before the temp file is written or
241
+ * before it is renamed, is made again and the write done once more: the
242
+ * sweep of another site sharing `dir` removes a folder only after 30 days
243
+ * unused, but a process may well sit that long without a read, and a
244
+ * person may clear the directory by hand. Only a failure that outlasts
245
+ * that second try is reported.
246
+ */
247
+ writeAt(tmp, file, stored) {
248
+ const { fs } = this.deps;
249
+ try {
250
+ fs.writeFileSync(tmp, stored);
251
+ fs.renameSync(tmp, file);
252
+ } catch (err) {
253
+ if (!isMissing(err)) throw err;
254
+ fs.mkdirSync(this.folder, { recursive: true });
255
+ if (this.hash !== void 0) this.mark();
256
+ fs.writeFileSync(tmp, stored);
257
+ fs.renameSync(tmp, file);
258
+ }
259
+ }
105
260
  /**
106
261
  * Hands a disk problem to `onError`. Never throws and never leaves a rejection
107
262
  * behind: this runs inside a cache write, which runs inside a read, and a
@@ -118,30 +273,134 @@ var FileCacheStore = class {
118
273
  } catch {
119
274
  }
120
275
  }
121
- /** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
122
- orphaned(file) {
276
+ /** Whether a file or folder was last changed more than `ms` ago. Unknown (missing) counts as "no". */
277
+ olderThan(path, ms) {
123
278
  try {
124
- return Date.now() - fs.statSync(file).mtimeMs > TEMP_ORPHAN_MS;
279
+ return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms;
125
280
  } catch {
126
281
  return false;
127
282
  }
128
283
  }
284
+ quietly(run) {
285
+ try {
286
+ run();
287
+ } catch {
288
+ }
289
+ }
129
290
  remove(file) {
130
291
  try {
131
- fs.rmSync(file, { force: true });
292
+ this.deps.fs.rmSync(file, { force: true });
132
293
  } catch (err) {
133
294
  this.fail(err);
134
295
  }
135
296
  }
136
- list() {
297
+ /** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */
298
+ list(folder) {
137
299
  try {
138
- return fs.readdirSync(this.dir);
300
+ return this.deps.fs.readdirSync(folder);
139
301
  } catch (err) {
140
- this.fail(err);
302
+ if (!isMissing(err)) this.fail(err);
141
303
  return [];
142
304
  }
143
305
  }
144
306
  };
307
+ var FILE_CACHES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-caches/2");
308
+ var FIRST_STARTS = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/first-starts/1");
309
+ function hasFolders(deps, dir) {
310
+ const { fs, join: join2 } = deps;
311
+ try {
312
+ return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join2(dir, entry.name)).includes(MARKER));
313
+ } catch {
314
+ return false;
315
+ }
316
+ }
317
+ function registry(symbol) {
318
+ const scope = globalThis;
319
+ const map = scope[symbol] ?? /* @__PURE__ */ new Map();
320
+ scope[symbol] = map;
321
+ return map;
322
+ }
323
+ function attachShared(options, deps, scope) {
324
+ const dir = deps.resolve(options.dir);
325
+ const firstStarts = registry(FIRST_STARTS);
326
+ if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir));
327
+ const caches = registry(FILE_CACHES);
328
+ const id = `${dir}
329
+ ${scope.identity}`;
330
+ const maxEntries = options.maxEntries ?? 500;
331
+ let shared = caches.get(id);
332
+ if (!shared) {
333
+ shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false };
334
+ caches.set(id, shared);
335
+ }
336
+ const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true });
337
+ const differs = maxEntries !== shared.maxEntries || options.onError !== void 0 && options.onError !== shared.onError;
338
+ if (attached && differs && !shared.told) {
339
+ shared.told = true;
340
+ scope.warn?.(`[@nordhavnhq/beacon] file cache ${attached.folder} is already open in this process: its first settings apply (maxEntries ${shared.maxEntries}, ${shared.onError ? "the first store's onError" : "no onError"}), not this one's`);
341
+ }
342
+ return attached;
343
+ }
344
+ function isMissing(err) {
345
+ return err?.code === "ENOENT";
346
+ }
347
+ function processId() {
348
+ return globalThis.process?.pid ?? 0;
349
+ }
350
+ function fileDeps(fs, crypto, path) {
351
+ return {
352
+ fs,
353
+ join: path.join,
354
+ resolve: path.resolve,
355
+ sha256: (text) => crypto.createHash("sha256").update(text).digest("hex"),
356
+ randomHex: (bytes) => crypto.randomBytes(bytes).toString("hex")
357
+ };
358
+ }
359
+
360
+ // src/file-store.ts
361
+ var NODE_DEPS = fileDeps(
362
+ { mkdirSync: fs.mkdirSync, readdirSync: fs.readdirSync, readFileSync: fs.readFileSync, renameSync: fs.renameSync, rmdirSync: fs.rmdirSync, rmSync: fs.rmSync, statSync: fs.statSync, utimesSync: fs.utimesSync, writeFileSync: fs.writeFileSync },
363
+ { createHash: crypto.createHash, randomBytes: crypto.randomBytes },
364
+ { join: path.join, resolve: path.resolve }
365
+ );
366
+ var FileCacheStore = class _FileCacheStore {
367
+ constructor(options) {
368
+ /** The folder caches of every client it was given to, for `clear`. */
369
+ this.attached = /* @__PURE__ */ new Set();
370
+ this.own = new FileCache(options, NODE_DEPS);
371
+ let firstIdentity;
372
+ const attach = (scope) => {
373
+ const plain = Object.getPrototypeOf(this) === _FileCacheStore.prototype;
374
+ if (!plain && firstIdentity !== void 0 && firstIdentity !== scope.identity) return void 0;
375
+ const attached = attachShared(options, NODE_DEPS, scope);
376
+ if (!attached) return void 0;
377
+ firstIdentity ??= scope.identity;
378
+ this.first ??= attached.store;
379
+ this.attached.add(attached.store);
380
+ return plain ? attached : { ...attached, store: this };
381
+ };
382
+ Object.defineProperty(this, ATTACH, { value: attach });
383
+ }
384
+ get cache() {
385
+ return this.first ?? this.own;
386
+ }
387
+ get(key) {
388
+ return this.cache.get(key);
389
+ }
390
+ set(key, entry) {
391
+ this.cache.set(key, entry);
392
+ }
393
+ delete(key) {
394
+ this.cache.delete(key);
395
+ }
396
+ keys() {
397
+ return this.cache.keys();
398
+ }
399
+ clear() {
400
+ if (this.attached.size === 0) this.own.clear();
401
+ for (const cache of this.attached) cache.clear();
402
+ }
403
+ };
145
404
 
146
405
  exports.FileCacheStore = FileCacheStore;
147
406
  //# sourceMappingURL=file-store.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/file-store.ts"],"names":["join","createHash","mkdirSync","readFileSync","statSync","randomBytes","writeFileSync","renameSync","rmSync","readdirSync"],"mappings":";;;;;;;AAgDA,IAAM,MAAA,GAAS,OAAA;AAQf,IAAM,UAAA,GAAa,sBAAA;AACnB,IAAM,SAAA,GAAY,8CAAA;AAQlB,IAAM,cAAA,GAAiB,GAAA;AAEhB,IAAM,iBAAN,MAA2C;AAAA,EAOhD,YAAY,OAAA,EAAgC;AAF5C;AAAA,IAAA,IAAA,CAAiB,GAAA,uBAAU,GAAA,EAAwB;AAGjD,IAAA,IAAI,CAAC,OAAA,EAAS,GAAA,EAAK,MAAM,IAAI,MAAM,mCAAmC,CAAA;AACtE,IAAA,IAAA,CAAK,MAAM,OAAA,CAAQ,GAAA;AACnB,IAAA,IAAA,CAAK,UAAA,GAAa,QAAQ,UAAA,IAAc,GAAA;AAExC,IAAA,IAAI,MAAA,GAAS,KAAA;AACb,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA,CAAQ,OAAA,KAAY,CAAC,GAAA,KAAQ;AAC1C,MAAA,IAAI,MAAA,EAAQ;AACZ,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,OAAA,CAAQ,IAAA,CAAK,sCAAsC,IAAA,CAAK,GAAG,oCAAoC,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,GAAG,CAAA;AAAA,IACzI,CAAA,CAAA;AAEA,IAAA,IAAA,CAAK,IAAA,EAAK;AAAA,EACZ;AAAA,EAEA,IAAI,GAAA,EAAqC;AACvC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AAAA,EACzB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAAyB;AACxC,IAAA,IAAA,CAAK,GAAA,CAAI,OAAO,GAAG,CAAA;A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;AACzC,MAAA,IAAI,OAAQ,OAAA,EAAmD,IAAA,KAAS,UAAA,EAAY;AAClF,QAAC,OAAA,CAAiC,IAAA,CAAK,KAAA,CAAA,EAAW,MAAM;AAAA,QAAC,CAAC,CAAA;AAAA,MAC5D;AAAA,IACF,CAAA,CAAA,MACM;AAAA,IAEN;AAAA,EACF;AAAA;AAAA,EAGQ,SAAS,IAAA,EAAuB;AACtC,IAAA,IAAI;AACF,MAAA,OAAO,KAAK,GAAA,EAAI,GAAIH,WAAA,CAAS,IAAI,EAAE,OAAA,GAAU,cAAA;AAAA,IAC/C,CAAA,CAAA,MACM;AACJ,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,OAAO,IAAA,EAAoB;AACjC,IAAA,IAAI;AACF,MAAAI,SAAA,CAAO,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAC9B,SACO,GAAA,EAAK;AACV,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AAAA,EAEQ,IAAA,GAAiB;AACvB,IAAA,IAAI;AACF,MAAA,OAAOC,cAAA,CAAY,KAAK,GAAG,CAAA;AAAA,IAC7B,SACO,GAAA,EAAK;AACV,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AACb,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF;AACF","file":"file-store.cjs","sourcesContent":["/**\n * A `CacheStore` that keeps its entries on disk as well as in memory, so a\n * restarted process still has the last good content - also when the studio is\n * down at that very moment.\n *\n * Node only (it uses `node:fs`), which is why it lives at its own entry point,\n * `@nordhavnhq/beacon/file-store`, and the main entry stays browser-safe.\n *\n * ```ts\n * import { createClient } from '@nordhavnhq/beacon'\n * import { FileCacheStore } from '@nordhavnhq/beacon/file-store'\n *\n * const studio = createClient({\n * apiKey,\n * cache: { store: new FileCacheStore({ dir: '/data/studio-cache' }) },\n * })\n * ```\n *\n * Reads come from memory; the disk is read once, when the store is created, and\n * written through on every change. One directory per site: cache keys do not\n * include the project or the API key, so two sites sharing a directory would\n * serve each other's content while the studio is unreachable.\n */\nimport { createHash, randomBytes } from 'node:crypto'\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { CacheEntry, CacheStore } from './cache'\n\nexport interface FileCacheStoreOptions {\n /** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. The store then keeps\n * working from memory, like the default store. Default: one `console.warn`\n * per store, so a read-only volume is noticed without flooding the log.\n */\n onError?: (err: unknown) => void\n}\n\n/** On-disk shape. `v` leaves room to change it without misreading old files. */\ninterface StoredFile {\n v: 1\n key: string\n entry: CacheEntry\n}\n\nconst SUFFIX = '.json'\n\n/**\n * The only names this store reads, replaces or removes: the sha256 of a cache\n * key (see `fileOf`), and the temp file of a write to one. `dir` may hold other\n * files - a mistyped path can point at a project root - and those are never\n * touched, whatever their extension.\n */\nconst CACHE_FILE = /^[0-9a-f]{64}\\.json$/\nconst TEMP_FILE = /^[0-9a-f]{64}\\.json\\.\\d+(\\.[0-9a-f]+)?\\.tmp$/\n\n/**\n * How old a temp file must be before a starting store takes it for an orphan.\n * A write takes milliseconds, so anything younger may be a write under way in\n * another process on the same directory: the old and the new container during\n * a redeploy, or the workers of a cluster.\n */\nconst TEMP_ORPHAN_MS = 60_000\n\nexport class FileCacheStore implements CacheStore {\n private readonly dir: string\n private readonly maxEntries: number\n private readonly onError: (err: unknown) => void\n /** Same order contract as `MemoryCacheStore`: oldest written first. */\n private readonly map = new Map<string, CacheEntry>()\n\n constructor(options: FileCacheStoreOptions) {\n if (!options?.dir) throw new Error('FileCacheStore: `dir` is required')\n this.dir = options.dir\n this.maxEntries = options.maxEntries ?? 500\n\n let warned = false\n this.onError = options.onError ?? ((err) => {\n if (warned) return\n warned = true\n console.warn(`[@nordhavnhq/beacon] file cache at ${this.dir} unusable, continuing in memory:`, err instanceof Error ? err.message : err)\n })\n\n this.load()\n }\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.map.delete(key)\n this.map.set(key, entry)\n this.write(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n this.remove(this.fileOf(key))\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n for (const name of this.list()) {\n if (CACHE_FILE.test(name)) this.remove(join(this.dir, name))\n }\n }\n\n // ── Disk ────────────────────────────────────────────────────────────────────\n\n /** File name per key: a hash, as keys hold `/` and `:` and may be long. */\n private fileOf(key: string): string {\n return join(this.dir, createHash('sha256').update(key).digest('hex') + SUFFIX)\n }\n\n /** Fills memory from disk, oldest file first so eviction order survives a restart. */\n private load(): void {\n try {\n mkdirSync(this.dir, { recursive: true })\n }\n catch (err) {\n this.fail(err)\n return\n }\n\n const found: { key: string, entry: CacheEntry, mtime: number }[] = []\n for (const name of this.list()) {\n const file = join(this.dir, name)\n // Left behind by a process killed between write and rename - unless it\n // is fresh, and then it belongs to a write that is still happening.\n if (TEMP_FILE.test(name)) {\n if (this.orphaned(file)) this.remove(file)\n continue\n }\n // Not one of ours: leave it exactly as it is.\n if (!CACHE_FILE.test(name)) continue\n try {\n const stored = JSON.parse(readFileSync(file, 'utf8')) as StoredFile\n if (stored?.v !== 1 || typeof stored.key !== 'string' || !stored.entry || file !== this.fileOf(stored.key)) {\n throw new Error('not a cache file')\n }\n found.push({ key: stored.key, entry: stored.entry, mtime: statSync(file).mtimeMs })\n }\n catch {\n // Ours by name but unreadable, or filed under another key: it can only\n // ever be a miss, so drop it.\n this.remove(file)\n }\n }\n\n found.sort((a, b) => a.mtime - b.mtime)\n for (const { key, entry } of found) this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n /** Temp file plus rename, so a reader (or a crash) never sees half a file. */\n private write(key: string, entry: CacheEntry): void {\n const file = this.fileOf(key)\n // The random part keeps two processes apart that write the same key at the\n // same moment. The pid alone does not: in a container it is 1 for both.\n const tmp = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n const stored: StoredFile = { v: 1, key, entry }\n writeFileSync(tmp, JSON.stringify(stored))\n renameSync(tmp, file)\n }\n catch (err) {\n this.remove(tmp)\n this.fail(err)\n }\n }\n\n /**\n * Hands a disk problem to `onError`. Never throws and never leaves a rejection\n * behind: this runs inside a cache write, which runs inside a read, and a\n * hook that fails (or an `async` one whose own work fails) must not fail the\n * read or stop the process over a cache that merely fell back to memory.\n */\n private fail(err: unknown): void {\n try {\n const outcome: unknown = this.onError(err)\n if (typeof (outcome as { then?: unknown } | null | undefined)?.then === 'function') {\n (outcome as PromiseLike<unknown>).then(undefined, () => {})\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /** Whether a temp file is old enough to have been abandoned. Unknown counts as \"no\". */\n private orphaned(file: string): boolean {\n try {\n return Date.now() - statSync(file).mtimeMs > TEMP_ORPHAN_MS\n }\n catch {\n return false\n }\n }\n\n private remove(file: string): void {\n try {\n rmSync(file, { force: true })\n }\n catch (err) {\n this.fail(err)\n }\n }\n\n private list(): string[] {\n try {\n return readdirSync(this.dir)\n }\n catch (err) {\n this.fail(err)\n return []\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/file-cache.ts","../src/file-store.ts"],"names":["join","mkdirSync","readdirSync","readFileSync","renameSync","rmdirSync","rmSync","statSync","utimesSync","writeFileSync","createHash","randomBytes","resolve"],"mappings":";;;;;;;;;AAgHO,IAAM,MAAA,mBAAS,MAAA,CAAO,GAAA,CAAI,wCAAwC,CAAA;AAUzE,IAAM,MAAA,GAAS,OAAA;AAQf,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CAAK,GAAA;AAAA,EAC5B;AAAA,EAEA,IAAI,GAAA,EAAqC;AACvC,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAAA,EAC3B;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAAyB;AACxC,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AAAA,EAC3B;AAAA,EAEA,OAAO,GAAA,EAAmB;AACxB,IAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,EACvB;AAAA,EAEA,IAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,MAAM,IAAA,EAAK;AAAA,EACzB;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAI,KAAK,QAAA,CAAS,IAAA,KAAS,CAAA,EAAG,IAAA,CAAK,IAAI,KAAA,EAAM;AAC7C,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,QAAA,EAAU,KAAA,CAAM,KAAA,EAAM;AAAA,EACjD;AACF","file":"file-store.cjs","sourcesContent":["/**\n * The file cache behind `FileCacheStore` (`@nordhavnhq/beacon/file-store`) and\n * the `cache.dir` option: entries on disk as well as in memory, so a restarted\n * process still has the last good content, also when the studio is down at\n * that very moment.\n *\n * Node's `fs`, `crypto` and `path` come in as `FileDeps` and are not imported\n * here: the file-store entry hands over its static imports, the main entry\n * (for `cache.dir`) takes them from `process.getBuiltinModule`, so the main\n * entry stays loadable in a browser.\n *\n * Kept per site. A client hands its identity over (`ATTACH`, `attachShared`);\n * the entries then live in `<dir>/<hash>/`, the hash a short sha256 of the\n * server and the credentials the client sends, and two sites (or two keys of\n * a developer) sharing `dir` never see each other's content. One cache per\n * folder in a process (`attachShared`), whoever asks for it. A store no client\n * attached to keeps its entries in `dir` itself, as it did up to 0.7.\n *\n * What it removes on its own is narrow on purpose, as `dir` may be mistyped\n * (a project root, `/tmp`, a parent of other sites' folders): only its own\n * cache files, and only folders it made itself, which carry `MARKER`.\n */\nimport type { CacheEntry, CacheStore } from './cache'\n\nexport interface FileCacheOptions {\n /** Directory for the cache files. Created when missing. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. Without one, the store\n * warns once, through the client's `logger` once a client attached it.\n */\n onError?: (err: unknown) => void\n}\n\n/*\n * The parts of Node's `fs`, `crypto` and `path` the store uses, declared\n * locally: beacon's main entry builds one too (for `cache.dir`) and must\n * typecheck without Node's types.\n */\ninterface DirEntry {\n name: string\n isDirectory(): boolean\n}\nexport interface FileSystem {\n mkdirSync(path: string, options: { recursive: true }): unknown\n readdirSync(path: string): string[]\n readdirSync(path: string, options: { withFileTypes: true }): DirEntry[]\n readFileSync(path: string, encoding: 'utf8'): string\n writeFileSync(path: string, data: string): void\n renameSync(from: string, to: string): void\n rmSync(path: string, options: { force: true }): void\n rmdirSync(path: string): void\n statSync(path: string): { mtimeMs: number }\n utimesSync(path: string, atime: Date, mtime: Date): void\n}\nexport interface FileDeps {\n fs: FileSystem\n join(...parts: string[]): string\n resolve(path: string): string\n sha256(text: string): string\n randomHex(bytes: number): string\n}\n\n/** What a client tells the store it attaches to. */\nexport interface StoreScope {\n /** Server and credentials (`identityOf`), hashed into the folder's name. */\n identity: string\n /**\n * Whether the cache files of 0.7 in `dir` itself are copied into a folder\n * that has no entries yet: for a `FileCacheStore` a site passes in, which\n * up to 0.7 had one `dir` per site, on the first start after 0.7 (decided\n * in `attachShared`). Not for `cache.dir`, new in 0.8.\n */\n adoptLegacy: boolean\n /** Where disk problems go when the store has no `onError` of its own; `undefined` keeps them quiet. */\n warn: ((...args: unknown[]) => void) | undefined\n}\n\n/** What the store reports back to the client that attached it. */\nexport interface AttachedStore {\n /** What the client caches in: the cache of its folder. */\n store: CacheStore\n /** The store's `dir`. */\n dir: string\n /** Where its entries live: `<dir>/<hash>`. */\n folder: string\n /** Entries in the folder on attaching, copied ones included. */\n loaded: number\n /** Cache files of 0.7 in `dir` itself, left where they are. */\n legacy: number\n /** How many of those were copied into the folder (`adoptLegacy`). */\n copied: number\n /** `false` for a second client with the same identity: it was already loaded. */\n first: boolean\n}\n\n/**\n * The method a client calls to hand the store its identity. A symbol from\n * the global registry: the main entry and the file-store entry are separate\n * bundles (and a site may load two copies), and must still find each other.\n * Returns `undefined` when the store already serves another identity.\n *\n * Keep this symbol (and the `globalThis` ones below) stable across releases.\n * A site can load two copies of beacon (a dependency pinning another\n * version), and a client from one hands its identity to a store from the\n * other through this name. If it is ever bumped, clients must keep trying\n * the older symbols too: else a store from an older copy is no longer found,\n * and a client of the newer one uses it as a plain store, in its unsplit\n * `dir`, as 0.7 did.\n */\nexport const ATTACH = Symbol.for('@nordhavnhq/beacon/file-cache-attach/3')\nexport type Attach = (scope: StoreScope) => AttachedStore | undefined\n\n/** On-disk shape. `v` leaves room to change it without misreading old files. */\ninterface StoredFile {\n v: 1\n key: string\n entry: CacheEntry\n}\n\nconst SUFFIX = '.json'\n\n/**\n * The only names this store reads, replaces or removes: the sha256 of a cache\n * key (see `fileOf`), and the temp file of a write to one. `dir` may hold other\n * files - a mistyped path can point at a project root - and those are never\n * touched, whatever their extension.\n */\nconst CACHE_FILE = /^[0-9a-f]{64}\\.json$/\nconst TEMP_FILE = /^[0-9a-f]{64}\\.json\\.\\d+(\\.[0-9a-f]+)?\\.tmp$/\n\n/** The name of a folder this store makes: 16 hex characters of a sha256. */\nconst FOLDER = /^[0-9a-f]{16}$/\n\n/**\n * Put in every folder this store makes, and kept fresh while it is used: the\n * sweep of another client looks only at folders that carry it, so a folder of\n * anything else that happens to have a fitting name is never touched.\n */\nexport const MARKER = '.beacon-cache'\nconst MARKER_TEXT = 'A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\\n'\n\n/**\n * How old a temp file must be before a starting store takes it for an orphan.\n * A write takes milliseconds, so anything younger may be a write under way in\n * another process on the same directory: the old and the new container during\n * a redeploy, or the workers of a cluster.\n */\nconst TEMP_ORPHAN_MS = 60_000\n\n/**\n * How long a folder of this store may go unused before a starting store\n * removes it: the cache of a key that was replaced. Its own folder is marked\n * as used at start and then at least daily (`TOUCH_MS`), whether or not\n * anything changes.\n */\nexport const STALE_MS = 30 * 24 * 3_600_000\nconst TOUCH_MS = 24 * 3_600_000\n\nexport class FileCache implements CacheStore {\n private readonly dir: string\n private readonly maxEntries: number\n private readonly onError: (err: unknown) => void\n private readonly deps: FileDeps\n /** Same order contract as `MemoryCacheStore`: oldest written first. */\n private readonly map = new Map<string, CacheEntry>()\n /** Where the entries live: `dir` until a client attaches, then `<dir>/<hash>`. */\n private folder: string\n /** The folder's name once a client attached. */\n private hash: string | undefined\n /** What the first attach reported, for the clients after it. */\n private attached: AttachedStore | undefined\n /** Read from disk on first use, not at construction: a client attaching first decides where from. */\n private loaded = false\n private touchedAt = 0\n /** Whether disk problems go to the default warning (and so follow an attaching client's `logger`). */\n private readonly ownWarning: boolean\n /** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */\n private warnTo: ((...args: unknown[]) => void) | undefined = (...args) => console.warn(...args)\n\n constructor(options: FileCacheOptions, deps: FileDeps) {\n if (!options?.dir) throw new Error('FileCacheStore: `dir` is required')\n this.dir = options.dir\n this.folder = options.dir\n this.maxEntries = options.maxEntries ?? 500\n this.deps = deps\n\n let warned = false\n this.onError = options.onError ?? ((err) => {\n if (warned) return\n warned = true\n this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err)\n })\n this.ownWarning = options.onError === undefined\n }\n\n get(key: string): CacheEntry | undefined {\n this.ensureLoaded()\n this.touch()\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.map.set(key, entry)\n this.write(key, entry)\n this.evict()\n }\n\n delete(key: string): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.remove(this.fileOf(key))\n }\n\n keys(): Iterable<string> {\n this.ensureLoaded()\n return this.map.keys()\n }\n\n clear(): void {\n this.ensureLoaded()\n this.map.clear()\n for (const name of this.list(this.folder)) {\n if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name))\n }\n }\n\n /**\n * Moves the store into its folder (`<dir>/<hash>`) and reads that; copies\n * the cache files of 0.7 in when asked and the folder is empty; then clears\n * out folders of this store that went unused (`sweep`). Entries already\n * read from `dir` itself are dropped from memory. A second client with the\n * same identity finds it done; one with another identity is refused, as the\n * store holds one site's entries.\n */\n [ATTACH](scope: StoreScope): AttachedStore | undefined {\n const hash = this.deps.sha256(scope.identity).slice(0, 16)\n if (this.hash !== undefined) {\n return this.hash === hash && this.attached ? { ...this.attached, first: false } : undefined\n }\n if (this.ownWarning) this.warnTo = scope.warn\n this.hash = hash\n this.folder = this.deps.join(this.dir, hash)\n this.map.clear()\n this.loaded = false\n this.ensureLoaded()\n this.mark()\n const legacy = this.legacyFiles()\n const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0\n this.sweep()\n this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true }\n return this.attached\n }\n\n // ── Disk ────────────────────────────────────────────────────────────────────\n\n /** File name per key: a hash, as keys hold `/` and `:` and may be long. */\n private fileOf(key: string, folder = this.folder): string {\n return this.deps.join(folder, this.deps.sha256(key) + SUFFIX)\n }\n\n private ensureLoaded(): void {\n if (this.loaded) return\n this.loaded = true\n this.load()\n }\n\n /** Fills memory from disk, oldest file first so eviction order survives a restart. */\n private load(): void {\n try {\n this.deps.fs.mkdirSync(this.folder, { recursive: true })\n }\n catch (err) {\n this.fail(err)\n return\n }\n for (const name of this.list(this.folder)) {\n // Left behind by a process killed between write and rename - unless it\n // is fresh, and then it belongs to a write that is still happening.\n if (TEMP_FILE.test(name)) {\n const file = this.deps.join(this.folder, name)\n if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file)\n }\n }\n // Ours by name but unreadable, or filed under another key: it can only\n // ever be a miss, so it goes.\n const found = this.readEntries(this.folder, file => this.remove(file))\n for (const { key, entry } of found) this.map.set(key, entry)\n this.evict()\n }\n\n /**\n * The readable cache files in `folder`, oldest first. Files that are this\n * store's by name but not a cache entry (half written, filed under another\n * key) go to `bad`; anything else in `folder` is not looked at.\n */\n private readEntries(folder: string, bad: (file: string) => void): { key: string, entry: CacheEntry, mtime: number }[] {\n const { fs } = this.deps\n const found: { key: string, entry: CacheEntry, mtime: number }[] = []\n for (const name of this.list(folder)) {\n if (!CACHE_FILE.test(name)) continue\n const file = this.deps.join(folder, name)\n try {\n const stored = JSON.parse(fs.readFileSync(file, 'utf8')) as StoredFile\n if (stored?.v !== 1 || typeof stored.key !== 'string' || !stored.entry || file !== this.fileOf(stored.key, folder)) {\n throw new Error('not a cache file')\n }\n found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs })\n }\n catch {\n bad(file)\n }\n }\n return found.sort((a, b) => a.mtime - b.mtime)\n }\n\n /** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */\n private legacyFiles(): { key: string, entry: CacheEntry, mtime: number }[] {\n return this.readEntries(this.dir, () => {})\n }\n\n /**\n * Copies the cache files of 0.7 into the (empty) folder, the newest\n * `maxEntries` of them, so a site that restarts during an outage right after\n * upgrading still has its content. Copied, not moved: a 0.7 process on the\n * same directory (the old container during a redeploy) keeps its own.\n */\n private adopt(legacy: { key: string, entry: CacheEntry }[]): number {\n const take = legacy.slice(-this.maxEntries)\n for (const { key, entry } of take) {\n this.map.set(key, entry)\n this.write(key, entry)\n }\n return take.length\n }\n\n /**\n * At attach, in `dir`: removes the folders of this store that went unused\n * for `STALE_MS`. A folder counts only when its name is a hash, it carries\n * `MARKER`, and it holds nothing but cache files, temp files and the\n * marker: then those go, and the folder. Anything else (a folder of the\n * site's, another site's 0.7 cache files, a folder with one foreign file in\n * it) is never touched, and neither is anything in `dir` itself.\n *\n * Silent on failure: this is tidying, not caching, and a folder another\n * user owns is no reason to say the cache is unusable.\n */\n private sweep(): void {\n const { fs, join } = this.deps\n let entries: DirEntry[]\n try {\n entries = fs.readdirSync(this.dir, { withFileTypes: true })\n }\n catch {\n return\n }\n for (const entry of entries) {\n // `isDirectory()` of a symbolic link is false: one is never followed.\n if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue\n const folder = join(this.dir, entry.name)\n const marker = join(folder, MARKER)\n if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue\n this.quietly(() => {\n const names = fs.readdirSync(folder)\n if (!names.every(name => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return\n for (const name of names) fs.rmSync(join(folder, name), { force: true })\n fs.rmdirSync(folder)\n })\n }\n }\n\n /** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */\n private mark(): void {\n const marker = this.deps.join(this.folder, MARKER)\n const now = new Date()\n this.touchedAt = now.getTime()\n this.quietly(() => {\n try {\n this.deps.fs.utimesSync(marker, now, now)\n }\n catch {\n this.deps.fs.writeFileSync(marker, MARKER_TEXT)\n }\n })\n }\n\n /**\n * Marks the folder as used, at most once per `TOUCH_MS`: a site whose\n * content does not change writes nothing, and its folder must not look\n * abandoned to the sweep of another site sharing `dir`.\n */\n private touch(): void {\n if (this.hash === undefined || Date.now() - this.touchedAt < TOUCH_MS) return\n this.mark()\n }\n\n private evict(): void {\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n /** Temp file plus rename, so a reader (or a crash) never sees half a file. */\n private write(key: string, entry: CacheEntry): void {\n const file = this.fileOf(key)\n // The random part keeps two processes apart that write the same key at the\n // same moment. The pid alone does not: in a container it is 1 for both.\n const tmp = `${file}.${processId()}.${this.deps.randomHex(6)}.tmp`\n const stored = JSON.stringify({ v: 1, key, entry } satisfies StoredFile)\n try {\n this.writeAt(tmp, file, stored)\n }\n catch (err) {\n this.remove(tmp)\n this.fail(err)\n }\n }\n\n /**\n * One write. A folder that is gone, before the temp file is written or\n * before it is renamed, is made again and the write done once more: the\n * sweep of another site sharing `dir` removes a folder only after 30 days\n * unused, but a process may well sit that long without a read, and a\n * person may clear the directory by hand. Only a failure that outlasts\n * that second try is reported.\n */\n private writeAt(tmp: string, file: string, stored: string): void {\n const { fs } = this.deps\n try {\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\n }\n catch (err) {\n if (!isMissing(err)) throw err\n fs.mkdirSync(this.folder, { recursive: true })\n if (this.hash !== undefined) this.mark()\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\n }\n }\n\n /**\n * Hands a disk problem to `onError`. Never throws and never leaves a rejection\n * behind: this runs inside a cache write, which runs inside a read, and a\n * hook that fails (or an `async` one whose own work fails) must not fail the\n * read or stop the process over a cache that merely fell back to memory.\n */\n private fail(err: unknown): void {\n try {\n const outcome: unknown = this.onError(err)\n if (typeof (outcome as { then?: unknown } | null | undefined)?.then === 'function') {\n (outcome as PromiseLike<unknown>).then(undefined, () => {})\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /** Whether a file or folder was last changed more than `ms` ago. Unknown (missing) counts as \"no\". */\n private olderThan(path: string, ms: number): boolean {\n try {\n return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms\n }\n catch {\n return false\n }\n }\n\n private quietly(run: () => void): void {\n try {\n run()\n }\n catch {\n /* see `sweep` */\n }\n }\n\n private remove(file: string): void {\n try {\n this.deps.fs.rmSync(file, { force: true })\n }\n catch (err) {\n this.fail(err)\n }\n }\n\n /** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */\n private list(folder: string): string[] {\n try {\n return this.deps.fs.readdirSync(folder)\n }\n catch (err) {\n if (!isMissing(err)) this.fail(err)\n return []\n }\n }\n}\n\n/**\n * The file caches attached by clients, one per folder (resolved `dir` and\n * identity) in a process, on `globalThis`: whoever asks for a folder gets\n * the same cache, `cache.dir` and a `FileCacheStore` alike, also from\n * another build of beacon (its ESM and CommonJS entries, a dev server's\n * reload). A site that makes a client (or a store) per request does not read\n * the directory again each time, and no two caches on one folder evict each\n * other's files. The first to ask decides `maxEntries` and `onError`; a later\n * one asking with others is told so, once.\n *\n * Keep the symbol stable (see `ATTACH`).\n */\nconst FILE_CACHES = Symbol.for('@nordhavnhq/beacon/file-caches/2')\n\ninterface SharedCache {\n cache: FileCache\n maxEntries: number\n onError: ((err: unknown) => void) | undefined\n /** Whether a later asker was already told that the first one's settings apply. */\n told: boolean\n}\n\n/**\n * Per resolved `dir` in a process, whether this is the first start after\n * 0.7: no folder of beacon's in it yet (a hash name with `MARKER`) when the\n * first client of the process attached. Decided once, before that client\n * makes its own folder, so a reader and a writer of one site, whichever\n * comes first, both copy the 0.7 entries into their folders; a new key in a\n * later process finds the folders and copies nothing (the 0.7 entries are\n * months old by then). Keep the symbol stable (see `ATTACH`).\n */\nconst FIRST_STARTS = Symbol.for('@nordhavnhq/beacon/first-starts/1')\n\n/** Whether `dir` holds a folder of beacon's: a hash name with `MARKER` in it. */\nfunction hasFolders(deps: FileDeps, dir: string): boolean {\n const { fs, join } = deps\n try {\n return fs.readdirSync(dir, { withFileTypes: true }).some(entry =>\n entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER))\n }\n catch {\n return false\n }\n}\n\nfunction registry<T>(symbol: symbol): Map<string, T> {\n const scope = globalThis as unknown as Record<symbol, Map<string, T> | undefined>\n const map = scope[symbol] ?? new Map<string, T>()\n scope[symbol] = map\n return map\n}\n\n/** Attaches `scope` to the cache of its folder in `options.dir`, made with `options` and `deps` if it is the first. */\nexport function attachShared(options: FileCacheOptions, deps: FileDeps, scope: StoreScope): AttachedStore | undefined {\n const dir = deps.resolve(options.dir)\n const firstStarts = registry<boolean>(FIRST_STARTS)\n if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir))\n const caches = registry<SharedCache>(FILE_CACHES)\n const id = `${dir}\\n${scope.identity}`\n const maxEntries = options.maxEntries ?? 500\n let shared = caches.get(id)\n if (!shared) {\n shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false }\n caches.set(id, shared)\n }\n const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true })\n const differs = maxEntries !== shared.maxEntries || (options.onError !== undefined && options.onError !== shared.onError)\n if (attached && differs && !shared.told) {\n shared.told = true\n scope.warn?.(`[@nordhavnhq/beacon] file cache ${attached.folder} is already open in this process: its first settings apply (maxEntries ${shared.maxEntries}, ${shared.onError ? 'the first store\\'s onError' : 'no onError'}), not this one's`)\n }\n return attached\n}\n\nfunction isMissing(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'ENOENT'\n}\n\n/** The pid, for temp file names; `0` where there is no `process`. */\nfunction processId(): number {\n return (globalThis as { process?: { pid?: number } }).process?.pid ?? 0\n}\n\n/**\n * `FileDeps` from the modules Node hands out synchronously\n * (`process.getBuiltinModule`, Node 22.3 and later), or `undefined` where\n * there are none: a browser, an edge runtime, an older Node.\n */\nexport function builtinFileDeps(builtin: (id: string) => unknown): FileDeps | undefined {\n const fs = builtin('node:fs') as FileSystem | undefined\n const crypto = builtin('node:crypto') as NodeCrypto | undefined\n const path = builtin('node:path') as NodePath | undefined\n if (!fs || !crypto || !path) return undefined\n return fileDeps(fs, crypto, path)\n}\n\ninterface NodeCrypto {\n createHash(algorithm: 'sha256'): { update(text: string): { digest(encoding: 'hex'): string } }\n randomBytes(size: number): { toString(encoding: 'hex'): string }\n}\ninterface NodePath {\n join(...parts: string[]): string\n resolve(path: string): string\n}\n\n/** `FileDeps` from Node's `fs`, `crypto` and `path`. */\nexport function fileDeps(fs: FileSystem, crypto: NodeCrypto, path: NodePath): FileDeps {\n return {\n fs,\n join: path.join,\n resolve: path.resolve,\n sha256: text => crypto.createHash('sha256').update(text).digest('hex'),\n randomHex: bytes => crypto.randomBytes(bytes).toString('hex'),\n }\n}\n","/**\n * A `CacheStore` that keeps its entries on disk as well as in memory, so a\n * restarted process still has the last good content - also when the studio is\n * down at that very moment.\n *\n * Node only (it uses `node:fs`), which is why it lives at its own entry point,\n * `@nordhavnhq/beacon/file-store`, and the main entry stays browser-safe. The\n * client's `cache.dir` option builds the same store without this import:\n *\n * ```ts\n * import { createClient } from '@nordhavnhq/beacon'\n *\n * const studio = createClient({ cache: { dir: '/data/studio-cache' } })\n * ```\n *\n * Reads come from memory; the disk is read once, when the store is first\n * used, and written through on every change. Given to a client as\n * `cache.store`, the store keeps its entries in a folder of `dir` named after\n * a hash of that client's server and key, so sites and keys sharing a\n * directory never see each other's content; on the first start after 0.7 it\n * copies the cache files 0.7 left in `dir` into that folder. Given to clients\n * of several keys (a reader and a writer, say), it keeps a folder per key, and\n * each client caches in its own. A store used on its own, without a client,\n * keeps its entries in `dir` itself, as up to 0.7.\n *\n * Its own methods `get`, `set`, `delete` and `keys` (as a site counts what\n * came from disk) act on the folder of the first client it was given to, or\n * on `dir` itself before that; `clear` clears the folder of every client it\n * was given to (a purge reaches the reader and the writer alike).\n *\n * A subclass is used as given, so its overrides keep applying: the clients\n * call its own methods, which act on the folder of the first key it was\n * given to. Given to a client of another key, it is not shared: that client\n * caches in memory, with a warning.\n */\nimport { createHash, randomBytes } from 'node:crypto'\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { CacheEntry, CacheStore } from './cache'\nimport { ATTACH, FileCache, attachShared, fileDeps, type AttachedStore, type FileSystem, type StoreScope } from './file-cache'\n\nexport interface FileCacheStoreOptions {\n /** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. The store then keeps\n * working from memory, like the default store. Default: one warning per\n * store, so a read-only volume is noticed without flooding the log: on the\n * console, or through the `logger` of the client the store is given to.\n */\n onError?: (err: unknown) => void\n}\n\nconst NODE_DEPS = fileDeps(\n { mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } as unknown as FileSystem,\n { createHash, randomBytes },\n { join, resolve },\n)\n\nexport class FileCacheStore implements CacheStore {\n /** The entries in `dir` itself, for a store no client was given to. */\n private readonly own: FileCache\n /** The cache of the first client's folder, once there is one. */\n private first: CacheStore | undefined\n /** The folder caches of every client it was given to, for `clear`. */\n private readonly attached = new Set<CacheStore>()\n\n constructor(options: FileCacheStoreOptions) {\n this.own = new FileCache(options, NODE_DEPS)\n let firstIdentity: string | undefined\n // How a client hands over its identity, and gets the cache of its folder\n // back (`attachShared`); kept out of the public type.\n const attach = (scope: StoreScope): AttachedStore | undefined => {\n // A subclass keeps its overrides: the client gets the store itself,\n // which can stand for one folder only.\n const plain = Object.getPrototypeOf(this) === FileCacheStore.prototype\n if (!plain && firstIdentity !== undefined && firstIdentity !== scope.identity) return undefined\n const attached = attachShared(options, NODE_DEPS, scope)\n if (!attached) return undefined\n firstIdentity ??= scope.identity\n this.first ??= attached.store\n this.attached.add(attached.store)\n return plain ? attached : { ...attached, store: this }\n }\n Object.defineProperty(this, ATTACH, { value: attach })\n }\n\n private get cache(): CacheStore {\n return this.first ?? this.own\n }\n\n get(key: string): CacheEntry | undefined {\n return this.cache.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.cache.set(key, entry)\n }\n\n delete(key: string): void {\n this.cache.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.cache.keys()\n }\n\n clear(): void {\n if (this.attached.size === 0) this.own.clear()\n for (const cache of this.attached) cache.clear()\n }\n}\n"]}
@@ -7,40 +7,26 @@ interface FileCacheStoreOptions {
7
7
  maxEntries?: number;
8
8
  /**
9
9
  * Called when the disk cannot be read or written. The store then keeps
10
- * working from memory, like the default store. Default: one `console.warn`
11
- * per store, so a read-only volume is noticed without flooding the log.
10
+ * working from memory, like the default store. Default: one warning per
11
+ * store, so a read-only volume is noticed without flooding the log: on the
12
+ * console, or through the `logger` of the client the store is given to.
12
13
  */
13
14
  onError?: (err: unknown) => void;
14
15
  }
15
16
  declare class FileCacheStore implements CacheStore {
16
- private readonly dir;
17
- private readonly maxEntries;
18
- private readonly onError;
19
- /** Same order contract as `MemoryCacheStore`: oldest written first. */
20
- private readonly map;
17
+ /** The entries in `dir` itself, for a store no client was given to. */
18
+ private readonly own;
19
+ /** The cache of the first client's folder, once there is one. */
20
+ private first;
21
+ /** The folder caches of every client it was given to, for `clear`. */
22
+ private readonly attached;
21
23
  constructor(options: FileCacheStoreOptions);
24
+ private get cache();
22
25
  get(key: string): CacheEntry | undefined;
23
26
  set(key: string, entry: CacheEntry): void;
24
27
  delete(key: string): void;
25
28
  keys(): Iterable<string>;
26
29
  clear(): void;
27
- /** File name per key: a hash, as keys hold `/` and `:` and may be long. */
28
- private fileOf;
29
- /** Fills memory from disk, oldest file first so eviction order survives a restart. */
30
- private load;
31
- /** Temp file plus rename, so a reader (or a crash) never sees half a file. */
32
- private write;
33
- /**
34
- * Hands a disk problem to `onError`. Never throws and never leaves a rejection
35
- * behind: this runs inside a cache write, which runs inside a read, and a
36
- * hook that fails (or an `async` one whose own work fails) must not fail the
37
- * read or stop the process over a cache that merely fell back to memory.
38
- */
39
- private fail;
40
- /** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
41
- private orphaned;
42
- private remove;
43
- private list;
44
30
  }
45
31
 
46
32
  export { FileCacheStore };