@cardonjs/cache 0.0.0-stage → 0.0.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 +414 -2
- package/dist/cache.d.ts +136 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +503 -0
- package/dist/cache.js.map +1 -0
- package/dist/contract.d.ts +26 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/contract.js +158 -0
- package/dist/contract.js.map +1 -0
- package/dist/duration.d.ts +13 -0
- package/dist/duration.d.ts.map +1 -0
- package/dist/duration.js +21 -0
- package/dist/duration.js.map +1 -0
- package/dist/envelope.d.ts +21 -0
- package/dist/envelope.d.ts.map +1 -0
- package/dist/envelope.js +89 -0
- package/dist/envelope.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/keys.d.ts +35 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +88 -0
- package/dist/keys.js.map +1 -0
- package/dist/store.d.ts +26 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +2 -0
- package/dist/store.js.map +1 -0
- package/dist/testing.d.ts +16 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +44 -0
- package/dist/testing.js.map +1 -0
- package/llms.txt +210 -0
- package/package.json +61 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matias Terradas
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,415 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cardonjs/cache
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A data cache for Cardón apps: "remember this value for a while, and forget it when the data
|
|
4
|
+
changes". `remember` reads through with a time to live, every value is checked with a Zod schema
|
|
5
|
+
on the way in and out, and `invalidateTags` forgets every entry that depends on, say, one product
|
|
6
|
+
at once. Tags are implemented here, once, over any store; the store itself only gets, sets and
|
|
7
|
+
deletes strings. The Workers KV store is [`@cardonjs/cache-kv`](../cache-kv/README.md).
|
|
8
|
+
|
|
9
|
+
A cache is never the source of truth: every read can miss, and a store that fails on a read or a
|
|
10
|
+
write is a miss, never an error for the caller. Only `delete` and `invalidateTags` reject, because
|
|
11
|
+
a silent failure there would serve stale data. This is a data cache, not an HTTP response cache.
|
|
12
|
+
|
|
13
|
+
Standard web APIs only (runs on Workers, Node, Bun and Deno). Peer dependencies: `zod`, and
|
|
14
|
+
`@cardonjs/testing` for the contract suite only.
|
|
15
|
+
|
|
16
|
+
For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
|
|
17
|
+
|
|
18
|
+
## Rules
|
|
19
|
+
|
|
20
|
+
- **The key must name everything the value depends on.** Data that differs per user, tenant or
|
|
21
|
+
role needs that id in the key (`cacheKey("orders", tenantId, userId)`); otherwise one caller is
|
|
22
|
+
served another's data. A route's cached value depends on everything its handler reads: the
|
|
23
|
+
identity, the tenant, query parameters, headers.
|
|
24
|
+
- Never cache secrets, tokens or credentials. Think twice about personal data: the store keeps it
|
|
25
|
+
until the entry expires, and invalidation is not instant everywhere (KV takes up to 60 seconds
|
|
26
|
+
in other locations). Only what the schema keeps is stored: use a schema without the columns
|
|
27
|
+
you must not cache.
|
|
28
|
+
- Not for data that must be right immediately (permissions, balances, stock at checkout), and
|
|
29
|
+
never cache an authorization decision.
|
|
30
|
+
- Invalidate after the write is committed, not before: an invalidation before the commit lets a
|
|
31
|
+
concurrent read cache the old data again.
|
|
32
|
+
- No personal data in keys or tags: key names show up in the KV dashboard and in listings. Use
|
|
33
|
+
ids, not emails or names; hash free text with `hashedKeyPart`.
|
|
34
|
+
- Key parts that come from a request (a search query, a filter) must be length-validated or
|
|
35
|
+
hashed: `cacheKey` throws for a key over 200 characters, and non-ASCII text grows about 9 times
|
|
36
|
+
when percent-encoded. `cacheKey("search", await hashedKeyPart(query))` is always 71 characters.
|
|
37
|
+
- To forget a record after a change, tag its entries with a per-record tag
|
|
38
|
+
(`tags: [cacheKey("product", id)]`) and call `invalidateTags`. `delete` drops one entry; it is
|
|
39
|
+
not an invalidation (see [`delete`](#cachedeletekey-and-cacheinvalidatetagstags)).
|
|
40
|
+
|
|
41
|
+
## Example
|
|
42
|
+
|
|
43
|
+
A public catalog read through the cache, and an admin route that changes a price and then
|
|
44
|
+
invalidates the product and its category:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { requireAuth, requireRole } from "@cardonjs/auth";
|
|
48
|
+
import { cacheKey, createCache } from "@cardonjs/cache";
|
|
49
|
+
import { kvCacheStore } from "@cardonjs/cache-kv";
|
|
50
|
+
import {
|
|
51
|
+
type CardonEnv,
|
|
52
|
+
createApp,
|
|
53
|
+
createLogger,
|
|
54
|
+
defineModule,
|
|
55
|
+
errorEnvelopeSchema,
|
|
56
|
+
idSchema,
|
|
57
|
+
NotFoundError,
|
|
58
|
+
ok,
|
|
59
|
+
successEnvelope,
|
|
60
|
+
} from "@cardonjs/core";
|
|
61
|
+
import { createRoute, z } from "@hono/zod-openapi";
|
|
62
|
+
|
|
63
|
+
// What is cached: only these fields are stored and returned, whatever else a row holds.
|
|
64
|
+
const productSchema = z.object({
|
|
65
|
+
id: z.string(),
|
|
66
|
+
categoryId: z.string(),
|
|
67
|
+
name: z.string(),
|
|
68
|
+
price: z.number().int(),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
type Bindings = { CACHE: KVNamespace; DB: D1Database };
|
|
72
|
+
const logger = createLogger();
|
|
73
|
+
const adapters = (env: Bindings) => ({
|
|
74
|
+
auth: sessionAuth(env), // your Authenticator
|
|
75
|
+
products: productsRepository(env.DB), // your repository
|
|
76
|
+
cache: createCache({
|
|
77
|
+
store: kvCacheStore(env.CACHE),
|
|
78
|
+
namespace: "shop",
|
|
79
|
+
defaultTtl: "5m",
|
|
80
|
+
// The operation and the error's name: never the key or the value.
|
|
81
|
+
onError: (error, operation) =>
|
|
82
|
+
logger.warn("cache failed", {
|
|
83
|
+
operation,
|
|
84
|
+
error: error instanceof Error ? error.name : "unknown",
|
|
85
|
+
}),
|
|
86
|
+
}),
|
|
87
|
+
});
|
|
88
|
+
type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
|
|
89
|
+
|
|
90
|
+
// One tag per record: invalidating it forgets every entry built from that record.
|
|
91
|
+
const productTag = (id: string) => cacheKey("product", id);
|
|
92
|
+
const categoryTag = (id: string) => cacheKey("category", id);
|
|
93
|
+
|
|
94
|
+
const listProducts = createRoute({
|
|
95
|
+
method: "get",
|
|
96
|
+
path: "/categories/{categoryId}/products",
|
|
97
|
+
tags: ["Catalog"],
|
|
98
|
+
summary: "List the products of a category",
|
|
99
|
+
request: { params: z.object({ categoryId: idSchema }) },
|
|
100
|
+
responses: {
|
|
101
|
+
200: {
|
|
102
|
+
description: "The products",
|
|
103
|
+
content: { "application/json": { schema: successEnvelope(z.array(productSchema)) } },
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const getProduct = createRoute({
|
|
109
|
+
method: "get",
|
|
110
|
+
path: "/products/{id}",
|
|
111
|
+
tags: ["Catalog"],
|
|
112
|
+
summary: "Get a product",
|
|
113
|
+
request: { params: z.object({ id: idSchema }) },
|
|
114
|
+
responses: {
|
|
115
|
+
200: {
|
|
116
|
+
description: "The product",
|
|
117
|
+
content: { "application/json": { schema: successEnvelope(productSchema) } },
|
|
118
|
+
},
|
|
119
|
+
404: {
|
|
120
|
+
description: "No such product",
|
|
121
|
+
content: { "application/json": { schema: errorEnvelopeSchema } },
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const setPrice = createRoute({
|
|
127
|
+
method: "put",
|
|
128
|
+
path: "/products/{id}/price",
|
|
129
|
+
tags: ["Catalog"],
|
|
130
|
+
summary: "Change the price of a product",
|
|
131
|
+
middleware: requireRole("admin"),
|
|
132
|
+
request: {
|
|
133
|
+
params: z.object({ id: idSchema }),
|
|
134
|
+
body: {
|
|
135
|
+
required: true,
|
|
136
|
+
content: {
|
|
137
|
+
"application/json": { schema: z.object({ price: z.number().int().positive() }) },
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
responses: {
|
|
142
|
+
200: {
|
|
143
|
+
description: "The product",
|
|
144
|
+
content: { "application/json": { schema: successEnvelope(productSchema) } },
|
|
145
|
+
},
|
|
146
|
+
404: {
|
|
147
|
+
description: "No such product",
|
|
148
|
+
content: { "application/json": { schema: errorEnvelopeSchema } },
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
const catalogModule = defineModule<AppEnv>({
|
|
154
|
+
name: "catalog",
|
|
155
|
+
prefix: "/v1",
|
|
156
|
+
routes: (app) => {
|
|
157
|
+
app.openapi(listProducts, async (c) => {
|
|
158
|
+
const { categoryId } = c.req.valid("param");
|
|
159
|
+
// The same list for every caller, so the key names the category only.
|
|
160
|
+
const products = await c.var.adapters.cache.remember(
|
|
161
|
+
cacheKey("products", "by-category", categoryId),
|
|
162
|
+
{ schema: z.array(productSchema), ttl: "10m", tags: [categoryTag(categoryId)] },
|
|
163
|
+
() => c.var.adapters.products.listByCategory(categoryId),
|
|
164
|
+
);
|
|
165
|
+
return ok(c, products);
|
|
166
|
+
});
|
|
167
|
+
app.openapi(getProduct, async (c) => {
|
|
168
|
+
const { id } = c.req.valid("param");
|
|
169
|
+
const product = await c.var.adapters.cache.remember(
|
|
170
|
+
cacheKey("product", id),
|
|
171
|
+
{ schema: productSchema.nullable(), tags: [productTag(id)] },
|
|
172
|
+
async () => (await c.var.adapters.products.get(id)) ?? null, // "not found" is cached too
|
|
173
|
+
);
|
|
174
|
+
if (!product) throw new NotFoundError("Product not found");
|
|
175
|
+
return ok(c, product);
|
|
176
|
+
});
|
|
177
|
+
app.openapi(setPrice, async (c) => {
|
|
178
|
+
const { id } = c.req.valid("param");
|
|
179
|
+
const product = await c.var.adapters.products.setPrice(id, c.req.valid("json").price);
|
|
180
|
+
if (!product) throw new NotFoundError("Product not found");
|
|
181
|
+
// After the write is committed, never before.
|
|
182
|
+
await c.var.adapters.cache.invalidateTags([productTag(id), categoryTag(product.categoryId)]);
|
|
183
|
+
return ok(c, product);
|
|
184
|
+
});
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
export default createApp(adapters, {
|
|
189
|
+
guard: requireAuth<AppEnv>({
|
|
190
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
191
|
+
public: ["GET /v1/categories/:categoryId/products", "GET /v1/products/:id"],
|
|
192
|
+
}),
|
|
193
|
+
}).register(catalogModule);
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Build the cache in the adapters factory: core calls it once per isolate, so concurrent `remember`
|
|
197
|
+
calls of the isolate share one load. If `invalidateTags` rejects (the store failed, also after
|
|
198
|
+
its retry), the price is already changed: the request answers `500` and the cached entries stay
|
|
199
|
+
until their `ttl` (10 and 5 minutes here). Keep the `ttl` as short as the data can be stale.
|
|
200
|
+
|
|
201
|
+
To read an entry without loading it, pass the tags it is written with, so an entry stored without
|
|
202
|
+
them is never served after an invalidation:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
const cached = await cache.get(cacheKey("product", id), {
|
|
206
|
+
schema: productSchema.nullable(),
|
|
207
|
+
tags: [productTag(id)],
|
|
208
|
+
}); // undefined on a miss
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## API
|
|
212
|
+
|
|
213
|
+
### `createCache(options)`
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
createCache({
|
|
217
|
+
store, // a CacheStore, e.g. kvCacheStore(env.CACHE)
|
|
218
|
+
namespace, // prefix of every store key and tag (default "cache")
|
|
219
|
+
defaultTtl, // when a call gives no ttl (e.g. "5m"); without it every write needs one
|
|
220
|
+
maxTtl, // longest ttl (default "1d", at most "30d")
|
|
221
|
+
maxValueBytes, // largest value, UTF-8 bytes of its JSON (default 1 MiB, at most 24 MiB)
|
|
222
|
+
invalidateRetryDelay, // ms before invalidateTags retries a failed write (default 1100, 0: never)
|
|
223
|
+
onError, // (error, operation: "get" | "set") => void
|
|
224
|
+
now, // () => Date, for tests
|
|
225
|
+
sleep, // (ms) => Promise<void>, for tests of the retry
|
|
226
|
+
}): Cache
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Synchronous, no I/O. Throws a `TypeError` for invalid options (the message never includes a
|
|
230
|
+
value). A duration is whole seconds (`600`) or a string of a whole number and `s`, `m`, `h` or `d`
|
|
231
|
+
(`"10m"`, `"1d"`). A namespace is 1 to 64 of `A-Z a-z 0-9 . _ -`, starting with a letter or digit.
|
|
232
|
+
Several caches (or apps) can share one store with different namespaces; tags are per namespace,
|
|
233
|
+
so `invalidateTags` on one cache never touches another's entries.
|
|
234
|
+
|
|
235
|
+
Schemas must be synchronous (no async refinements) and of plain JSON (dates as ISO strings, no
|
|
236
|
+
`transform`): the value is stored as JSON and parsed with the schema on the way out. A schema that
|
|
237
|
+
throws or is async on a read makes that read a miss, reported through `onError`.
|
|
238
|
+
|
|
239
|
+
### `cache.get(key, { schema, tags? })`
|
|
240
|
+
|
|
241
|
+
The value, or `undefined` on a miss. A miss is: no entry, an entry past its time, an entry whose
|
|
242
|
+
tags were invalidated (or whose tag versions the store lost), a stored value that does not match
|
|
243
|
+
`schema`, anything in the store that is not an envelope this package wrote, or a store failure
|
|
244
|
+
(reported through `onError`).
|
|
245
|
+
|
|
246
|
+
**Pass `tags`.** With `tags`, an entry stored without one of them is a miss. Without `tags`, `get`
|
|
247
|
+
also serves an entry written by a plain `set` without tags, even after `invalidateTags`: by
|
|
248
|
+
design (`get` cannot know which tags you expect), so pass the tags the entry is written with.
|
|
249
|
+
|
|
250
|
+
### `cache.set(key, value, { ttl?, tags?, schema? })`
|
|
251
|
+
|
|
252
|
+
Stores `value` and resolves whether it was stored: `false` for `undefined` (it means "nothing";
|
|
253
|
+
`null` is a value), a value that does not serialize to JSON or is over `maxValueBytes`, or a store
|
|
254
|
+
failure (each but `undefined` reported through `onError`). Up to 8 tags. With `schema`, the value
|
|
255
|
+
is parsed first and only what the schema keeps is stored (a value it refuses is a `TypeError`);
|
|
256
|
+
without it, `set` stores what it is given. A load of the same key in flight in this isolate does
|
|
257
|
+
not overwrite it. Prefer `remember`: `set` cannot know whether `value` was read before or after an
|
|
258
|
+
invalidation.
|
|
259
|
+
|
|
260
|
+
### `cache.remember(key, { schema, ttl?, tags? }, loader)`
|
|
261
|
+
|
|
262
|
+
The cached value, or the loader's result, stored for next time:
|
|
263
|
+
|
|
264
|
+
- The loader runs only on a miss. A stored value that does not match `schema` is a miss and is
|
|
265
|
+
replaced.
|
|
266
|
+
- **Only what the schema keeps is stored and returned.** The loader's result is parsed with
|
|
267
|
+
`schema`: a row with a `passwordHash` column and a schema without it stores and returns the row
|
|
268
|
+
without it, on a miss and on a hit alike. A result the schema refuses is a programming error:
|
|
269
|
+
`remember` rejects with a `TypeError` (its message holds no key and no value) and stores
|
|
270
|
+
nothing. Besides a throwing loader, it is the one case where `remember` rejects.
|
|
271
|
+
- Concurrent calls for the same key in the same isolate share one loader call, as long as the
|
|
272
|
+
load in flight has every tag of the later call. Each caller gets its own copy of the value
|
|
273
|
+
(parsed from the stored JSON text with its own schema), the one that ran the loader too, so a
|
|
274
|
+
handler that mutates its result never changes another's. Across isolates and locations there is
|
|
275
|
+
no lock: several may load at once, and the last write wins.
|
|
276
|
+
- A load in flight that `delete`, `set` or `invalidateTags` (with one of its tags) affects never
|
|
277
|
+
writes its result and is never joined by a later call: a call that starts after an invalidation
|
|
278
|
+
resolved runs its own load.
|
|
279
|
+
- A loader that throws is not cached, and its error propagates (to every caller that shared it);
|
|
280
|
+
the next call loads again.
|
|
281
|
+
- A parsed result that is `undefined`, does not serialize to JSON, is over `maxValueBytes`, or
|
|
282
|
+
would not match `schema` after a JSON round trip (a `Date`, a `Map`, a `bigint`) is returned and
|
|
283
|
+
not cached.
|
|
284
|
+
- The tag versions are read (and created for a tag that has none) before the loader runs, so an
|
|
285
|
+
invalidation that lands while it loads makes the loaded entry a miss.
|
|
286
|
+
|
|
287
|
+
### `cache.delete(key)` and `cache.invalidateTags(tags)`
|
|
288
|
+
|
|
289
|
+
`delete` removes one entry; `invalidateTags` makes every entry with any of `tags` (up to 64 per
|
|
290
|
+
call) a miss, by writing a new version of each tag. Both reject when the store fails.
|
|
291
|
+
|
|
292
|
+
- **`delete` is for dropping an entry, not for invalidating after a write.** In this isolate, a
|
|
293
|
+
`remember` that was loading when `delete` ran does not write its (possibly old) result. In
|
|
294
|
+
another isolate it still can: its loader read the row before the change, `delete` resolves,
|
|
295
|
+
then its write lands, and the old value stays for its full `ttl`. A new tag version cannot be
|
|
296
|
+
defeated that way (the late write carries the old version, so it is a miss): for a record that
|
|
297
|
+
changes, tag its entries with a per-record tag and call `invalidateTags`.
|
|
298
|
+
- With KV, a second write to the same tag within a second fails (one write per second per key):
|
|
299
|
+
`invalidateTags` waits `invalidateRetryDelay` (1.1 seconds by default) and tries a failed tag
|
|
300
|
+
once more, and rejects only when the retry fails too. That conflict is rare, and it adds that
|
|
301
|
+
delay to the request when it happens.
|
|
302
|
+
|
|
303
|
+
### `cacheKey(...parts)` and `hashedKeyPart(text)`
|
|
304
|
+
|
|
305
|
+
`cacheKey` joins strings and finite numbers with `:`, percent-encoding each part, so a part
|
|
306
|
+
holding a `:` cannot collide with another key: `cacheKey("a:b", "c")` is `"a%3Ab:c"`,
|
|
307
|
+
`cacheKey("a", "b:c")` is `"a:b%3Ac"`. A number is its text: `cacheKey(1)` equals `cacheKey("1")`.
|
|
308
|
+
Throws a `TypeError` for no parts, an empty part, another type, or a key over 200 characters.
|
|
309
|
+
Every key and tag is 1 to 200 printable ASCII characters without spaces; any other is a
|
|
310
|
+
`TypeError` from the call that uses it.
|
|
311
|
+
|
|
312
|
+
`await hashedKeyPart(text)` is the SHA-256 of any text in hex (64 characters): use it for a part
|
|
313
|
+
that comes from a request, so the key length is fixed and the text never shows in key names.
|
|
314
|
+
Throws a `TypeError` for a non-string or an unpaired surrogate.
|
|
315
|
+
|
|
316
|
+
### `onError(error, operation)`
|
|
317
|
+
|
|
318
|
+
Called when a store read (`"get"`) or write (`"set"`) fails, a schema throws on a read, or a value
|
|
319
|
+
is not stored. It gets the error and the operation, never the key (it may hold an id) or the
|
|
320
|
+
value. A throwing `onError` is ignored. Store errors may carry the provider's own message: log the
|
|
321
|
+
error's name, as in the example, unless you know the store's messages are safe.
|
|
322
|
+
|
|
323
|
+
## Tags
|
|
324
|
+
|
|
325
|
+
Each tag has a version in the store (`<namespace>:t:<tag>`): a random string, written by
|
|
326
|
+
`invalidateTags`, or by the first write of an entry with a tag that has none. An entry keeps the
|
|
327
|
+
version each of its tags had before its value was computed, and a read compares them: any
|
|
328
|
+
difference, or a tag whose version is gone, is a miss. So invalidating a tag costs one write,
|
|
329
|
+
however many entries carry it, a store that loses a version early only costs misses, and a read of
|
|
330
|
+
an entry with tags also reads its tags' versions, in parallel (at most 8 tags per entry). Tag
|
|
331
|
+
versions are stored for 60 days, twice the longest `maxTtl`.
|
|
332
|
+
|
|
333
|
+
## Entries
|
|
334
|
+
|
|
335
|
+
The store sees an opaque string: a JSON envelope with the value, its expiry, its tag versions and
|
|
336
|
+
a format version. Whatever a store returns is untrusted: anything that is not that envelope (not
|
|
337
|
+
JSON, another format, a value written by another tool, an expiry further away than `maxTtl`) is a
|
|
338
|
+
miss, decoding never throws, `__proto__` keys are dropped, and the value is then checked with the
|
|
339
|
+
caller's schema. Every entry expires: the cache checks the entry's own expiry, so a store may keep
|
|
340
|
+
it longer (KV keeps at least 60 seconds).
|
|
341
|
+
|
|
342
|
+
## Workers KV
|
|
343
|
+
|
|
344
|
+
With [`@cardonjs/cache-kv`](../cache-kv/README.md) (Cloudflare documentation, checked
|
|
345
|
+
2026-11-27):
|
|
346
|
+
|
|
347
|
+
- KV is eventually consistent: a write or an invalidation is visible at once in the location that
|
|
348
|
+
made it and can take up to 60 seconds (or the store's `cacheTtl`) elsewhere. A cache on KV is
|
|
349
|
+
wrong for data that must be right immediately.
|
|
350
|
+
- KV's minimum expiration is 60 seconds: the store keeps an entry for at least that, and the cache
|
|
351
|
+
checks the entry's own expiry, so a `ttl` of 10 seconds works.
|
|
352
|
+
- One write per second per key: a second write within a second fails. For an entry it is a failed
|
|
353
|
+
write (a miss next time); `invalidateTags` retries a failed tag once after
|
|
354
|
+
`invalidateRetryDelay`, and rejects if that fails too.
|
|
355
|
+
- A key is at most 512 bytes (the longest this package builds is 267) and a value at most 25 MiB;
|
|
356
|
+
`maxValueBytes` caps a value at 1 MiB by default.
|
|
357
|
+
|
|
358
|
+
## `CacheStore`
|
|
359
|
+
|
|
360
|
+
```ts
|
|
361
|
+
interface CacheStore {
|
|
362
|
+
/** The stored string, or `undefined`. May return an entry past its time: `cache` checks it. */
|
|
363
|
+
get(key: string): Promise<string | undefined>;
|
|
364
|
+
/** Stores for at least `ttlSeconds` (a store may keep it longer, never forever). */
|
|
365
|
+
set(key: string, value: string, ttlSeconds: number): Promise<void>;
|
|
366
|
+
delete(key: string): Promise<void>;
|
|
367
|
+
}
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
A store is a new adapter (D1, a Durable Object, Redis): implement these three methods and run the
|
|
371
|
+
contract suite. Store keys are `<namespace>:e:<key>` and `<namespace>:t:<tag>`. Two rules every
|
|
372
|
+
store must follow, which no test can check from outside:
|
|
373
|
+
|
|
374
|
+
- **Keep a key at least `ttlSeconds`.** Evicting a tag version early is safe (its entries become
|
|
375
|
+
misses), but it costs reloads.
|
|
376
|
+
- **Reject from `set` and `delete` whenever the write did not happen.** A store that swallows its
|
|
377
|
+
own errors makes `invalidateTags` resolve with nothing written, and stale entries stay.
|
|
378
|
+
|
|
379
|
+
## Contract suite (`@cardonjs/cache/contract`)
|
|
380
|
+
|
|
381
|
+
`cacheStoreContract` is a list of cases (`{ name, run(harness) }`) every store must pass, run with
|
|
382
|
+
the store's own test runner against a real store. It needs `@cardonjs/testing`.
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
import { cacheStoreContract } from "@cardonjs/cache/contract";
|
|
386
|
+
import { it } from "vitest";
|
|
387
|
+
|
|
388
|
+
it.each(cacheStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
|
|
389
|
+
c.run({ create: () => myStore() }), // an empty store per call
|
|
390
|
+
);
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
It checks that a string comes back exactly as stored (also one over 1 MiB), a missing key is
|
|
394
|
+
`undefined`, `set` overwrites, `delete` removes, keys are compared exactly, any `ttlSeconds` from
|
|
395
|
+
1 second to 60 days is accepted, and the longest key the cache builds works.
|
|
396
|
+
|
|
397
|
+
## Testing (`@cardonjs/cache/testing`)
|
|
398
|
+
|
|
399
|
+
`memoryCacheStore({ now? })` keeps entries in a `Map` for exactly their `ttlSeconds` (by `now`).
|
|
400
|
+
Test-only: entries are lost when the isolate restarts. It passes `cacheStoreContract`.
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
import { createCache } from "@cardonjs/cache";
|
|
404
|
+
import { memoryCacheStore } from "@cardonjs/cache/testing";
|
|
405
|
+
|
|
406
|
+
const cache = createCache({ store: memoryCacheStore(), defaultTtl: "5m" });
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
## Out of scope
|
|
410
|
+
|
|
411
|
+
- HTTP response caching (Workers Caching, the Cache API), `Cache-Control` helpers and ETags: a
|
|
412
|
+
cached response is where authenticated data leaks to other callers.
|
|
413
|
+
- Stale-while-revalidate, locks across isolates, cache warming.
|
|
414
|
+
- Other stores (Cache API, D1, Durable Objects, Redis): each is an adapter when a project needs it.
|
|
415
|
+
- Metrics and a health check.
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createCache`: a data cache over any {@link CacheStore}. Read-through with a time to live, values
|
|
3
|
+
* checked with the caller's Zod schema on the way in and out, and tags implemented here once,
|
|
4
|
+
* over the store's get, set and delete.
|
|
5
|
+
*
|
|
6
|
+
* - A cache is never the source of truth: a failed store read or write is a miss (reported
|
|
7
|
+
* through `onError` with the operation only), never an error for the caller. `delete` and
|
|
8
|
+
* `invalidateTags` reject on a store failure: a silent failure there serves stale data.
|
|
9
|
+
* - Tags: each tag has a version in the store (`<namespace>:t:<tag>`), a random string. An entry
|
|
10
|
+
* records the version each of its tags had before its value was computed; a read compares them
|
|
11
|
+
* and treats any difference, or a tag without a version, as a miss. A tag without a version
|
|
12
|
+
* gets a fresh one before an entry with it is written, so a lost version only costs misses.
|
|
13
|
+
* - Loads in flight (`remember`) are tracked per isolate with their tags: `delete`, `set` and
|
|
14
|
+
* `invalidateTags` drop the ones they affect, which then never write their result and are never
|
|
15
|
+
* joined by a later call.
|
|
16
|
+
* - Every caller gets its own copy of a value; keys and values never reach an error message or
|
|
17
|
+
* `onError`.
|
|
18
|
+
*/
|
|
19
|
+
import type { output, ZodType } from "zod";
|
|
20
|
+
import { type Duration } from "./duration.js";
|
|
21
|
+
import type { CacheStore } from "./store.js";
|
|
22
|
+
/** What failed, as `onError` receives it. */
|
|
23
|
+
export type CacheOperation = "get" | "set";
|
|
24
|
+
export interface CreateCacheOptions {
|
|
25
|
+
/** Where entries live, e.g. `kvCacheStore(env.CACHE)` from `@cardonjs/cache-kv`. */
|
|
26
|
+
readonly store: CacheStore;
|
|
27
|
+
/**
|
|
28
|
+
* Prefix of every store key, so several caches can share one store (default `"cache"`):
|
|
29
|
+
* 1 to 64 of `A-Z a-z 0-9 . _ -`, starting with a letter or digit. Tags are per namespace too.
|
|
30
|
+
*/
|
|
31
|
+
readonly namespace?: string;
|
|
32
|
+
/** Time to live of an entry when a call gives none. Without it every write needs a `ttl`. */
|
|
33
|
+
readonly defaultTtl?: Duration;
|
|
34
|
+
/** Longest time to live of an entry (default `"1d"`, at most `"30d"`). */
|
|
35
|
+
readonly maxTtl?: Duration;
|
|
36
|
+
/** Largest value, in UTF-8 bytes of its JSON (default 1 MiB, at most 24 MiB). */
|
|
37
|
+
readonly maxValueBytes?: number;
|
|
38
|
+
/**
|
|
39
|
+
* Milliseconds `invalidateTags` waits before trying a failed tag write once more (default
|
|
40
|
+
* 1100, a little over KV's one write per second per key; 0 disables the retry; at most 10000).
|
|
41
|
+
*/
|
|
42
|
+
readonly invalidateRetryDelay?: number;
|
|
43
|
+
/**
|
|
44
|
+
* Called when a store read or write fails, a schema throws on a read, or a value is not stored
|
|
45
|
+
* (too large, not JSON, does not match the schema after a JSON round trip). Gets the error and
|
|
46
|
+
* the operation only, never the key or the value. A throwing (or rejecting) `onError` is
|
|
47
|
+
* ignored.
|
|
48
|
+
*/
|
|
49
|
+
readonly onError?: (error: unknown, operation: CacheOperation) => void;
|
|
50
|
+
/** The clock (default `() => new Date()`); for tests. */
|
|
51
|
+
readonly now?: () => Date;
|
|
52
|
+
/** Waits `ms` milliseconds (default: `setTimeout`); for tests of the invalidation retry. */
|
|
53
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
export interface CacheGetOptions<S extends ZodType> {
|
|
56
|
+
/** The value's schema (synchronous): a stored value that does not match is a miss. */
|
|
57
|
+
readonly schema: S;
|
|
58
|
+
/**
|
|
59
|
+
* Tags the entry must carry (with their current versions): an entry stored without one of
|
|
60
|
+
* them is a miss. Pass the tags the entry is written with: without them, a value stored by a
|
|
61
|
+
* plain `set` without tags is served even after `invalidateTags`.
|
|
62
|
+
*/
|
|
63
|
+
readonly tags?: readonly string[];
|
|
64
|
+
}
|
|
65
|
+
export interface CacheSetOptions {
|
|
66
|
+
/** Time to live (default: the cache's `defaultTtl`); at most the cache's `maxTtl`. */
|
|
67
|
+
readonly ttl?: Duration;
|
|
68
|
+
/** Up to 8 tags; `invalidateTags` with any of them makes the entry a miss. */
|
|
69
|
+
readonly tags?: readonly string[];
|
|
70
|
+
}
|
|
71
|
+
export interface CacheSetWithSchemaOptions<S extends ZodType> extends CacheSetOptions {
|
|
72
|
+
/**
|
|
73
|
+
* Parses the value first: only what the schema keeps is stored (a value it refuses is a
|
|
74
|
+
* `TypeError`). Without it, `set` stores the value as given.
|
|
75
|
+
*/
|
|
76
|
+
readonly schema?: S;
|
|
77
|
+
}
|
|
78
|
+
export interface CacheRememberOptions<S extends ZodType> extends CacheSetOptions {
|
|
79
|
+
/**
|
|
80
|
+
* The value's schema (synchronous). The loader's result is parsed with it, and only what it
|
|
81
|
+
* keeps is stored and returned; a stored value that does not match is a miss and is replaced.
|
|
82
|
+
*/
|
|
83
|
+
readonly schema: S;
|
|
84
|
+
}
|
|
85
|
+
export interface Cache {
|
|
86
|
+
/** The value stored under `key`, or `undefined` (a miss). Never rejects on a store failure. */
|
|
87
|
+
get<S extends ZodType>(key: string, options: CacheGetOptions<S>): Promise<output<S> | undefined>;
|
|
88
|
+
/**
|
|
89
|
+
* Stores `value` (JSON) under `key`. Resolves whether it was stored: `false` for `undefined`, a
|
|
90
|
+
* value that is not JSON or is too large, or a store failure. Never rejects on a store failure;
|
|
91
|
+
* rejects with a `TypeError` when `schema` is given and refuses the value.
|
|
92
|
+
*/
|
|
93
|
+
set(key: string, value: unknown, options?: CacheSetWithSchemaOptions<ZodType>): Promise<boolean>;
|
|
94
|
+
/**
|
|
95
|
+
* The value under `key`, or the loader's result parsed with `schema`, stored for next time. The
|
|
96
|
+
* loader runs only on a miss, and once per isolate for concurrent calls with the same key (each
|
|
97
|
+
* caller gets its own copy). A loader that throws is not cached and its error propagates; a
|
|
98
|
+
* result the schema refuses is a `TypeError` (nothing stored). A parsed result that is
|
|
99
|
+
* `undefined`, not JSON, too large or does not match `schema` after a JSON round trip is
|
|
100
|
+
* returned and not cached.
|
|
101
|
+
*/
|
|
102
|
+
remember<S extends ZodType>(key: string, options: CacheRememberOptions<S>, loader: () => unknown): Promise<output<S>>;
|
|
103
|
+
/**
|
|
104
|
+
* Removes the entry under `key`; a load of this key in flight in this isolate does not write
|
|
105
|
+
* its result. Rejects on a store failure. To invalidate after a change, prefer a per-record tag
|
|
106
|
+
* and `invalidateTags`: a load in flight in another isolate can still write the old value back
|
|
107
|
+
* after `delete`, while it cannot defeat a new tag version.
|
|
108
|
+
*/
|
|
109
|
+
delete(key: string): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Makes every entry with any of `tags` a miss, by writing a new version of each tag (a failed
|
|
112
|
+
* write is tried once more after `invalidateRetryDelay`). Loads in flight in this isolate with
|
|
113
|
+
* any of these tags never write their result. Rejects on a store failure (some tags may have
|
|
114
|
+
* been invalidated). Up to 64 tags per call.
|
|
115
|
+
*/
|
|
116
|
+
invalidateTags(tags: readonly string[]): Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
/** The largest `maxTtl`: 30 days. */
|
|
119
|
+
export declare const MAX_TTL_LIMIT: number;
|
|
120
|
+
/**
|
|
121
|
+
* How long a tag version is stored: twice the largest `maxTtl` (60 days), whatever this cache's
|
|
122
|
+
* own `maxTtl`. A tag whose version is gone makes its entries misses, so a store that keeps it
|
|
123
|
+
* less long only costs misses.
|
|
124
|
+
*/
|
|
125
|
+
export declare const TAG_VERSION_TTL: number;
|
|
126
|
+
/** The largest `maxValueBytes`: 24 MiB, under KV's 25 MiB value limit with room for the envelope. */
|
|
127
|
+
export declare const MAX_VALUE_BYTES_LIMIT: number;
|
|
128
|
+
/** Most tags `invalidateTags` takes in one call. */
|
|
129
|
+
export declare const MAX_INVALIDATE_TAGS = 64;
|
|
130
|
+
/**
|
|
131
|
+
* A cache over `store`. Synchronous and cheap (no I/O): build it once, e.g. in the app's adapters
|
|
132
|
+
* factory, so concurrent `remember` calls of an isolate share their loads. Throws a `TypeError`
|
|
133
|
+
* for invalid options; the message never includes a value.
|
|
134
|
+
*/
|
|
135
|
+
export declare function createCache(options: CreateCacheOptions): Cache;
|
|
136
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAC3C,OAAO,EAAE,KAAK,QAAQ,EAAmB,MAAM,eAAe,CAAC;AAW/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,6CAA6C;AAC7C,MAAM,MAAM,cAAc,GAAG,KAAK,GAAG,KAAK,CAAC;AAE3C,MAAM,WAAW,kBAAkB;IACjC,oFAAoF;IACpF,QAAQ,CAAC,KAAK,EAAE,UAA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