@ultimat3/cache 31.46.0 → 31.47.1

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/CLAUDE.md CHANGED
@@ -70,7 +70,7 @@ Tier 1. Tagged caching + THE invalidation graph.
70
70
  internal `routeTagKeys` (`render/src/route.ts`) — one public `tagKeys`, this one.
71
71
  - **`invalidateWireTags` has no production caller and is KEPT**: the outbound twin of
72
72
  `receiveInvalidationBroadcast`, which `packages/cli/src/runtime-cache.ts` calls.
73
- - `tag.x` typing comes from the `CacheTagRegistry` augmentation, generated by `x manifest`.
73
+ - `tag.x` typing comes from the app's hand-written `CacheTagRegistry` augmentation; nothing generates it.
74
74
  - **`declareTags()` is additive and process-wide: a test undoes it with `isolateDeclaredTags()`,
75
75
  never `resetDeclaredTags()`** (the empty set switches `assertKnownTags` off).
76
76
  - **Every process-global registry has that seam: `isolateGraph()`, `isolateTiers()`.** A reset
package/README.md CHANGED
@@ -5,6 +5,8 @@ Four tiers. **One invalidation graph, not three.**
5
5
  `bun add @ultimat3/cache` · guide: [Caching And Invalidation](https://github.com/developerz-ai/ultimate/wiki/Caching-And-Invalidation)
6
6
 
7
7
  ```ts
8
+ import { tag } from '@ultimat3/cache';
9
+
8
10
  cache: { invalidates: [tag.post, tag.feed] }
9
11
  ```
10
12
 
@@ -37,12 +39,19 @@ other processes also write). Swap or omit any of them
37
39
  without touching a call site — order comes from `@ultimat3/core`'s `CACHE_TIERS`, not registration order.
38
40
 
39
41
  ```ts
40
- import { cacheStack, lruTier, memoTier, registerTier } from '@ultimat3/cache';
42
+ import { cacheStack, lruTier, memoTier, registerTier, tag } from '@ultimat3/cache';
43
+ import { database, entity, uuid } from '@ultimat3/entity';
44
+
45
+ const posts = entity('posts', {
46
+ tenant: 'orgId',
47
+ columns: { id: uuid().primaryKey(), orgId: uuid() },
48
+ });
49
+ const db = database({ posts });
41
50
 
42
51
  const stack = cacheStack([memoTier(), lruTier({ maxBytes: 64 * 1024 * 1024 })]);
43
52
  for (const tier of stack.tiers) registerTier(tier);
44
53
 
45
- const feed = await stack.read('feed:org-1', () => db.posts.recent(), {
54
+ const feed = await stack.read('feed:org-1', () => db.posts.where({ orgId: 'org-1' }).limit(20).all(), {
46
55
  ttlMs: 30_000,
47
56
  tags: [tag('post')],
48
57
  });
@@ -110,6 +119,8 @@ called. 40,000 keys warmed by one rolling restart otherwise share one expiry ins
110
119
  inside the same 30-second window. The roll is injected, never `Math.random()` at a call site:
111
120
 
112
121
  ```ts
122
+ import { lruTier, redisTier } from '@ultimat3/cache';
123
+
113
124
  lruTier({ rng: () => 0 }); // the full lease — what a test asserting an exact expiry wants
114
125
  redisTier({ jitterFraction: 0 }); // off entirely
115
126
  redisTier({ jitterFraction: 0.2 }); // a wider spread; outside [0, 1) is X_CACHE_JITTER_INVALID
@@ -140,6 +151,13 @@ already wrote is taken back. The caller still gets what the origin answered: a f
140
151
  publish, it never fails a read. It is exported for any cache doing its own read-through:
141
152
 
142
153
  ```ts
154
+ import { type CacheTier, type FenceScope, sampleFence } from '@ultimat3/cache';
155
+
156
+ declare const tier: CacheTier;
157
+ declare const key: string;
158
+ declare const tags: NonNullable<FenceScope['tags']>;
159
+ declare function run(): Promise<unknown>;
160
+
143
161
  const fence = sampleFence({ key, tags });
144
162
  const value = await run();
145
163
  if (fence.isValid()) await tier.set(key, value, { tags });
@@ -170,7 +188,20 @@ replacing — an entry that outgrew the LRU's budget served its previous version
170
188
  `undefined`, so a lookup for a row that has not replicated yet is not held for the positive lease:
171
189
 
172
190
  ```ts
