@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/llms.txt ADDED
@@ -0,0 +1,210 @@
1
+ # @cardonjs/cache
2
+
3
+ A data cache for Cardón apps: read-through with a time to live (`remember`), values checked with
4
+ the caller's Zod schema on the way in and out, and tag invalidation
5
+ (`invalidateTags([cacheKey("product", id)])`) implemented once over any store. A store only gets,
6
+ sets and deletes strings; the Workers KV store is `@cardonjs/cache-kv`. Standard web APIs only.
7
+ Not an HTTP response cache.
8
+
9
+ A cache is never the source of truth: a store failure on a read or a write is a miss (reported
10
+ through `onError`), never an error for the caller. `delete` and `invalidateTags` reject on a store
11
+ failure.
12
+
13
+ Full documentation: README.md in this package.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ pnpm add @cardonjs/cache @cardonjs/cache-kv zod
19
+ ```
20
+
21
+ Peer dependencies: `zod`; `@cardonjs/testing` only for `@cardonjs/cache/contract`.
22
+
23
+ ## Rules (read first)
24
+
25
+ - The key must name everything the value depends on. Data that differs per user, tenant or role
26
+ needs that id in the key (`cacheKey("orders", tenantId, userId)`); otherwise one caller is
27
+ served another's data. Say it in every review of a cached route.
28
+ - Never cache secrets, tokens or credentials. Think twice about personal data: the store keeps it
29
+ until the entry expires, and invalidation is not instant everywhere. Only what the schema keeps
30
+ is stored: leave columns you must not cache out of the schema.
31
+ - Not for data that must be right immediately (permissions, balances, stock at checkout).
32
+ - Never cache an authorization decision (whether a caller may do something).
33
+ - Invalidate after the write is committed, not before.
34
+ - No personal data in keys or tags (key names show up in the KV dashboard and in listings): ids,
35
+ never emails or names; hash free text with `hashedKeyPart`.
36
+ - Key parts from a request (a search query, a filter) must be length-validated or hashed:
37
+ `cacheKey` throws over 200 characters (non-ASCII grows about 9 times when percent-encoded), which
38
+ would be a 500. Use `cacheKey("search", await hashedKeyPart(query))`.
39
+ - To forget a record after a change, tag its entries per record (`tags: [cacheKey("product", id)]`)
40
+ and call `invalidateTags`. `delete` only drops one entry: a load in flight in another isolate
41
+ can write the old value back after it.
42
+
43
+ ## Exports
44
+
45
+ ### `@cardonjs/cache`
46
+
47
+ - `createCache(options: CreateCacheOptions): Cache`. Synchronous, no I/O; build it in the app's
48
+ adapters factory (once per isolate). Throws a `TypeError` for invalid options. Options:
49
+ - `store: CacheStore` (required), e.g. `kvCacheStore(env.CACHE)`.
50
+ - `namespace?: string` (default `"cache"`): prefix of every store key and tag; 1 to 64 of
51
+ `A-Z a-z 0-9 . _ -`, starting with a letter or digit. Tags are per namespace:
52
+ `invalidateTags` never touches another namespace sharing the store.
53
+ - `defaultTtl?: Duration`: used when a call gives no `ttl`. Without it, every `set` and
54
+ `remember` needs a `ttl` (else a `TypeError`).
55
+ - `maxTtl?: Duration` (default `"1d"`, at most `"30d"`): a larger `ttl` is a `TypeError`.
56
+ - `maxValueBytes?: number` (default 1 MiB, at most 24 MiB): UTF-8 bytes of the value's JSON; a
57
+ larger value is not stored and is reported through `onError`.
58
+ - `invalidateRetryDelay?: number` (milliseconds, default 1100, 0 disables, at most 10000):
59
+ `invalidateTags` waits this long and retries a failed tag write once (KV refuses a second
60
+ write to a key within a second). Adds that delay to the request when it happens.
61
+ - `onError?: (error: unknown, operation: CacheOperation) => void`: `CacheOperation` is
62
+ `"get" | "set"`. Never receives the key or the value. A throwing `onError` is ignored.
63
+ - `now?: () => Date` and `sleep?: (ms: number) => Promise<void>` for tests.
64
+ - Schemas: synchronous (no async refinements) and of plain JSON (dates as ISO strings, no
65
+ `transform`). A schema that throws or is async on a read makes the read a miss (`onError`).
66
+ - `Cache` methods (each rejects with a `TypeError` for an invalid key, tag, ttl or schema):
67
+ - `get(key, { schema, tags? }: CacheGetOptions): Promise<value | undefined>`. `undefined` is a
68
+ miss: missing, expired, invalidated (or its tag version lost), not matching `schema`, not an
69
+ envelope this package wrote, or a store failure. Always pass the `tags` the entry is written
70
+ with: with them, an entry stored without one is a miss; without them, an untagged entry (a
71
+ plain `set`) is served even after `invalidateTags`.
72
+ - `set(key, value, { ttl?, tags?, schema? }?: CacheSetWithSchemaOptions): Promise<boolean>`:
73
+ whether it was stored. `undefined` is never stored (`null` is); a value that is not JSON or
74
+ too large is not. With `schema`, only what it keeps is stored (a refused value is a
75
+ `TypeError`); without it, the value is stored as given. Options type without the schema:
76
+ `CacheSetOptions`.
77
+ - `remember(key, { schema, ttl?, tags? }: CacheRememberOptions, loader): Promise<value>`: the
78
+ cached value, or the loader's result parsed with `schema` and stored for next time. Only what
79
+ the schema keeps is stored and returned (a row's extra columns never reach the store). A
80
+ loader result the schema refuses rejects with a `TypeError` (no key or value in the message)
81
+ and stores nothing; a loader that throws propagates its error. Concurrent calls for the same
82
+ key in the same isolate share one loader call when the load covers their tags; each caller
83
+ gets its own copy. A load that `delete`, `set` or `invalidateTags` affects never writes and is
84
+ never joined later. A parsed result that is `undefined`, not JSON, too large or does not match
85
+ `schema` after a JSON round trip (a `Date`, a `bigint`) is returned and not cached. Tag
86
+ versions are read before the loader runs, so an invalidation during the load makes the entry
87
+ a miss.
88
+ - `delete(key): Promise<void>`: drops one entry (and keeps this isolate's load of it in flight
89
+ from writing). Rejects on a store failure. Not an invalidation across isolates.
90
+ - `invalidateTags(tags): Promise<void>`: every entry with any of the tags (up to 64 per call)
91
+ becomes a miss. Retries a failed tag once after `invalidateRetryDelay`; rejects if that fails.
92
+ - `cacheKey(...parts: (string | number)[]): string`: joins parts with `:`, percent-encoding each
93
+ (`cacheKey("a:b", "c")` is `"a%3Ab:c"`, never equal to `cacheKey("a", "b:c")`; a number is its
94
+ text, `cacheKey(1) === cacheKey("1")`). Throws a `TypeError` for no parts, an empty part, a
95
+ non-finite number, another type, or over 200 characters.
96
+ - `hashedKeyPart(text: string): Promise<string>`: SHA-256 of the text, 64 hex characters, for key
97
+ parts from a request. Throws a `TypeError` for a non-string or an unpaired surrogate.
98
+ - Keys and tags: 1 to 200 printable ASCII characters without spaces. Up to 8 tags per entry.
99
+ - `Duration`: whole seconds (`600`) or `"<n>s" | "<n>m" | "<n>h" | "<n>d"` (`"10m"`, `"1d"`).
100
+ - `CacheStore` (a store adapter implements it):
101
+ `get(key): Promise<string | undefined>` (may return an entry past its time),
102
+ `set(key, value, ttlSeconds): Promise<void>` (must keep it at least `ttlSeconds`, never forever),
103
+ `delete(key): Promise<void>`. `set` and `delete` must reject whenever the write did not happen.
104
+ - Types: `Cache`, `CacheGetOptions`, `CacheOperation`, `CacheRememberOptions`, `CacheSetOptions`,
105
+ `CacheSetWithSchemaOptions`, `CacheStore`, `CreateCacheOptions`, `Duration`.
106
+
107
+ ### `@cardonjs/cache/contract`
108
+
109
+ - `cacheStoreContract`: cases `{ name, run(harness) }` every `CacheStore` must pass; the harness
110
+ is `CacheStoreContractHarness` (`{ create(): CacheStore | Promise<CacheStore> }`, an empty store
111
+ per call). Needs `@cardonjs/testing`.
112
+
113
+ ### `@cardonjs/cache/testing`
114
+
115
+ - `memoryCacheStore(options?: MemoryCacheStoreOptions): CacheStore`: test-only, in a `Map`,
116
+ keeps an entry for exactly `ttlSeconds` by `options.now` (`() => Date`). Passes
117
+ `cacheStoreContract`. Type: `MemoryCacheStoreOptions`.
118
+
119
+ ## Minimal example
120
+
121
+ ```ts
122
+ import { cacheKey, createCache } from "@cardonjs/cache";
123
+ import { kvCacheStore } from "@cardonjs/cache-kv";
124
+ import { type CardonEnv, createApp, defineModule, idSchema, ok, successEnvelope } from "@cardonjs/core";
125
+ import { createRoute, z } from "@hono/zod-openapi";
126
+
127
+ // Only these fields are stored and returned, whatever else a row holds.
128
+ const productSchema = z.object({ id: z.string(), name: z.string(), price: z.number().int() });
129
+
130
+ type Bindings = { CACHE: KVNamespace; DB: D1Database };
131
+ const adapters = (env: Bindings) => ({
132
+ products: productsRepository(env.DB), // your repository
133
+ cache: createCache({ store: kvCacheStore(env.CACHE), namespace: "shop", defaultTtl: "5m" }),
134
+ });
135
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
136
+
137
+ const listProducts = createRoute({
138
+ method: "get",
139
+ path: "/categories/{categoryId}/products",
140
+ tags: ["Catalog"],
141
+ summary: "List the products of a category",
142
+ request: { params: z.object({ categoryId: idSchema }) },
143
+ responses: {
144
+ 200: {
145
+ description: "The products",
146
+ content: { "application/json": { schema: successEnvelope(z.array(productSchema)) } },
147
+ },
148
+ },
149
+ });
150
+
151
+ const catalogModule = defineModule<AppEnv>({
152
+ name: "catalog",
153
+ prefix: "/v1",
154
+ routes: (app) => {
155
+ app.openapi(listProducts, async (c) => {
156
+ const { categoryId } = c.req.valid("param");
157
+ // A public list, the same for every caller: the key names the category only.
158
+ const products = await c.var.adapters.cache.remember(
159
+ cacheKey("products", "by-category", categoryId),
160
+ { schema: z.array(productSchema), ttl: "10m", tags: [cacheKey("category", categoryId)] },
161
+ () => c.var.adapters.products.listByCategory(categoryId),
162
+ );
163
+ return ok(c, products);
164
+ });
165
+ },
166
+ });
167
+
168
+ export default createApp(adapters).register(catalogModule);
169
+
170
+ // Reading without loading: pass the tags the entry is written with.
171
+ // const cached = await cache.get(cacheKey("products", "by-category", categoryId), {
172
+ // schema: z.array(productSchema),
173
+ // tags: [cacheKey("category", categoryId)],
174
+ // });
175
+ // Where a product of the category changes, after the write is committed:
176
+ // await c.var.adapters.cache.invalidateTags([cacheKey("category", categoryId)]);
177
+ ```
178
+
179
+ ## Rules and common mistakes
180
+
181
+ - Build the cache once in the adapters factory, not per request: concurrent `remember` calls
182
+ only share a load within one cache object.
183
+ - Prefer `remember` over `get` + `set`: it reads the tag versions before loading, so a change
184
+ committed during the load is never cached as current. A plain `set` cannot know that.
185
+ - Invalidate a changed record with its per-record tag, not with `delete`.
186
+ - Pass the same `tags` to `get` that the entry is written with, so an entry stored without them
187
+ (e.g. by an old deploy or a plain `set`) is not served after an invalidation.
188
+ - Every entry expires; keep `ttl` as short as the data may be stale. There is no "forever".
189
+ - `invalidateTags` rejects when the store fails (after its retry): the write is already
190
+ committed, so the cached entries stay until their `ttl`. Answer accordingly.
191
+ - `onError` gets the error and the operation; log the error's name and the operation, never a
192
+ key, a value or a tag that holds personal data.
193
+ - Routes that use the cache still need auth unless they are deliberately public (core's `guard`
194
+ with `requireAuth` and its `public` list).
195
+
196
+ ## Workers KV facts (with `@cardonjs/cache-kv`)
197
+
198
+ - Eventually consistent: a write or an invalidation is visible at once in the same location and
199
+ can take up to 60 seconds (or the store's `cacheTtl`) in other locations.
200
+ - Minimum expiration 60 seconds: the store keeps an entry at least that long, and the cache
201
+ checks the entry's own expiry, so a 10-second `ttl` works.
202
+ - One write per second per key: a second write within a second fails (a failed cache write, a
203
+ miss next time); `invalidateTags` retries a failed tag once after `invalidateRetryDelay`.
204
+ - Key at most 512 bytes (this package builds at most 267), value at most 25 MiB.
205
+
206
+ ## Out of scope
207
+
208
+ - HTTP response caching (Workers Caching, the Cache API), `Cache-Control` helpers, ETags.
209
+ - Stale-while-revalidate, locks across isolates, cache warming.
210
+ - Other stores (Cache API, D1, Durable Objects, Redis): each is an adapter when needed.
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@cardonjs/cache",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Data cache for Cardón apps: read-through with a time to live, values checked with Zod on the way out, tag invalidation over any store, the CacheStore interface, its contract suite and an in-memory store.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cardonjs/cardon.git",
9
+ "directory": "packages/cache"
10
+ },
11
+ "homepage": "https://github.com/cardonjs/cardon/tree/main/packages/cache#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cardonjs/cardon/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./contract": {
23
+ "types": "./dist/contract.d.ts",
24
+ "default": "./dist/contract.js"
25
+ },
26
+ "./testing": {
27
+ "types": "./dist/testing.d.ts",
28
+ "default": "./dist/testing.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "llms.txt"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "peerDependencies": {
39
+ "zod": "^4.6.7",
40
+ "@cardonjs/testing": "^0.7.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@cardonjs/testing": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@hono/zod-openapi": "1.6.3",
49
+ "@scalar/hono-api-reference": "0.12.20",
50
+ "hono": "4.13.18",
51
+ "typescript": "7.0.2",
52
+ "vitest": "5.1.0",
53
+ "zod": "4.6.7",
54
+ "@cardonjs/auth": "0.2.7",
55
+ "@cardonjs/config": "0.0.0",
56
+ "@cardonjs/core": "0.5.1",
57
+ "@cardonjs/testing": "0.7.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsc -p tsconfig.build.json",
61
+ "typecheck": "tsc -p tsconfig.json --noEmit",
62
+ "test": "vitest run"
63
+ }
6
64
  }