@nordhavnhq/beacon 0.4.1 → 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/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 +41 -9
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nordhavn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read caching for the content client. GET responses (schema, record lists,
|
|
3
|
+
* single records, queries) are cached by request key and kept fresh by
|
|
4
|
+
* conditional revalidation: each entry stores the studio's `ETag`, which the
|
|
5
|
+
* client sends back as `If-None-Match`. A cheap project-wide stamp gates whether
|
|
6
|
+
* a revalidation is even attempted, so a stable site serves straight from cache.
|
|
7
|
+
*
|
|
8
|
+
* Swap in a custom `CacheStore` to share a cache across client instances or to
|
|
9
|
+
* back it with something persistent.
|
|
10
|
+
*/
|
|
11
|
+
interface CacheEntry {
|
|
12
|
+
value: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`
|
|
15
|
+
* to revalidate: a `304` means the stored value is still current.
|
|
16
|
+
*/
|
|
17
|
+
etag?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The project stamp this entry was last confirmed current against. When it
|
|
20
|
+
* equals the client's latest known stamp, the entry is served without any
|
|
21
|
+
* network call at all.
|
|
22
|
+
*/
|
|
23
|
+
validatedVersion?: string;
|
|
24
|
+
/** Epoch ms when the entry expires. `0` means it never expires. */
|
|
25
|
+
expiresAt: number;
|
|
26
|
+
/**
|
|
27
|
+
* Epoch ms before which a failed refetch is not retried: until then the entry
|
|
28
|
+
* is served as-is. Set after a transient error, cleared by a fresh value or a
|
|
29
|
+
* `304`.
|
|
30
|
+
*/
|
|
31
|
+
retryAt?: number;
|
|
32
|
+
}
|
|
33
|
+
/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */
|
|
34
|
+
interface CacheStore {
|
|
35
|
+
get(key: string): CacheEntry | undefined;
|
|
36
|
+
set(key: string, entry: CacheEntry): void;
|
|
37
|
+
delete(key: string): void;
|
|
38
|
+
/** Iterate current keys (used for prefix invalidation). */
|
|
39
|
+
keys(): Iterable<string>;
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
|
42
|
+
interface CacheOptions {
|
|
43
|
+
/** Master switch. Default `true`. */
|
|
44
|
+
enabled?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* How long a cached entry survives, in ms. Default `604800000` (7 days).
|
|
47
|
+
*
|
|
48
|
+
* This is NOT how long until content refreshes - revalidation keeps entries
|
|
49
|
+
* current within `revalidate` (seconds) whenever the studio is reachable. The
|
|
50
|
+
* TTL only decides when an entry stops being served blindly and the next read
|
|
51
|
+
* must refetch it. If that refetch fails transiently (studio down, 5xx,
|
|
52
|
+
* network), the expired value is served anyway, so a studio outage degrades
|
|
53
|
+
* to "slightly stale" rather than "site errors" however long it lasts.
|
|
54
|
+
*
|
|
55
|
+
* The one case where it bounds staleness directly is when revalidation is off
|
|
56
|
+
* (`revalidate: false`) or the server has no `/version` endpoint: then content
|
|
57
|
+
* can be up to `ttl` old while the studio is reachable. `0` = never expire.
|
|
58
|
+
*/
|
|
59
|
+
ttl?: number;
|
|
60
|
+
/**
|
|
61
|
+
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
|
+
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
+
* the next check after it lands); an editor viewing a surface preview bypasses
|
|
64
|
+
* the cache entirely and always sees changes instantly.
|
|
65
|
+
*
|
|
66
|
+
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
|
+
* checks at all; the interval only caps the busy case. Each check costs the
|
|
68
|
+
* studio a small API-key lookup, so raise it (a few minutes) if you run many
|
|
69
|
+
* frontends; lower it for a tighter public window. `false` disables checking
|
|
70
|
+
* and leaves you with pure TTL expiry.
|
|
71
|
+
*/
|
|
72
|
+
revalidate?: number | false;
|
|
73
|
+
/**
|
|
74
|
+
* How long a read that already holds a cached value waits on the studio for a
|
|
75
|
+
* fresher one, in ms. Default `1000`. Past it the read gets the cached value
|
|
76
|
+
* and the refresh finishes in the background, so the next read has it.
|
|
77
|
+
*
|
|
78
|
+
* It keeps a slow or hanging studio from slowing your pages down: without it
|
|
79
|
+
* every read after an edit waits for as long as the studio takes, up to
|
|
80
|
+
* `timeout`. The price is that on a slow studio an edit shows one read later.
|
|
81
|
+
*
|
|
82
|
+
* `0` never waits (always serve the cached value, refresh in the background).
|
|
83
|
+
* `false` waits for the studio; choose it where work cannot outlive the
|
|
84
|
+
* request, as on serverless platforms that freeze the process once the
|
|
85
|
+
* response is out. A read with nothing cached always waits.
|
|
86
|
+
*/
|
|
87
|
+
waitForFresh?: number | false;
|
|
88
|
+
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
|
+
maxEntries?: number;
|
|
90
|
+
/** Custom backing store. Defaults to an in-memory store. */
|
|
91
|
+
store?: CacheStore;
|
|
92
|
+
}
|
|
93
|
+
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
94
|
+
declare class MemoryCacheStore implements CacheStore {
|
|
95
|
+
private maxEntries;
|
|
96
|
+
private map;
|
|
97
|
+
constructor(maxEntries?: number);
|
|
98
|
+
get(key: string): CacheEntry | undefined;
|
|
99
|
+
set(key: string, entry: CacheEntry): void;
|
|
100
|
+
delete(key: string): void;
|
|
101
|
+
keys(): Iterable<string>;
|
|
102
|
+
clear(): void;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation
|
|
106
|
+
* bookkeeping (etag + validated stamp), and prefix invalidation, so the client
|
|
107
|
+
* only deals in cache keys.
|
|
108
|
+
*/
|
|
109
|
+
declare class ContentCache {
|
|
110
|
+
readonly enabled: boolean;
|
|
111
|
+
private ttl;
|
|
112
|
+
/** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */
|
|
113
|
+
private retryDelay;
|
|
114
|
+
private store;
|
|
115
|
+
constructor(opts?: CacheOptions);
|
|
116
|
+
/**
|
|
117
|
+
* The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
|
|
118
|
+
* whole entry (value + etag + validated stamp) so the client can decide
|
|
119
|
+
* whether to serve it, revalidate it, or fall back to it on error.
|
|
120
|
+
*
|
|
121
|
+
* An expired entry is left in the store (the refetch overwrites it, or
|
|
122
|
+
* `maxEntries` evicts it) so `stale` can still fall back to it.
|
|
123
|
+
*/
|
|
124
|
+
peek(key: string, now: number): CacheEntry | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* The entry for `key` whether or not its TTL has run out: the last good value
|
|
127
|
+
* to serve when a refetch fails transiently.
|
|
128
|
+
*/
|
|
129
|
+
stale(key: string): CacheEntry | undefined;
|
|
130
|
+
/** Store a freshly fetched value with its validator and the stamp it is current against. */
|
|
131
|
+
set(key: string, value: unknown, opts: {
|
|
132
|
+
etag?: string;
|
|
133
|
+
version?: string;
|
|
134
|
+
}, now: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Record that an existing entry is still current as of `version` (after a
|
|
137
|
+
* `304`), refreshing its TTL without touching the value. No-op if it is gone.
|
|
138
|
+
*/
|
|
139
|
+
confirm(key: string, version: string | undefined, now: number): void;
|
|
140
|
+
/**
|
|
141
|
+
* Record that refetching `key` from `from` just failed transiently, so reads
|
|
142
|
+
* serve it as-is for a while instead of each waiting on an unreachable studio.
|
|
143
|
+
* Returns the entry to serve: `from`, or the newer one a concurrent read stored
|
|
144
|
+
* in the meantime (left unpaused, since its own fetch succeeded).
|
|
145
|
+
*/
|
|
146
|
+
backoff(key: string, from: CacheEntry, now: number): CacheEntry;
|
|
147
|
+
/**
|
|
148
|
+
* Mark `key` as due for a refetch while keeping its value to fall back on:
|
|
149
|
+
* the next read asks the studio again whatever the stamp says, and still
|
|
150
|
+
* serves this value if the studio does not answer. For when the stored value
|
|
151
|
+
* may be outdated but there is no telling - dropping it would throw away the
|
|
152
|
+
* only thing left to show during an outage. No-op for a key that is not held.
|
|
153
|
+
*/
|
|
154
|
+
expire(key: string): void;
|
|
155
|
+
/** `expire` for every key that starts with `prefix`. */
|
|
156
|
+
expirePrefix(prefix: string): void;
|
|
157
|
+
/** Drop one exact key. */
|
|
158
|
+
delete(key: string): void;
|
|
159
|
+
/** Drop every key that starts with `prefix`. */
|
|
160
|
+
deletePrefix(prefix: string): void;
|
|
161
|
+
clear(): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { MemoryCacheStore as M, ContentCache as c };
|
|
165
|
+
export type { CacheStore as C, CacheEntry as a, CacheOptions as b };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read caching for the content client. GET responses (schema, record lists,
|
|
3
|
+
* single records, queries) are cached by request key and kept fresh by
|
|
4
|
+
* conditional revalidation: each entry stores the studio's `ETag`, which the
|
|
5
|
+
* client sends back as `If-None-Match`. A cheap project-wide stamp gates whether
|
|
6
|
+
* a revalidation is even attempted, so a stable site serves straight from cache.
|
|
7
|
+
*
|
|
8
|
+
* Swap in a custom `CacheStore` to share a cache across client instances or to
|
|
9
|
+
* back it with something persistent.
|
|
10
|
+
*/
|
|
11
|
+
interface CacheEntry {
|
|
12
|
+
value: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`
|
|
15
|
+
* to revalidate: a `304` means the stored value is still current.
|
|
16
|
+
*/
|
|
17
|
+
etag?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The project stamp this entry was last confirmed current against. When it
|
|
20
|
+
* equals the client's latest known stamp, the entry is served without any
|
|
21
|
+
* network call at all.
|
|
22
|
+
*/
|
|
23
|
+
validatedVersion?: string;
|
|
24
|
+
/** Epoch ms when the entry expires. `0` means it never expires. */
|
|
25
|
+
expiresAt: number;
|
|
26
|
+
/**
|
|
27
|
+
* Epoch ms before which a failed refetch is not retried: until then the entry
|
|
28
|
+
* is served as-is. Set after a transient error, cleared by a fresh value or a
|
|
29
|
+
* `304`.
|
|
30
|
+
*/
|
|
31
|
+
retryAt?: number;
|
|
32
|
+
}
|
|
33
|
+
/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */
|
|
34
|
+
interface CacheStore {
|
|
35
|
+
get(key: string): CacheEntry | undefined;
|
|
36
|
+
set(key: string, entry: CacheEntry): void;
|
|
37
|
+
delete(key: string): void;
|
|
38
|
+
/** Iterate current keys (used for prefix invalidation). */
|
|
39
|
+
keys(): Iterable<string>;
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
|
42
|
+
interface CacheOptions {
|
|
43
|
+
/** Master switch. Default `true`. */
|
|
44
|
+
enabled?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* How long a cached entry survives, in ms. Default `604800000` (7 days).
|
|
47
|
+
*
|
|
48
|
+
* This is NOT how long until content refreshes - revalidation keeps entries
|
|
49
|
+
* current within `revalidate` (seconds) whenever the studio is reachable. The
|
|
50
|
+
* TTL only decides when an entry stops being served blindly and the next read
|
|
51
|
+
* must refetch it. If that refetch fails transiently (studio down, 5xx,
|
|
52
|
+
* network), the expired value is served anyway, so a studio outage degrades
|
|
53
|
+
* to "slightly stale" rather than "site errors" however long it lasts.
|
|
54
|
+
*
|
|
55
|
+
* The one case where it bounds staleness directly is when revalidation is off
|
|
56
|
+
* (`revalidate: false`) or the server has no `/version` endpoint: then content
|
|
57
|
+
* can be up to `ttl` old while the studio is reachable. `0` = never expire.
|
|
58
|
+
*/
|
|
59
|
+
ttl?: number;
|
|
60
|
+
/**
|
|
61
|
+
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
|
+
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
+
* the next check after it lands); an editor viewing a surface preview bypasses
|
|
64
|
+
* the cache entirely and always sees changes instantly.
|
|
65
|
+
*
|
|
66
|
+
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
|
+
* checks at all; the interval only caps the busy case. Each check costs the
|
|
68
|
+
* studio a small API-key lookup, so raise it (a few minutes) if you run many
|
|
69
|
+
* frontends; lower it for a tighter public window. `false` disables checking
|
|
70
|
+
* and leaves you with pure TTL expiry.
|
|
71
|
+
*/
|
|
72
|
+
revalidate?: number | false;
|
|
73
|
+
/**
|
|
74
|
+
* How long a read that already holds a cached value waits on the studio for a
|
|
75
|
+
* fresher one, in ms. Default `1000`. Past it the read gets the cached value
|
|
76
|
+
* and the refresh finishes in the background, so the next read has it.
|
|
77
|
+
*
|
|
78
|
+
* It keeps a slow or hanging studio from slowing your pages down: without it
|
|
79
|
+
* every read after an edit waits for as long as the studio takes, up to
|
|
80
|
+
* `timeout`. The price is that on a slow studio an edit shows one read later.
|
|
81
|
+
*
|
|
82
|
+
* `0` never waits (always serve the cached value, refresh in the background).
|
|
83
|
+
* `false` waits for the studio; choose it where work cannot outlive the
|
|
84
|
+
* request, as on serverless platforms that freeze the process once the
|
|
85
|
+
* response is out. A read with nothing cached always waits.
|
|
86
|
+
*/
|
|
87
|
+
waitForFresh?: number | false;
|
|
88
|
+
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
|
+
maxEntries?: number;
|
|
90
|
+
/** Custom backing store. Defaults to an in-memory store. */
|
|
91
|
+
store?: CacheStore;
|
|
92
|
+
}
|
|
93
|
+
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
94
|
+
declare class MemoryCacheStore implements CacheStore {
|
|
95
|
+
private maxEntries;
|
|
96
|
+
private map;
|
|
97
|
+
constructor(maxEntries?: number);
|
|
98
|
+
get(key: string): CacheEntry | undefined;
|
|
99
|
+
set(key: string, entry: CacheEntry): void;
|
|
100
|
+
delete(key: string): void;
|
|
101
|
+
keys(): Iterable<string>;
|
|
102
|
+
clear(): void;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation
|
|
106
|
+
* bookkeeping (etag + validated stamp), and prefix invalidation, so the client
|
|
107
|
+
* only deals in cache keys.
|
|
108
|
+
*/
|
|
109
|
+
declare class ContentCache {
|
|
110
|
+
readonly enabled: boolean;
|
|
111
|
+
private ttl;
|
|
112
|
+
/** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */
|
|
113
|
+
private retryDelay;
|
|
114
|
+
private store;
|
|
115
|
+
constructor(opts?: CacheOptions);
|
|
116
|
+
/**
|
|
117
|
+
* The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
|
|
118
|
+
* whole entry (value + etag + validated stamp) so the client can decide
|
|
119
|
+
* whether to serve it, revalidate it, or fall back to it on error.
|
|
120
|
+
*
|
|
121
|
+
* An expired entry is left in the store (the refetch overwrites it, or
|
|
122
|
+
* `maxEntries` evicts it) so `stale` can still fall back to it.
|
|
123
|
+
*/
|
|
124
|
+
peek(key: string, now: number): CacheEntry | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* The entry for `key` whether or not its TTL has run out: the last good value
|
|
127
|
+
* to serve when a refetch fails transiently.
|
|
128
|
+
*/
|
|
129
|
+
stale(key: string): CacheEntry | undefined;
|
|
130
|
+
/** Store a freshly fetched value with its validator and the stamp it is current against. */
|
|
131
|
+
set(key: string, value: unknown, opts: {
|
|
132
|
+
etag?: string;
|
|
133
|
+
version?: string;
|
|
134
|
+
}, now: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Record that an existing entry is still current as of `version` (after a
|
|
137
|
+
* `304`), refreshing its TTL without touching the value. No-op if it is gone.
|
|
138
|
+
*/
|
|
139
|
+
confirm(key: string, version: string | undefined, now: number): void;
|
|
140
|
+
/**
|
|
141
|
+
* Record that refetching `key` from `from` just failed transiently, so reads
|
|
142
|
+
* serve it as-is for a while instead of each waiting on an unreachable studio.
|
|
143
|
+
* Returns the entry to serve: `from`, or the newer one a concurrent read stored
|
|
144
|
+
* in the meantime (left unpaused, since its own fetch succeeded).
|
|
145
|
+
*/
|
|
146
|
+
backoff(key: string, from: CacheEntry, now: number): CacheEntry;
|
|
147
|
+
/**
|
|
148
|
+
* Mark `key` as due for a refetch while keeping its value to fall back on:
|
|
149
|
+
* the next read asks the studio again whatever the stamp says, and still
|
|
150
|
+
* serves this value if the studio does not answer. For when the stored value
|
|
151
|
+
* may be outdated but there is no telling - dropping it would throw away the
|
|
152
|
+
* only thing left to show during an outage. No-op for a key that is not held.
|
|
153
|
+
*/
|
|
154
|
+
expire(key: string): void;
|
|
155
|
+
/** `expire` for every key that starts with `prefix`. */
|
|
156
|
+
expirePrefix(prefix: string): void;
|
|
157
|
+
/** Drop one exact key. */
|
|
158
|
+
delete(key: string): void;
|
|
159
|
+
/** Drop every key that starts with `prefix`. */
|
|
160
|
+
deletePrefix(prefix: string): void;
|
|
161
|
+
clear(): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { MemoryCacheStore as M, ContentCache as c };
|
|
165
|
+
export type { CacheStore as C, CacheEntry as a, CacheOptions as b };
|
|
@@ -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,M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AAM,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 };
|