173
- await stack.read(key, () => db.posts.byId(id), { ttlMs: 300_000, negativeTtlMs: 5_000 });
191
+ import { database, entity, uuid } from '@ultimat3/entity';
192
+ import { cacheStack } from '@ultimat3/cache';
193
+
194
+ declare const stack: ReturnType<typeof cacheStack>;
195
+
196
+ const posts = entity('posts', {
197
+ tenant: 'orgId',
198
+ columns: { id: uuid().primaryKey(), orgId: uuid() },
199
+ });
200
+ const db = database({ posts });
201
+ declare const id: string;
202
+ declare const key: string;
203
+
204
+ await stack.read(key, () => db.posts.where({ id }).one(), { ttlMs: 300_000, negativeTtlMs: 5_000 });
174
205
  ```
175
206
 
176
207
  **A promoted hit carries its own remaining life.** When a read hits a far tier and populates the
@@ -201,6 +232,10 @@ closed (`TierLabel`) so the panel can group by it. `'query-read'` is in that uni
201
232
  ## Tags
202
233
 
203
234
  ```ts
235
+ import { tag } from '@ultimat3/cache';
236
+
237
+ declare const id: string;
238
+
204
239
  tag.post // the collection — busts lists
205
240
  tag('post', id) // one row — also busts the lists that contained it
206
241
  ```
@@ -209,8 +244,8 @@ Wire form is `post` / `post:<id>`, identical in Redis keys, CDN surrogate keys a
209
244
  `--json` reports — the edge adds one `e:<entity>` index key per entity ([CDN](#cdn)). Invalidation is asymmetric-tolerant on purpose: busting a collection
210
245
  kills its rows, busting a row kills the collections that held it.
211
246
 
212
- `tag.post` is typed via a registry that `x manifest` generates, so `tag.pots` is a build
213
- error:
247
+ `tag.post` is typed via a registry the app writes by hand, beside its `declareTags` call, so
248
+ `tag.pots` is a build error. Nothing generates it:
214
249
 
215
250
  ```ts
216
251
  declare module '@ultimat3/cache' {
@@ -218,8 +253,8 @@ declare module '@ultimat3/cache' {
218
253
  }
219
254
  ```
220
255
 
221
- `declareTags()` takes the manifest's entity names at boot and is **additive and process-wide** —
222
- once anything is declared, an undeclared tag is `X_CACHE_TAG_UNKNOWN`. A test that declares its own
256
+ `declareTags()` takes the tag names the app lists (`examples/dummy/packages/db/src/tags.ts`) and is
257
+ **additive and process-wide** — until something is declared no tag is checked; once anything is, an undeclared tag is `X_CACHE_TAG_UNKNOWN`. A test that declares its own
223
258
  fixture entity therefore turns validation on for every later file in the same `bun test` process.
224
259
  `isolateDeclaredTags()` is the seam for that — see [Test seams](#test-seams).
225
260
 
@@ -285,6 +320,10 @@ your own payloads.
285
320
  ## Invalidating
286
321
 
287
322
  ```ts
323
+ import { invalidateTags, tag } from '@ultimat3/cache';
324
+
325
+ declare const postId: string;
326
+
288
327
  const report = await invalidateTags([tag('post', postId)]);
289
328
  ```
290
329
 
@@ -377,6 +416,10 @@ not reach `realtime` or a message bus — and whoever owns the transport (`@ulti
377
416
  boot, exactly as `@ultimat3/render` wires the `Revalidator`:
378
417
 
379
418
  ```ts
419
+ import { receiveInvalidationBroadcast, registerInvalidationBroadcast } from '@ultimat3/cache';
420
+
421
+ declare const bus: { publish(subject: string, tags: readonly string[]): Promise<void>; subscribe(subject: string, on: (tags: readonly string[]) => void): void };
422
+
380
423
  registerInvalidationBroadcast(async (wireTags) => bus.publish('cache.invalidate', wireTags));
381
424
  bus.subscribe('cache.invalidate', (wireTags) => receiveInvalidationBroadcast(wireTags));
382
425
  ```
@@ -437,6 +480,9 @@ Every registry here is process-global and `bun test` is one process, so a suite
437
480
  registrations with an `isolate*()` — **capture and restore, never a reset**:
438
481
 
439
482
  ```ts
483
+ import { declareTags, isolateDeclaredTags } from '@ultimat3/cache';
484
+ import { afterAll } from 'bun:test';
485
+
440
486
  const restoreTags = isolateDeclaredTags();
441
487
  declareTags(['fixture']);
442
488
  afterAll(restoreTags);
@@ -460,6 +506,10 @@ unsubscribes (core's `resetInstrumentation()` is the backstop).
460
506
  ## CDN
461
507
 
462
508
  ```ts
509
+ import { cacheHeaders, tag } from '@ultimat3/cache';
510
+
511
+ declare const id: string;
512
+
463
513
  cacheHeaders({ sMaxAge: 300, staleWhileRevalidate: 86_400, tags: [tag('post', id)] });
464
514
  // => { 'Cache-Control': 'public, max-age=0, s-maxage=300, stale-while-revalidate=86400',
465
515
  // 'Surrogate-Key': 'post:1 e:post', 'Cache-Tag': 'post:1,e:post' }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cache",
3
- "version": "31.46.0",
3
+ "version": "31.47.1",
4
4
  "description": "Tagged caching: request memo, LRU, Redis, CDN — one invalidation graph",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -43,6 +43,6 @@
43
43
  "test": "bun test"
44
44
  },
