@ultimat3/cache 31.6.1 → 31.8.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/CLAUDE.md CHANGED
@@ -201,7 +201,12 @@ Tier 1. Tagged caching + THE invalidation graph.
201
201
  | `redis-buckets.ts` | the tag → keys sorted-set layout: join + prune + lease, paged read, `UNLINK`, sweep |
202
202
  | `set-options.ts` | how two callers' `CacheSetOptions` combine, and the `null`-load TTL |
203
203
  | `tier-failures.ts` | `bestEffort()`, and the `cache.tier_failure` event for each refusal it absorbs |
204
- | `memo.ts` | request memo over the ALS ctx (WeakMap, no lifecycle) |
204
+ | `memo-store.ts` | the one per-ctx memo store (WeakMap on the ALS ctx) and its `MEMO_MAX_BYTES` (8 MiB) bound, oldest evicted silently |
205
+ | `memo.ts` | `memoTier`: the request-memo rung over `memo-store.ts` |
206
+ | `memo-flights.ts` | `memoFlights(ctx, name)`: a named namespace of reads in flight in an explicit ctx's memo — `@ultimat3/query`'s request memo |
207
+ | `memo-per-request.ts` | `memoPerRequest(fn, key)`: the same store for a plain function; straight through outside a ctx |
208
+ | `approx-bytes.ts` | `approxBytes`: a held value's cost from a bounded sample (8 elements, 32 members, depth 6, 512 nodes) — the memo charges every query read, so never a serialisation |
209
+ | `byte-length.ts` | `utf8ByteLength`: UTF-8 length counted off code units, no `TextEncoder` copy |
205
210
  | `lru.ts` | byte-budgeted LRU (linked list + map + tag index) |
206
211
  | `value-codec.ts` | the one value encoding every tier stores and decodes |
207
212
  | `redis.ts` | the shared tier over core's `redisClient()` (`@ultimat3/core/redis`, never `Bun.redis`), build-namespaced keys, the value budget, the write/bust order |
package/README.md CHANGED
@@ -48,6 +48,32 @@ const feed = await stack.read('feed:org-1', () => db.posts.recent(), {
48
48
  });
