@nordhavnhq/beacon 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +3 -329
- package/dist/cache-q8uLEGYg.d.cts +165 -0
- package/dist/cache-q8uLEGYg.d.ts +165 -0
- package/dist/file-store.cjs +148 -0
- package/dist/file-store.cjs.map +1 -0
- package/dist/file-store.d.cts +47 -0
- package/dist/file-store.d.ts +47 -0
- package/dist/file-store.js +146 -0
- package/dist/file-store.js.map +1 -0
- package/dist/index.cjs +621 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -130
- package/dist/index.d.ts +240 -130
- package/dist/index.js +621 -107
- package/dist/index.js.map +1 -1
- package/package.json +42 -19
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
|
|
7
|
+
// src/file-store.ts
|
|
8
|
+
var SUFFIX = ".json";
|
|
9
|
+
var CACHE_FILE = /^[0-9a-f]{64}\.json$/;
|
|
10
|
+
var TEMP_FILE = /^[0-9a-f]{64}\.json\.\d+(\.[0-9a-f]+)?\.tmp$/;
|
|
11
|
+
var TEMP_ORPHAN_MS = 6e4;
|
|
12
|
+
var FileCacheStore = class {
|
|
13
|
+
constructor(options) {
|
|
14
|
+
/** Same order contract as `MemoryCacheStore`: oldest written first. */
|
|
15
|
+
this.map = /* @__PURE__ */ new Map();
|
|
16
|
+
if (!options?.dir) throw new Error("FileCacheStore: `dir` is required");
|
|
17
|
+
this.dir = options.dir;
|
|
18
|
+
this.maxEntries = options.maxEntries ?? 500;
|
|
19
|
+
let warned = false;
|
|
20
|
+
this.onError = options.onError ?? ((err) => {
|
|
21
|
+
if (warned) return;
|
|
22
|
+
warned = true;
|
|
23
|
+
console.warn(`[@nordhavnhq/beacon] file cache at ${this.dir} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
|
|
24
|
+
});
|
|
25
|
+
this.load();
|
|
26
|
+
}
|
|
27
|
+
get(key) {
|
|
28
|
+
return this.map.get(key);
|
|
29
|
+
}
|
|
30
|
+
set(key, entry) {
|
|
31
|
+
this.map.delete(key);
|
|
32
|
+
this.map.set(key, entry);
|
|
33
|
+
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
|
+
}
|
|
39
|
+
}
|
|
40
|
+
delete(key) {
|
|
41
|
+
this.map.delete(key);
|
|
42
|
+
this.remove(this.fileOf(key));
|
|
43
|
+
}
|
|
44
|
+
keys() {
|
|
45
|
+
return this.map.keys();
|
|
46
|
+
}
|
|
47
|
+
clear() {
|
|
48
|
+
this.map.clear();
|
|
49
|
+
for (const name of this.list()) {
|
|
50
|
+
if (CACHE_FILE.test(name)) this.remove(path.join(this.dir, name));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// ── Disk ────────────────────────────────────────────────────────────────────
|
|
54
|
+
/** 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);
|
|
57
|
+
}
|
|
58
|
+
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
59
|
+
load() {
|
|
60
|
+
try {
|
|
61
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
62
|
+
} catch (err) {
|
|
63
|
+
this.fail(err);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const found = [];
|
|
67
|
+
for (const name of this.list()) {
|
|
68
|
+
const file = path.join(this.dir, name);
|
|
69
|
+
if (TEMP_FILE.test(name)) {
|
|
70
|
+
if (this.orphaned(file)) this.remove(file);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (!CACHE_FILE.test(name)) continue;
|
|
74
|
+
try {
|
|
75
|
+
const stored = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
76
|
+
if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key)) {
|
|
77
|
+
throw new Error("not a cache file");
|
|
78
|
+
}
|
|
79
|
+
found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs });
|
|
80
|
+
} catch {
|
|
81
|
+
this.remove(file);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
found.sort((a, b) => a.mtime - b.mtime);
|
|
85
|
+
for (const { key, entry } of found) this.map.set(key, entry);
|
|
86
|
+
while (this.map.size > this.maxEntries) {
|
|
87
|
+
const oldest = this.map.keys().next().value;
|
|
88
|
+
if (oldest === void 0) break;
|
|
89
|
+
this.delete(oldest);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
93
|
+
write(key, entry) {
|
|
94
|
+
const file = this.fileOf(key);
|
|
95
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
96
|
+
try {
|
|
97
|
+
const stored = { v: 1, key, entry };
|
|
98
|
+
fs.writeFileSync(tmp, JSON.stringify(stored));
|
|
99
|
+
fs.renameSync(tmp, file);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
this.remove(tmp);
|
|
102
|
+
this.fail(err);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
107
|
+
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
108
|
+
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
109
|
+
* read or stop the process over a cache that merely fell back to memory.
|
|
110
|
+
*/
|
|
111
|
+
fail(err) {
|
|
112
|
+
try {
|
|
113
|
+
const outcome = this.onError(err);
|
|
114
|
+
if (typeof outcome?.then === "function") {
|
|
115
|
+
outcome.then(void 0, () => {
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
} catch {
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
|
|
122
|
+
orphaned(file) {
|
|
123
|
+
try {
|
|
124
|
+
return Date.now() - fs.statSync(file).mtimeMs > TEMP_ORPHAN_MS;
|
|
125
|
+
} catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
remove(file) {
|
|
130
|
+
try {
|
|
131
|
+
fs.rmSync(file, { force: true });
|
|
132
|
+
} catch (err) {
|
|
133
|
+
this.fail(err);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
list() {
|
|
137
|
+
try {
|
|
138
|
+
return fs.readdirSync(this.dir);
|
|
139
|
+
} catch (err) {
|
|
140
|
+
this.fail(err);
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
exports.FileCacheStore = FileCacheStore;
|
|
147
|
+
//# sourceMappingURL=file-store.cjs.map
|
|
148
|
+
//# sourceMappingURL=file-store.cjs.map
|
|
@@ -0,0 +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,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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"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { CacheStore, CacheEntry } from './index.cjs';
|
|
2
|
+
|
|
3
|
+
interface FileCacheStoreOptions {
|
|
4
|
+
/** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */
|
|
5
|
+
dir: string;
|
|
6
|
+
/** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */
|
|
7
|
+
maxEntries?: number;
|
|
8
|
+
/**
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
onError?: (err: unknown) => void;
|
|
14
|
+
}
|
|
15
|
+
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;
|
|
21
|
+
constructor(options: FileCacheStoreOptions);
|
|
22
|
+
get(key: string): CacheEntry | undefined;
|
|
23
|
+
set(key: string, entry: CacheEntry): void;
|
|
24
|
+
delete(key: string): void;
|
|
25
|
+
keys(): Iterable<string>;
|
|
26
|
+
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
|
+
}
|
|
45
|
+
|
|
46
|
+
export { FileCacheStore };
|
|
47
|
+
export type { FileCacheStoreOptions };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { CacheStore, CacheEntry } from './index.js';
|
|
2
|
+
|
|
3
|
+
interface FileCacheStoreOptions {
|
|
4
|
+
/** Directory for the cache files. Created when missing. Put it on a volume that survives a redeploy. */
|
|
5
|
+
dir: string;
|
|
6
|
+
/** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */
|
|
7
|
+
maxEntries?: number;
|
|
8
|
+
/**
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
onError?: (err: unknown) => void;
|
|
14
|
+
}
|
|
15
|
+
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;
|
|
21
|
+
constructor(options: FileCacheStoreOptions);
|
|
22
|
+
get(key: string): CacheEntry | undefined;
|
|
23
|
+
set(key: string, entry: CacheEntry): void;
|
|
24
|
+
delete(key: string): void;
|
|
25
|
+
keys(): Iterable<string>;
|
|
26
|
+
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
|
+
}
|
|
45
|
+
|
|
46
|
+
export { FileCacheStore };
|
|
47
|
+
export type { FileCacheStoreOptions };
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, statSync, writeFileSync, renameSync, rmSync, readdirSync } from 'fs';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
|
|
5
|
+
// src/file-store.ts
|
|
6
|
+
var SUFFIX = ".json";
|
|
7
|
+
var CACHE_FILE = /^[0-9a-f]{64}\.json$/;
|
|
8
|
+
var TEMP_FILE = /^[0-9a-f]{64}\.json\.\d+(\.[0-9a-f]+)?\.tmp$/;
|
|
9
|
+
var TEMP_ORPHAN_MS = 6e4;
|
|
10
|
+
var FileCacheStore = class {
|
|
11
|
+
constructor(options) {
|
|
12
|
+
/** Same order contract as `MemoryCacheStore`: oldest written first. */
|
|
13
|
+
this.map = /* @__PURE__ */ new Map();
|
|
14
|
+
if (!options?.dir) throw new Error("FileCacheStore: `dir` is required");
|
|
15
|
+
this.dir = options.dir;
|
|
16
|
+
this.maxEntries = options.maxEntries ?? 500;
|
|
17
|
+
let warned = false;
|
|
18
|
+
this.onError = options.onError ?? ((err) => {
|
|
19
|
+
if (warned) return;
|
|
20
|
+
warned = true;
|
|
21
|
+
console.warn(`[@nordhavnhq/beacon] file cache at ${this.dir} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
|
|
22
|
+
});
|
|
23
|
+
this.load();
|
|
24
|
+
}
|
|
25
|
+
get(key) {
|
|
26
|
+
return this.map.get(key);
|
|
27
|
+
}
|
|
28
|
+
set(key, entry) {
|
|
29
|
+
this.map.delete(key);
|
|
30
|
+
this.map.set(key, entry);
|
|
31
|
+
this.write(key, entry);
|
|
32
|
+
while (this.map.size > this.maxEntries) {
|
|
33
|
+
const oldest = this.map.keys().next().value;
|
|
34
|
+
if (oldest === void 0) break;
|
|
35
|
+
this.delete(oldest);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
delete(key) {
|
|
39
|
+
this.map.delete(key);
|
|
40
|
+
this.remove(this.fileOf(key));
|
|
41
|
+
}
|
|
42
|
+
keys() {
|
|
43
|
+
return this.map.keys();
|
|
44
|
+
}
|
|
45
|
+
clear() {
|
|
46
|
+
this.map.clear();
|
|
47
|
+
for (const name of this.list()) {
|
|
48
|
+
if (CACHE_FILE.test(name)) this.remove(join(this.dir, name));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// ── Disk ────────────────────────────────────────────────────────────────────
|
|
52
|
+
/** File name per key: a hash, as keys hold `/` and `:` and may be long. */
|
|
53
|
+
fileOf(key) {
|
|
54
|
+
return join(this.dir, createHash("sha256").update(key).digest("hex") + SUFFIX);
|
|
55
|
+
}
|
|
56
|
+
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
57
|
+
load() {
|
|
58
|
+
try {
|
|
59
|
+
mkdirSync(this.dir, { recursive: true });
|
|
60
|
+
} catch (err) {
|
|
61
|
+
this.fail(err);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const found = [];
|
|
65
|
+
for (const name of this.list()) {
|
|
66
|
+
const file = join(this.dir, name);
|
|
67
|
+
if (TEMP_FILE.test(name)) {
|
|
68
|
+
if (this.orphaned(file)) this.remove(file);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!CACHE_FILE.test(name)) continue;
|
|
72
|
+
try {
|
|
73
|
+
const stored = JSON.parse(readFileSync(file, "utf8"));
|
|
74
|
+
if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key)) {
|
|
75
|
+
throw new Error("not a cache file");
|
|
76
|
+
}
|
|
77
|
+
found.push({ key: stored.key, entry: stored.entry, mtime: statSync(file).mtimeMs });
|
|
78
|
+
} catch {
|
|
79
|
+
this.remove(file);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
found.sort((a, b) => a.mtime - b.mtime);
|
|
83
|
+
for (const { key, entry } of found) this.map.set(key, entry);
|
|
84
|
+
while (this.map.size > this.maxEntries) {
|
|
85
|
+
const oldest = this.map.keys().next().value;
|
|
86
|
+
if (oldest === void 0) break;
|
|
87
|
+
this.delete(oldest);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
91
|
+
write(key, entry) {
|
|
92
|
+
const file = this.fileOf(key);
|
|
93
|
+
const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
94
|
+
try {
|
|
95
|
+
const stored = { v: 1, key, entry };
|
|
96
|
+
writeFileSync(tmp, JSON.stringify(stored));
|
|
97
|
+
renameSync(tmp, file);
|
|
98
|
+
} catch (err) {
|
|
99
|
+
this.remove(tmp);
|
|
100
|
+
this.fail(err);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
105
|
+
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
106
|
+
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
107
|
+
* read or stop the process over a cache that merely fell back to memory.
|
|
108
|
+
*/
|
|
109
|
+
fail(err) {
|
|
110
|
+
try {
|
|
111
|
+
const outcome = this.onError(err);
|
|
112
|
+
if (typeof outcome?.then === "function") {
|
|
113
|
+
outcome.then(void 0, () => {
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Whether a temp file is old enough to have been abandoned. Unknown counts as "no". */
|
|
120
|
+
orphaned(file) {
|
|
121
|
+
try {
|
|
122
|
+
return Date.now() - statSync(file).mtimeMs > TEMP_ORPHAN_MS;
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
remove(file) {
|
|
128
|
+
try {
|
|
129
|
+
rmSync(file, { force: true });
|
|
130
|
+
} catch (err) {
|
|
131
|
+
this.fail(err);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
list() {
|
|
135
|
+
try {
|
|
136
|
+
return readdirSync(this.dir);
|
|
137
|
+
} catch (err) {
|
|
138
|
+
this.fail(err);
|
|
139
|
+
return [];
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export { FileCacheStore };
|
|
145
|
+
//# sourceMappingURL=file-store.js.map
|
|
146
|
+
//# sourceMappingURL=file-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/file-store.ts"],"names":[],"mappings":";;;;;AAgDA,IAAM,MAAA,GAAS,OAAA;AAQf,IAAM,UAAA,GAAa,sBAAA;AACnB,IAAM,SAAA,GAAY,8CAAA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AAA,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,MAAA,MAAA,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,OAAO,WAAA,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.js","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"]}
|