45
45
  "dependencies": {
46
- "@ultimat3/core": "31.46.0"
46
+ "@ultimat3/core": "31.47.1"
47
47
  }
48
48
  }
package/src/errors.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // The X_* codes owned by @ultimat3/cache. Each one names the exact config change or
2
2
  // command that resolves it, so an agent reading the failure can act without a doc lookup.
3
- import { registerErrorCodes, UltimateError } from '@ultimat3/core';
3
+ import { registerErrorCodes, renderFixLiteral, UltimateError } from '@ultimat3/core';
4
4
 
5
5
  /** Codes this package declares and owns. */
6
6
  export const CACHE_OWNED_ERROR_CODES = [
@@ -54,12 +54,15 @@ export class CacheDriverUnavailableError extends UltimateError {
54
54
  */
55
55
  export class CacheTagUnknownError extends UltimateError {
56
56
  constructor(input: { tag: string; known: readonly string[] }) {
57
+ // `declareTags` takes the name; a row tag arrives in its wire form, `<name>:<id>`.
58
+ const name = input.tag.split(':', 1)[0] ?? input.tag;
57
59
  super({
58
60
  code: 'X_CACHE_TAG_UNKNOWN',
59
61
  cause: `tag "${input.tag}" is not declared by any entity (declared: ${
60
62
  input.known.length > 0 ? input.known.join(', ') : 'none'
61
63
  })`,
62
- fix: 'x manifest',
64
+ // Only the app declares tags, so the repair is an edit there: nothing generates either half.
65
+ fix: `declareTags([${renderFixLiteral(name, "'<tag>'")}]) // in the module that already calls declareTags, and add the name to its CacheTagRegistry; for a typo, use a declared name from the cause instead`,
63
66
  });
64
67
  }
65
68
  }
@@ -67,11 +70,16 @@ export class CacheTagUnknownError extends UltimateError {
67
70
  /** A single entry cannot fit the tier's byte budget, so caching it would evict everything. */
68
71
  export class CacheTooLargeError extends UltimateError {
69
72
  constructor(input: { key: string; bytes: number; maxBytes: number; tier: string }) {
73
+ const bytes = String(input.bytes);
74
+ // The cap is a constructor option on every tier, never an `app.config.ts` key.
75
+ const raise =
76
+ input.tier === 'redis'
77
+ ? `redisTier({ maxValueBytes: ${bytes} })`
78
+ : `lruTier({ maxBytes: ${bytes} })`;
70
79
  super({
71
80
  code: 'X_CACHE_TOO_LARGE',
72
81
  cause: `entry "${input.key}" is ${input.bytes}B, over the ${input.tier} budget of ${input.maxBytes}B`,
73
- // The cap is a constructor option on every tier, never an `app.config.ts` key.
74
- fix: `${input.tier}Tier({ ${input.tier === 'redis' ? 'maxValueBytes' : 'maxBytes'}: ${String(input.bytes)} }) where the tier is built, or cache a projection instead of the row`,
82
+ fix: `${raise} where the tier is built, or cache a projection instead of the row`,
75
83
  });
76
84
  }
77
85
  }
@@ -3,7 +3,7 @@
3
3
  // tags ARE Ultimate's wire tags, so a `Cache-Tag` response header and an `invalidates: [tag.post]`
4
4
  // name the same string — the alternative, purging by URL, would need a route list nobody keeps.
5
5
 
6
- import { isRetryableStatus } from '@ultimat3/core';
6
+ import { isJsonObject, isRetryableStatus } from '@ultimat3/core';
7
7
  import type { PurgeDriver } from './cdn';
8
8
  import { CachePurgeFailedError } from './errors';
9
9
  import type { PurgeFetch } from './purge-http';
@@ -13,7 +13,6 @@ import {
13
13
  DEFAULT_PURGE_TIMEOUT_MS,
14
14
  defaultPurgeFetch,
15
15
  detailFrom,
16
- isRecord,
17
16
  purgeBody,
18
17
  purgePost,
19
18
  requireCredential,
@@ -59,12 +58,12 @@ const fixFor = (status: number): string => {
59
58
 
60
59
  /** Cloudflare's own errors, when it sent any: `{"errors":[{"code":1122,"message":"…"}]}`. */
61
60
  function messagesFrom(payload: unknown): string | undefined {
62
- if (!isRecord(payload)) return undefined;
61
+ if (!isJsonObject(payload)) return undefined;
63
62
  const errors = payload['errors'];
64
63
  if (!Array.isArray(errors) || errors.length === 0) return undefined;
65
64
  const messages = errors
66
65
  .map((entry) =>
67
- isRecord(entry) && typeof entry['message'] === 'string' ? entry['message'] : undefined,
66
+ isJsonObject(entry) && typeof entry['message'] === 'string' ? entry['message'] : undefined,
68
67
  )
69
68
  .filter((message): message is string => message !== undefined);
70
69
  return messages.length > 0 ? messages.join('; ') : undefined;
@@ -108,7 +107,7 @@ export function cloudflarePurgeDriver(options: CloudflarePurgeOptions): PurgeDri
108
107
  fix: fixFor(response.status),
109
108
  });
110
109
  }
111
- if (isRecord(body.json) && body.json['success'] === false) {
110
+ if (isJsonObject(body.json) && body.json['success'] === false) {
112
111
  throw new CachePurgeFailedError({
113
112
  driver: 'cloudflare',
114
113
  detail:
@@ -3,7 +3,7 @@
3
3
  // client. The keys are Ultimate's wire tags unchanged (`post`, `post:1`), which is the property
4
4
  // that keeps an edge purge and an app-level invalidation from ever meaning different things.
5
5
 
6
- import { isRetryableStatus } from '@ultimat3/core';
6
+ import { isJsonObject, isRetryableStatus } from '@ultimat3/core';
7
7
  import type { PurgeDriver } from './cdn';
8
8
  import { CachePurgeFailedError } from './errors';
9
9
  import type { PurgeFetch } from './purge-http';
@@ -13,7 +13,6 @@ import {
13
13
  DEFAULT_PURGE_TIMEOUT_MS,
14
14
  defaultPurgeFetch,
15
15
  detailFrom,
16
- isRecord,
17
16
  type PurgeBody,
18
17
  purgeBody,
19
18
  purgePost,
@@ -61,7 +60,7 @@ const fixFor = (status: number): string => {
61
60
  */
62
61
  function acceptedFrom(body: PurgeBody, batch: readonly string[]): string[] {
63
62
  const payload = body.json;
64
- if (!isRecord(payload)) return [...batch];
63
+ if (!isJsonObject(payload)) return [...batch];
65
64
  // `Object.hasOwn`, never `in`: a surrogate key named `constructor` or `toString` answered `true`
66
65
  // out of a body that never mentioned it, so `InvalidationReport.tiers` listed keys nothing had
67
66
  // purged — a partial bust reading as a clean one.
package/src/purge-http.ts CHANGED
@@ -157,10 +157,6 @@ export function detailFrom(body: PurgeBody): string {
157
157
  : body.text;
158
158
  }
159
159
 
160
- export function isRecord(value: unknown): value is Record<string, unknown> {
161
- return typeof value === 'object' && value !== null && !Array.isArray(value);
162
- }
163
-
164
160
  export interface PurgePostInput {
165
161
  readonly driver: string;
166
162
  readonly url: string;
package/src/tags.ts CHANGED
@@ -11,14 +11,14 @@ export interface CacheTag<E extends string = string> {
11
11
  }
12
12
 
13
13
  /**
14
- * Apps augment this interface (generated by `x manifest` from their entities) to get
15
- * `tag.post` typed and `tag.pots` as a build error:
14
+ * Apps augment this interface by hand, beside their `declareTags` call, to get `tag.post` typed
15
+ * and `tag.pots` as a build error. Nothing generates it:
16
16
  *
17
17
  * declare module '@ultimat3/cache' {
18
18
  * interface CacheTagRegistry { post: true; feed: true }
19
19
  * }
20
20
  */
21
- // biome-ignore lint/suspicious/noEmptyInterface: augmentation target, filled by generated code
21
+ // biome-ignore lint/suspicious/noEmptyInterface: augmentation target, filled by each app
22
22
  export interface CacheTagRegistry {}
23
23
 
24
24
  type TagAccessors = { readonly [K in keyof CacheTagRegistry & string]: CacheTag<K> };
@@ -30,7 +30,7 @@ const makeTag = <E extends string>(entity: E, id?: string): CacheTag<E> =>
30
30
 
31
31
  /**
32
32
  * `tag('post', id)` for a row, `tag.post` for the collection. The property form is a Proxy
33
- * so generated registry augmentations need no runtime codegen.
33
+ * so a registry augmentation, which is types only, needs no runtime counterpart.
34
34
  */
35
35
  export const tag: TagFactory = new Proxy(makeTag, {
36
36
  get(target, prop, receiver): unknown {
@@ -101,7 +101,7 @@ export function tagsIntersect(requested: readonly CacheTag[], owned: readonly Ca
101
101
 
102
102
  const declared = new Set<string>();
103
103
 
104
- /** Called once at boot with the entity names from `x.manifest.json`. */
104
+ /** Called by the app, at import of its tag module. Until it is, no tag is checked. */
105
105
  export function declareTags(entities: readonly string[]): void {
106
106
  for (const name of entities) declared.add(name);
107
107
  }
@@ -3,7 +3,7 @@
3
3
  // every tier stores TEXT, no two readers ever share one mutable object. Lives here, not in
4
4
  // `@ultimat3/query`'s cursor codec: query is tier 3, and this package is tier 1.
5
5
 
6
- import { renderThrowable } from '@ultimat3/core';
6
+ import { isJsonObject, renderThrowable } from '@ultimat3/core';
7
7
  import { CacheValueUnencodableError } from './errors';
8
8
 
9
9
  /** The member that marks a tagged value. Only this codec writes it; an app's own is escaped. */
@@ -38,9 +38,6 @@ export const CACHE_CODEC_MARK = 'x1:';
38
38
 
39
39
  type Tagged = { readonly [TAG]: 'date' | 'bigint' | 'map' | 'set'; readonly v: unknown };
40
40
 
41
- const isRecord = (value: unknown): value is Record<string, unknown> =>
42
- typeof value === 'object' && value !== null && !Array.isArray(value);
43
-
44
41
  /** A copy with every tag-shaped key given one more `$`, or the object itself when it has none. */
45
42
  const escapeKeys = (value: Record<string, unknown>): Record<string, unknown> => {
46
43
  const keys = Object.keys(value);
@@ -62,7 +59,9 @@ const unescapeKeys = (value: Record<string, unknown>): Record<string, unknown> =
62
59
  */
63
60
  function transform(holder: unknown, key: string, value: unknown): unknown {
64
61
  const raw =
65
- isRecord(holder) || Array.isArray(holder) ? (holder as Record<string, unknown>)[key] : value;
62
+ isJsonObject(holder) || Array.isArray(holder)
63
+ ? (holder as Record<string, unknown>)[key]
64
+ : value;
66
65
  if (raw instanceof Date) {
67
66
  return { [TAG]: 'date', v: Number.isNaN(raw.getTime()) ? null : raw.toISOString() };
68
67
  }
@@ -77,7 +76,7 @@ function transform(holder: unknown, key: string, value: unknown): unknown {
77
76
  }
78
77
  if (raw instanceof Map) return { [TAG]: 'map', v: [...raw.entries()] };
79
78
  if (raw instanceof Set) return { [TAG]: 'set', v: [...raw] };
80
- return isRecord(value) ? escapeKeys(value) : value;
79
+ return isJsonObject(value) ? escapeKeys(value) : value;
81
80
  }
82
81
 
83
82
  /** A limit this codec refuses at, carried out of `JSON.stringify` to `encodeCacheValue`. */
@@ -136,7 +135,7 @@ const untag = (value: Record<string, unknown>): { readonly revived: unknown } |
136
135
 
137
136
  /** Bottom-up, so a tagged value's members are already revived when the tag itself is read. */
138
137
  const revive = (_key: string, value: unknown): unknown => {
139
- if (!isRecord(value)) return value;
138
+ if (!isJsonObject(value)) return value;
140
139
  const tagged = untag(value);
141
140
  return tagged === undefined ? unescapeKeys(value) : tagged.revived;
142
141
  };