49
49
  ```
50
50
 
51
+ **The request memo is bounded: `MEMO_MAX_BYTES` (8 MiB) per ctx, oldest evicted silently.** A
52
+ job's ctx is the whole attempt, so an unbounded memo held every page a backfill read until it
53
+ ended — 198 MiB after 2,000 batches of 100 rows through a `cache:` query, measured; 8.4 MiB
54
+ bounded. An evicted entry costs one more read, never a wrong one. A held value is charged from a bounded
55
+ sample (`approxBytes`, ≈2 µs for a 50- or 500-row page, within 2× of the exact figure), never
56
+ serialised: the memo charges every query read. One entry over the bound on its
57
+ own is not memoized and evicts nothing.
58
+
59
+ `@ultimat3/query`'s request memo (`readOnce`) is this store too, through
60
+ `memoFlights(ctx, 'query')`: one store, one bound, whichever entry point filled it.
61
+
62
+ **`memoPerRequest(fn, key)` — the same memo for a plain function.** Once per ctx and key; outside a
63
+ ctx it calls straight through. An async `fn` hands every concurrent caller one promise, and a
64
+ rejection is dropped so the next call retries. Each wrapper owns its key space, and its entries
65
+ count against the same 8 MiB. The value is held by reference (it never leaves the request), not
66
+ through the codec below.
67
+
68
+ ```ts
69
+ import { memoPerRequest } from '@ultimat3/cache';
70
+
71
+ interface Org { readonly id: string; readonly name: string }
72
+ declare const db: { readonly orgs: { find(id: string): Promise<Org> } };
73
+
74
+ export const loadOrg = memoPerRequest((id: string) => db.orgs.find(id), (id) => id);
75
+ ```
76
+
51
77
  **Cached values: JSON + `Date` + `bigint` + `Map` + `Set` — the same shape from every tier.**
52
78
  Every tier (the memo and the LRU included) stores the value as text through one codec
53
79
  (`value-codec.ts`) and decodes a fresh copy on each hit, so:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cache",
3
- "version": "31.6.1",
3
+ "version": "31.8.0",
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.6.1"
46
+ "@ultimat3/core": "31.8.0"
47
47
  }
48
48
  }
@@ -0,0 +1,105 @@
1
+ // What a held value costs the request memo, from a bounded SAMPLE: `estimateBytes` serialises the
2
+ // whole value (160 µs for a 50-row page, measured), and the memo charges every query read. Shaped
3
+ // like the JSON `estimateBytes` would count, so both budgets read in one unit, within 2x.
4
+
5
+ /** Elements read from an array, a Map or a Set; the rest are charged at the sample's mean. */
6
+ const SAMPLE = 8;
7
+ /** Members of one object read before the rest are counted (keys only) and charged at the mean. */
8
+ const MEMBERS = 32;
9
+ /** Nesting walked; below it — and past the budget — a node is charged a flat `OPAQUE`. */
10
+ const MAX_DEPTH = 6;
11
+ const OPAQUE = 64;
12
+ /** Nodes visited per call, whatever the value's size: the work bound the memo depends on. */
13
+ const BUDGET = 512;
14
+
15
+ interface Walk {
16
+ left: number;
17
+ }
18
+
19
+ /**
20
+ * Cheap, bounded size estimate for an in-memory value. Never serialises, never throws: a getter or
21
+ * a Proxy trap that throws charges its node `OPAQUE` — the charge runs inside a promise's `.then`,
22
+ * where a throw is an unhandled rejection and a process exit.
23
+ */
24
+ export function approxBytes(value: unknown): number {
25
+ return sized(value, 0, { left: BUDGET });
26
+ }
27
+
28
+ function sized(value: unknown, depth: number, walk: Walk): number {
29
+ switch (typeof value) {
30
+ case 'string':
31
+ return value.length + 2;
32
+ case 'number':
33
+ case 'bigint':
34
+ return 8;
35
+ case 'boolean':
36
+ return 5;
37
+ case 'object':
38
+ break;
39
+ default:
40
+ return 0; // undefined, a function, a symbol: JSON drops them
41
+ }
42
+ if (value === null) return 4;
43
+ if (depth >= MAX_DEPTH || walk.left <= 0) return OPAQUE;
44
+ walk.left -= 1;
45
+ try {
46
+ return nodeBytes(value, depth, walk);
47
+ } catch {
48
+ return OPAQUE;
49
+ }
50
+ }
51
+
52
+ /** One non-null object; may throw (a getter, a Proxy trap) — `sized` catches. */
53
+ function nodeBytes(value: object, depth: number, walk: Walk): number {
54
+ if (value instanceof Date) return 26;
55
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return value.byteLength;
56
+ if (Array.isArray(value)) return arrayBytes(value, depth, walk);
57
+ if (value instanceof Map || value instanceof Set) return iterableBytes(value, depth, walk);
58
+ return objectBytes(value, depth, walk);
59
+ }
60
+
61
+ /** Up to `SAMPLE` elements, evenly spread, so a page sorted by size is not read from one end. */
62
+ function arrayBytes(items: readonly unknown[], depth: number, walk: Walk): number {
63
+ const count = items.length;
64
+ if (count === 0) return 2;
65
+ const taken = Math.min(count, SAMPLE);
66
+ let sum = 0;
67
+ for (let i = 0; i < taken; i += 1) {
68
+ sum += sized(items[Math.floor((i * count) / taken)], depth + 1, walk) + 1;
69
+ }
70
+ return 2 + Math.round((sum / taken) * count);
71
+ }
72
+
73
+ /** A Map's entries or a Set's members, as `estimateBytes` walks them: the first `SAMPLE`. */
74
+ function iterableBytes(
75
+ collection: ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>,
76
+ depth: number,
77
+ walk: Walk,
78
+ ): number {
79
+ const count = collection.size;
80
+ if (count === 0) return 2;
81
+ let sum = 0;
82
+ let taken = 0;
83
+ for (const item of collection.entries()) {
84
+ if (taken === SAMPLE) break;
85
+ const [key, member] = item;
86
+ sum += (collection instanceof Map ? sized(key, depth + 1, walk) + 4 : 0) + 1;
87
+ sum += sized(member, depth + 1, walk);
88
+ taken += 1;
89
+ }
90
+ return 2 + Math.round((sum / taken) * count);
91
+ }
92
+
93
+ function objectBytes(record: object, depth: number, walk: Walk): number {
94
+ let sum = 0;
95
+ let read = 0;
96
+ let count = 0;
97
+ for (const key in record) {
98
+ if (!Object.hasOwn(record, key)) continue;
99
+ count += 1;
100
+ if (read === MEMBERS) continue;
101
+ sum += key.length + 4 + sized((record as Record<string, unknown>)[key], depth + 1, walk);
102
+ read += 1;
103
+ }
104
+ return count === 0 ? 2 : 2 + Math.round((sum / read) * count);
105
+ }
@@ -0,0 +1,28 @@
1
+ // UTF-8 byte length counted off the UTF-16 code units, allocating nothing. Every byte budget in
2
+ // this package (the LRU, the request memo) charges through it, so `TextEncoder.encode` — a full
3
+ // copy of the payload — never runs just to read `.byteLength` off the copy.
4
+
5
+ /**
6
+ * What `new TextEncoder().encode(text).byteLength` answers, without the copy. A surrogate PAIR is
7
+ * one astral code point, 4 bytes; a LONE surrogate is encoded as U+FFFD, 3 bytes — the same
8
+ * replacement `TextEncoder` makes, so the two never disagree on a budget.
9
+ */
10
+ export function utf8ByteLength(text: string): number {
11
+ let bytes = 0;
12
+ const length = text.length;
13
+ for (let i = 0; i < length; i += 1) {
14
+ const unit = text.charCodeAt(i);
15
+ if (unit < 0x80) bytes += 1;
16
+ else if (unit < 0x800) bytes += 2;
17
+ else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < length) {
18
+ const low = text.charCodeAt(i + 1);
19
+ if (low >= 0xdc00 && low <= 0xdfff) {
20
+ bytes += 4;
21
+ i += 1;
22
+ } else {
23
+ bytes += 3;
24
+ }
25
+ } else bytes += 3;
26
+ }
27
+ return bytes;
28
+ }
package/src/index.ts CHANGED
@@ -55,7 +55,10 @@ export {
55
55
  } from './invalidate';
56
56
  export type { LruOptions } from './lru';
57
57
  export { estimateBytes, LruCache, lruTier } from './lru';
58
- export { memoTier } from './memo';
58
+ export { MEMO_MAX_BYTES, memoTier } from './memo';
59
+ export type { MemoFlights } from './memo-flights';
60
+ export { memoFlights } from './memo-flights';
61
+ export { memoPerRequest } from './memo-per-request';
59
62
  export type { CloudflarePurgeOptions } from './purge-cloudflare';
60
63
  export { CLOUDFLARE_API_URL, cloudflarePurgeDriver } from './purge-cloudflare';
61
64
  export type { PurgeEnvironment, PurgeSelection } from './purge-env';
package/src/lru.ts CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Clock } from '@ultimat3/core';
7
7
  import { systemClock } from '@ultimat3/core';
8
+ import { utf8ByteLength } from './byte-length';
8
9
  import { CacheTooLargeError } from './errors';
9
10
  import type { CacheTag } from './tags';
10
11
  import { serializeTag } from './tags';
@@ -47,8 +48,6 @@ interface LruNode {
47
48
  next: LruNode | undefined;
48
49
  }
49
50
 
50
- const encoder = new TextEncoder();
51
-
52
51
  /**
53
52
  * `JSON.stringify` renders a `Map` or a `Set` as `{}` — two bytes for a collection of any size, so
54
53
  * a tier budgeted at 64 MiB held gigabytes of them without evicting once. Walked as their entries
@@ -60,14 +59,17 @@ const widenCollections = (_key: string, value: unknown): unknown => {
60
59
  return value;
61
60
  };
62
61
 
63
- /** Cheap, deterministic size estimate. Exact heap cost is unknowable; consistency matters. */
62
+ /**
63
+ * Cheap, deterministic size estimate. Exact heap cost is unknowable; consistency matters. Counted,
64
+ * never encoded: `utf8ByteLength` allocates nothing.
65
+ */
64
66
  export function estimateBytes(value: unknown): number {
65
67
  if (value === undefined) return 0;
66
- if (typeof value === 'string') return encoder.encode(value).byteLength;
68
+ if (typeof value === 'string') return utf8ByteLength(value);
67
69
  if (value instanceof ArrayBuffer) return value.byteLength;
68
70
  if (ArrayBuffer.isView(value)) return value.byteLength;
69
71
  try {
70
- return encoder.encode(JSON.stringify(value, widenCollections) ?? '').byteLength;
72
+ return utf8ByteLength(JSON.stringify(value, widenCollections) ?? '');
71
73
  } catch {
72
74
  return 1024;
73
75
  }
@@ -155,7 +157,7 @@ export class LruCache {
155
157
  // Encoded first: the budget is then the exact bytes held, and an unencodable value is refused
156
158
  // before anything is evicted for it.
157
159
  const text = encodeCacheValue({ v: value }, { key, tier: 'lru' });
158
- const bytes = estimateBytes(text) + encoder.encode(key).byteLength;
160
+ const bytes = utf8ByteLength(text) + utf8ByteLength(key);
159
161
  if (bytes > this.maxBytes) {
160
162
  throw new CacheTooLargeError({ key, bytes, maxBytes: this.maxBytes, tier: 'lru' });
161
163
  }
@@ -0,0 +1,32 @@
1
+ // `memoFlights(ctx, name)`: one named namespace of reads in flight inside a ctx's request memo —
2
+ // the store and byte bound `memoTier` and `memoPerRequest` use. It exists for `@ultimat3/query`,
3
+ // which is handed its ctx instead of reading the ALS one and keeps `fresh` reads that replace.
4
+
5
+ import { holdValue, storeOf } from './memo-store';
6
+
7
+ /** A ctx's reads under one name: joinable while pending, dropped on rejection, evicted oldest. */
8
+ export interface MemoFlights {
9
+ get(key: string): Promise<unknown> | undefined;
10
+ has(key: string): boolean;
11
+ /** Publish `flight` as the newest answer for `key`, replacing whatever was held. */
12
+ publish(key: string, flight: Promise<unknown>): void;
13
+ /** Bytes the WHOLE ctx memo holds (every namespace), against `MEMO_MAX_BYTES`. */
14
+ readonly bytes: number;
15
+ }
16
+
17
+ export function memoFlights(ctx: object, name: string): MemoFlights {
18
+ const store = storeOf(ctx, true);
19
+ const namespace = `\u0000flight:${name}\u0000`;
20
+ const held = (key: string): Promise<unknown> | undefined => {
21
+ const entry = store.entries.get(namespace + key);
22
+ return entry?.kind === 'value' ? (entry.value as Promise<unknown>) : undefined;
23
+ };
24
+ return {
25
+ get: held,
26
+ has: (key) => held(key) !== undefined,
27
+ publish: (key, flight) => holdValue(store, namespace + key, flight),
28
+ get bytes() {
29
+ return store.bytes;
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,37 @@
1
+ // `memoPerRequest(fn, key)`: the request memo for a plain function, over the same per-ctx store
2
+ // and byte bound as `memoTier` — one mechanism, a second entry point, so an app stops writing its
3
+ // own WeakMap-on-ctx wrapper. Outside a ctx it calls straight through.
4
+
5
+ import { holdValue, storeFor } from './memo-store';
6
+
7
+ /** Wrapper identities: two wrappers handed the same key string must not answer for each other. */
8
+ let wrappers = 0;
9
+
10
+ /**
11
+ * Memoize `fn` per request: the first call for a key in a ctx runs it, every later call in that
12
+ * ctx gets the same return value — for an async `fn`, the same promise, so concurrent calls join
13
+ * one flight. A rejected promise is dropped, so the next call retries. Each wrapper owns its key
14
+ * space, kept apart from `memoTier`'s keys by a NUL-prefixed namespace no tier key starts with.
15
+ *
16
+ * The value is held by reference, not through the cache codec: it is a function's own return
17
+ * value inside one request, not a cache entry shared between readers, and a promise or a class
18
+ * instance must come back as itself.
19
+ */
20
+ export function memoPerRequest<A extends readonly unknown[], R>(
21
+ fn: (...args: A) => R,
22
+ key: (...args: A) => string,
23
+ ): (...args: A) => R {
24
+ wrappers += 1;
25
+ const namespace = `\u0000memo:${wrappers}\u0000`;
26
+
27
+ return (...args: A): R => {
28
+ const store = storeFor(true);
29
+ if (store === undefined) return fn(...args);
30
+ const slot = namespace + key(...args);
31
+ const held = store.entries.get(slot);
32
+ if (held?.kind === 'value') return held.value as R;
33
+ const value = fn(...args);
34
+ holdValue(store, slot, value);
35
+ return value;
36
+ };
37
+ }
@@ -0,0 +1,159 @@
1
+ // The one per-request store behind `memoTier` and `memoPerRequest`: a Map per ALS ctx (WeakMap,
2
+ // so it dies with the ctx) under a byte bound. The bound is why this is one file: a job's ctx is
3
+ // the whole attempt, and an unbounded memo held every page a backfill ever read until it ended.
4
+
5
+ import type { Ctx } from '@ultimat3/core';
6
+ import { useContext } from '@ultimat3/core';
7
+ import { approxBytes } from './approx-bytes';
8
+ import { utf8ByteLength } from './byte-length';
9
+ import type { CacheTag } from './tags';
10
+
11
+ /**
12
+ * 8 MiB per ctx. A request never comes near it; a job attempt reading page after page does, and
13
+ * the memo is best-effort — an evicted entry is one more read, never a wrong one — so the oldest
14
+ * goes, silently.
15
+ */
16
+ export const MEMO_MAX_BYTES = 8 * 1024 * 1024;
17
+
18
+ /**
19
+ * A `memoTier` entry: codec text, as in every other tier — two callers in one request reading one
20
+ * key must not share one mutable object, and a hit here must be the shape the LRU or Redis would
21
+ * have answered.
22
+ */
23
+ export interface MemoTextEntry {
24
+ readonly kind: 'text';
25
+ readonly text: string;
26
+ readonly tags: readonly CacheTag[];
27
+ bytes: number;
28
+ }
29
+
30
+ /** A `memoPerRequest` entry: the function's own return value — a promise is the read in flight. */
31
+ export interface MemoValueEntry {
32
+ readonly kind: 'value';
33
+ readonly value: unknown;
34
+ bytes: number;
35
+ }
36
+
37
+ export type MemoEntry = MemoTextEntry | MemoValueEntry;
38
+
39
+ /** Insertion order is age: `Map` iterates oldest first, so the eviction needs no list. */
40
+ export interface MemoStore {
41
+ readonly entries: Map<string, MemoEntry>;
42
+ bytes: number;
43
+ }
44
+
45
+ const stores = new WeakMap<object, MemoStore>();
46
+
47
+ export function currentCtx(): object | undefined {
48
+ try {
49
+ const ctx: Ctx = useContext();
50
+ return typeof ctx === 'object' && ctx !== null ? (ctx as object) : undefined;
51
+ } catch {
52
+ // No ambient context: not a request. Nothing to memoize against.
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ export function storeFor(create: boolean): MemoStore | undefined {
58
+ const ctx = currentCtx();
59
+ return ctx === undefined ? undefined : storeOf(ctx, create);
60
+ }
61
+
62
+ /** The store of an EXPLICIT ctx — `@ultimat3/query` is handed its ctx rather than reading ALS. */
63
+ export function storeOf(ctx: object, create: true): MemoStore;
64
+ export function storeOf(ctx: object, create: boolean): MemoStore | undefined;
65
+ export function storeOf(ctx: object, create: boolean): MemoStore | undefined {
66
+ const existing = stores.get(ctx);
67
+ if (existing !== undefined) return existing;
68
+ if (!create) return undefined;
69
+ const fresh: MemoStore = { entries: new Map(), bytes: 0 };
70
+ stores.set(ctx, fresh);
71
+ return fresh;
72
+ }
73
+
74
+ export function dropStore(): void {
75
+ const ctx = currentCtx();
76
+ if (ctx !== undefined) stores.delete(ctx);
77
+ }
78
+
79
+ /**
80
+ * What an entry costs: its key plus its text, or its value from a bounded sample (`approxBytes`) —
81
+ * a held value is charged on every query read, so it is never serialised to be measured.
82
+ */
83
+ export function entryBytes(key: string, entry: MemoEntry): number {
84
+ const body = entry.kind === 'text' ? utf8ByteLength(entry.text) : approxBytes(entry.value);
85
+ return utf8ByteLength(key) + body;
86
+ }
87
+
88
+ export function removeEntry(store: MemoStore, key: string): void {
89
+ const entry = store.entries.get(key);
90
+ if (entry === undefined) return;
91
+ store.entries.delete(key);
92
+ store.bytes -= entry.bytes;
93
+ }
94
+
95
+ /**
96
+ * Re-price a held entry at `bytes` (a write, or an async value settling), then evict oldest-first
97
+ * to the bound. An entry over the bound on its own is dropped instead, evicting nothing.
98
+ */
99
+ export function charge(store: MemoStore, key: string, entry: MemoEntry, bytes: number): void {
100
+ if (store.entries.get(key) !== entry) return;
101
+ if (bytes > MEMO_MAX_BYTES) {
102
+ removeEntry(store, key);
103
+ return;
104
+ }
105
+ store.bytes += bytes - entry.bytes;
106
+ entry.bytes = bytes;
107
+ for (const [oldest] of store.entries) {
108
+ if (store.bytes <= MEMO_MAX_BYTES) break;
109
+ if (oldest !== key) removeEntry(store, oldest);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Store as the NEWEST entry. An entry over the bound on its own is not memoized and evicts nothing:
115
+ * clearing the whole store to hold one value it cannot hold would cost every other read.
116
+ */
117
+ export function putEntry(store: MemoStore, key: string, entry: MemoEntry): void {
118
+ removeEntry(store, key);
119
+ entry.bytes = 0;
120
+ store.entries.set(key, entry);
121
+ charge(store, key, entry, entryBytes(key, entry));
122
+ }
123
+
124
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
125
+ return (
126
+ (typeof value === 'object' || typeof value === 'function') &&
127
+ value !== null &&
128
+ typeof (value as { readonly then?: unknown }).then === 'function'
129
+ );
130
+ }
131
+
132
+ /**
133
+ * Hold a function's own return value as the NEWEST entry. A promise is the read in flight: charged
134
+ * at what it settles to (pending, it measures as `{}`), and dropped if it rejects — a rejection is
135
+ * not an answer. Both are no-ops once the entry was evicted or replaced in the meantime, so a
136
+ * later write is never undone by an earlier read settling.
137
+ *
138
+ * A pending entry is NOT pinned against eviction: evicting one costs the next reader a second read
139
+ * of the same source, never a wrong answer, and a pin would let N pending reads hold the bound open.
140
+ */
141
+ export function holdValue(store: MemoStore, slot: string, value: unknown): void {
142
+ const entry: MemoValueEntry = { kind: 'value', value, bytes: 0 };
143
+ putEntry(store, slot, entry);
144
+ if (!isThenable(value)) return;
145
+ // Neither handler may throw: a throw in either is an unhandled rejection of the promise
146
+ // `.then` returns, which nobody awaits. `approxBytes` cannot throw; the `try` is the guarantee.
147
+ value.then(
148
+ (settled) => {
149
+ try {
150
+ charge(store, slot, entry, entryBytes(slot, { ...entry, value: settled }));
151
+ } catch {
152
+ // Unmeasurable: it stays held at its pending charge, which is still under the bound.
153
+ }
154
+ },
155
+ () => {
156
+ if (store.entries.get(slot) === entry) removeEntry(store, slot);
157
+ },
158
+ );
159
+ }
package/src/memo.ts CHANGED
@@ -1,59 +1,28 @@
1
- // Tier 0: per-request memoization. Keyed off the ALS context object itself via a WeakMap,
2
- // so the store dies with the request — there is no `clear()` to forget, no cross-request
3
- // leak, and no lifecycle for an agent to get wrong. Outside a request (worker boot, a
4
- // script) the tier degrades to a no-op rather than throwing: memoization is never required
5
- // for correctness.
1
+ // Tier 0: per-request memoization over `memo-store.ts` — keyed off the ALS ctx, so it dies with
2
+ // the request, and bounded at `MEMO_MAX_BYTES` per ctx. Outside a request (worker boot, a script)
3
+ // the tier degrades to a no-op rather than throwing: memoization is never required for correctness.
6
4
 
7
- import type { Ctx } from '@ultimat3/core';
8
- import { useContext } from '@ultimat3/core';
5
+ import { dropStore, putEntry, removeEntry, storeFor } from './memo-store';
9
6
  import type { CacheTag } from './tags';
10
7
  import { tagsIntersect } from './tags';
11
8
  import type { CacheEntry, CacheSetOptions, CacheTier, TierInvalidation } from './tiers';
12
9
  import { assertTtl } from './tiers';
13
10
  import { decodeCacheValue, encodeCacheValue } from './value-codec';
14
11
 
15
- /**
16
- * Codec text, as in every other tier: two callers in one request reading one key must not share
17
- * one mutable object, and a hit here must be the shape the LRU or Redis would have answered.
18
- */
19
- interface MemoEntry {
20
- readonly text: string;
21
- readonly tags: readonly CacheTag[];
22
- }
23
-
24
- type MemoStore = Map<string, MemoEntry>;
25
-
26
- const stores = new WeakMap<object, MemoStore>();
27
-
28
- function currentCtx(): object | undefined {
29
- try {
30
- const ctx: Ctx = useContext();
31
- return typeof ctx === 'object' && ctx !== null ? (ctx as object) : undefined;
32
- } catch {
33
- // No ambient context: not a request. Nothing to memoize against.
34
- return undefined;
35
- }
36
- }
37
-
38
- function storeFor(create: boolean): MemoStore | undefined {
39
- const ctx = currentCtx();
40
- if (ctx === undefined) return undefined;
41
- const existing = stores.get(ctx);
42
- if (existing !== undefined) return existing;
43
- if (!create) return undefined;
44
- const fresh: MemoStore = new Map();
45
- stores.set(ctx, fresh);
46
- return fresh;
47
- }
12
+ export { MEMO_MAX_BYTES } from './memo-store';
48
13
 
49
14
  /** Escape hatch for `x dev`'s long-lived contexts; a normal request never calls this. */
50
15
  export function clearMemo(): void {
51
- const ctx = currentCtx();
52
- if (ctx !== undefined) stores.delete(ctx);
16
+ dropStore();
53
17
  }
54
18
 
55
19
  export function memoSize(): number {
56
- return storeFor(false)?.size ?? 0;
20
+ return storeFor(false)?.entries.size ?? 0;
21
+ }
22
+
23
+ /** Bytes the current ctx's memo holds, against `MEMO_MAX_BYTES`. 0 outside a ctx. */
24
+ export function memoBytes(): number {
25
+ return storeFor(false)?.bytes ?? 0;
57
26
  }
58
27
 
59
28
  export function memoTier(): CacheTier {
@@ -61,9 +30,10 @@ export function memoTier(): CacheTier {
61
30
  name: 'request-memo',
62
31
 
63
32
  get<T>(key: string): Promise<CacheEntry<T> | undefined> {
64
- const entry = storeFor(false)?.get(key);
65
- // No TTL check: a request is shorter than any meaningful TTL.
66
- if (entry === undefined) return Promise.resolve(undefined);
33
+ const entry = storeFor(false)?.entries.get(key);
34
+ // No TTL check: a request is shorter than any meaningful TTL. A `memoPerRequest` entry is
35
+ // never under a tier key (its keys are namespaced), so `kind` is a type guard, not a branch.
36
+ if (entry?.kind !== 'text') return Promise.resolve(undefined);
67
37
  const { v } = decodeCacheValue(entry.text) as { readonly v: T };
68
38
  return Promise.resolve({ value: v, tags: entry.tags });
69
39
  },
@@ -88,11 +58,15 @@ export function memoTier(): CacheTier {
88
58
  assertTtl(key, options.ttlMs, 'request-memo', { jitterFraction: 0 });
89
59
  }
90
60
  const text = encodeCacheValue({ v: value }, { key, tier: 'request-memo' });
91
- storeFor(true)?.set(key, { text, tags: options?.tags ?? [] });
61
+ const store = storeFor(true);
62
+ if (store !== undefined) {
63
+ putEntry(store, key, { kind: 'text', text, tags: options?.tags ?? [], bytes: 0 });
64
+ }
92
65
  },
93
66
 
94
67
  del(key: string): Promise<void> {
95
- storeFor(false)?.delete(key);
68
+ const store = storeFor(false);
69
+ if (store !== undefined) removeEntry(store, key);
96
70
  return Promise.resolve();
97
71
  },
98
72
 
@@ -102,9 +76,9 @@ export function memoTier(): CacheTier {
102
76
  return Promise.resolve({ tier: 'request-memo', keys: [], skipped: 'no request context' });
103
77
  }
104
78
  const keys: string[] = [];
105
- for (const [key, entry] of store) {
106
- if (tagsIntersect(tags, entry.tags)) {
107
- store.delete(key);
79
+ for (const [key, entry] of store.entries) {
80
+ if (entry.kind === 'text' && tagsIntersect(tags, entry.tags)) {
81
+ removeEntry(store, key);
108
82
  keys.push(key);
109
83
  }
110
84
  }