@ultimat3/render 30.9.0 → 31.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.
@@ -0,0 +1,66 @@
1
+ // Single responsibility: what a render tells core's instrumentation bus — `render.page` around a
2
+ // route component, `render.hole` around each streamed hole fill, `render.isr.regenerate` around an
3
+ // ISR generation — each inside an internal span carrying the route PATTERN as `http.route`.
4
+
5
+ import type { InstrumentEventMap } from '@ultimat3/core';
6
+ import { instrument, SEMCONV, subscribed, withSpan } from '@ultimat3/core';
7
+ import { routePatternOfFile } from './registry';
8
+ import type { HoleSink } from './render-html';
9
+
10
+ type RenderEventName = 'render.page' | 'render.hole' | 'render.isr.regenerate';
11
+
12
+ /** The route's pattern when the file is a registered route; the file itself otherwise, never a guess. */
13
+ export function routeOfFile(file: string): string {
14
+ return routePatternOfFile(file) ?? file;
15
+ }
16
+
17
+ /**
18
+ * Run `work` inside a span named for the event, then publish the event with its duration — and the
19
+ * failure, rethrown unchanged, when it threw.
20
+ */
21
+ export async function timedRender<N extends RenderEventName, T>(
22
+ name: N,
23
+ fields: Omit<InstrumentEventMap[N], 'durationMs' | 'error'>,
24
+ work: () => Promise<T>,
25
+ ): Promise<T> {
26
+ const started = performance.now();
27
+ const publish = (error?: unknown): void => {
28
+ if (!subscribed(name)) return;
29
+ const timed = {
30
+ durationMs: performance.now() - started,
31
+ ...(error === undefined ? {} : { error }),
32
+ };
33
+ instrument(name, { ...fields, ...timed } as InstrumentEventMap[N]);
34
+ };
35
+ try {
36
+ const result = await withSpan(name, work, {
37
+ kind: 'internal',
38
+ attributes: { [SEMCONV.httpRoute]: fields.route },
39
+ });
40
+ publish();
41
+ return result;
42
+ } catch (error) {
43
+ publish(error);
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The caller's sink, every hole's fill timed as `render.hole`. Holes, ids and `add` stay the
50
+ * caller's own, so the stream branch still reads the holes it handed in.
51
+ */
52
+ export function instrumentedHoles(sink: HoleSink, route: string): HoleSink {
53
+ return {
54
+ get holes() {
55
+ return sink.holes;
56
+ },
57
+ nextId: () => sink.nextId(),
58
+ add: (hole) =>
59
+ sink.add({
60
+ ...hole,
61
+ resolve: (signal) =>
62
+ timedRender('render.hole', { route, hole: hole.id }, () => hole.resolve(signal)),
63
+ }),
64
+ enter: sink.enter,
65
+ };
66
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What a store that SERIALIZES pages needs beside the store: an `IsrEntry` read back off bytes,
3
+ * totally — anything else is a miss, never a cast.
4
+ */
5
+
6
+ import type { IsrEntry } from './render-isr-store';
7
+
8
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
9
+ typeof value === 'object' && value !== null && !Array.isArray(value);
10
+
11
+ /**
12
+ * The stored text as an entry for `path`, or `undefined`. A shared store holds what another
13
+ * release, another app or a hand wrote: an object whose `path` is not the key it sits under is
14
+ * somebody else's page, and serving it would be #171 again.
15
+ */
16
+ export function parseIsrEntry(text: string, path: string): IsrEntry | undefined {
17
+ let value: unknown;
18
+ try {
19
+ value = JSON.parse(text);
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ if (!isRecord(value)) return undefined;
24
+ const { html, hash, generatedAt, ttlMs, stale, status } = value;
25
+ if (value['path'] !== path || typeof html !== 'string' || typeof hash !== 'string') {
26
+ return undefined;
27
+ }
28
+ if (typeof generatedAt !== 'number' || typeof stale !== 'boolean') return undefined;
29
+ if (ttlMs !== null && typeof ttlMs !== 'number') return undefined;
30
+ if (status !== undefined && typeof status !== 'number') return undefined;
31
+ // `ttlMs` and `status` are screened again where they are read (`entryTtlMs`, `isRenderStatus`).
32
+ return {
33
+ path,
34
+ html,
35
+ hash,
36
+ generatedAt,
37
+ ttlMs,
38
+ stale,
39
+ ...(status === undefined ? {} : { status }),
40
+ };
41
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The shared ISR store: pages and tag-fence generations as objects on a disk every replica
3
+ * reads, so three web replicas hold ONE copy of a page and a purge on any of them takes it down
4
+ * everywhere. Over `@ultimat3/storage`'s `StorageDriver` — `disk('isr')` — by its shape.
5
+ */
6
+
7
+ import type { Page } from '@ultimat3/core';
8
+ import { finiteCount, isUltimateError, logger } from '@ultimat3/core';
9
+ import type { IsrEntry, IsrStore, IsrTagFence } from './render-isr-store';
10
+ import { DEFAULT_ISR_MAX_BYTES, DEFAULT_ISR_MAX_ENTRIES } from './render-isr-store';
11
+ import { parseIsrEntry } from './render-isr-store-codec';
12
+
13
+ /** One object of a listing: what eviction needs. `StorageListEntry` is one. */
14
+ export interface IsrDiskEntry {
15
+ readonly key: string;
16
+ readonly size: number;
17
+ readonly lastModified?: Date | undefined;
18
+ }
19
+
20
+ /**
21
+ * The calls this store makes. `@ultimat3/storage`'s `StorageDriver` satisfies it as it is, so
22
+ * `storageIsrStore({ disk: disk('isr') })` needs no adapter; any other disk implementing these
23
+ * five does too. Render takes no import of storage for it: the store needs a shape, not a package.
24
+ */
25
+ export interface IsrDisk {
26
+ put(
27
+ key: string,
28
+ body: Uint8Array,
29
+ options?: { readonly contentType?: string | undefined },
30
+ ): Promise<unknown>;
31
+ /** Raises a coded `X_STORAGE_NOT_FOUND` for an absent key, as every shipped driver does. */
32
+ get(key: string): Promise<{ readonly bytes: Uint8Array }>;
33
+ delete(key: string): Promise<void>;
34
+ list(options?: {
35
+ readonly prefix?: string | undefined;
36
+ readonly cursor?: string | null | undefined;
37
+ }): Promise<Page<IsrDiskEntry>>;
38
+ }
39
+
40
+ export interface StorageIsrStoreOptions {
41
+ readonly disk: IsrDisk;
42
+ /** Every key this store writes starts with it. Default `isr/`. */
43
+ readonly prefix?: string;
44
+ /** Pages kept, across every replica. Default `DEFAULT_ISR_MAX_ENTRIES`. */
45
+ readonly maxEntries?: number;
46
+ /** Total stored bytes, across every replica. Default `DEFAULT_ISR_MAX_BYTES`. */
47
+ readonly maxBytes?: number;
48
+ /** How many writes, per process, between two sweeps of the bounds. Default 32. */
49
+ readonly sweepEvery?: number;
50
+ /** A fence token no other bump can have written. Injected so a test can name them. */
51
+ readonly token?: () => string;
52
+ }
53
+
54
+ const NOT_FOUND = 'X_STORAGE_NOT_FOUND';
55
+ const encoder = new TextEncoder();
56
+ const decoder = new TextDecoder();
57
+
58
+ /** Any string as a key segment: a path carries `?`, `&`, `%` and `/`, which a disk may not keep. */
59
+ const segment = (value: string): string =>
60
+ encoder.encode(value).toBase64({ alphabet: 'base64url', omitPadding: true });
61
+ const unsegment = (value: string): string =>
62
+ decoder.decode(Uint8Array.fromBase64(value, { alphabet: 'base64url' }));
63
+
64
+ export function storageIsrStore(options: StorageIsrStoreOptions): IsrStore {
65
+ const { disk } = options;
66
+ const prefix = options.prefix ?? 'isr/';
67
+ // `finiteCount` at each default: a cap that arrived `NaN` (an unset env value) is no cap at all.
68
+ const bounds = {
69
+ maxEntries: finiteCount(
70
+ 'storageIsrStore',
71
+ 'maxEntries',
72
+ options.maxEntries ?? DEFAULT_ISR_MAX_ENTRIES,
73
+ ),
74
+ maxBytes: finiteCount('storageIsrStore', 'maxBytes', options.maxBytes ?? DEFAULT_ISR_MAX_BYTES),
75
+ sweepEvery: finiteCount('storageIsrStore', 'sweepEvery', options.sweepEvery ?? 32, 1),
76
+ };
77
+ const token = options.token ?? (() => crypto.randomUUID());
78
+ const pages = `${prefix}page/`;
79
+ const pageKey = (path: string): string => `${pages}${segment(path)}`;
80
+ const fenceKey = (entity: string): string => `${prefix}fence/${segment(entity)}`;
81
+ let writes = 0;
82
+
83
+ /** The object's text, or `undefined` when there is none — the one refusal read as absence. */
84
+ async function read(key: string): Promise<string | undefined> {
85
+ try {
86
+ return decoder.decode((await disk.get(key)).bytes);
87
+ } catch (error) {
88
+ if (isUltimateError(error) && error.code === NOT_FOUND) return undefined;
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ async function listPages(): Promise<readonly IsrDiskEntry[]> {
94
+ const all: IsrDiskEntry[] = [];
95
+ let cursor: string | null = null;
96
+ do {
97
+ const page: Page<IsrDiskEntry> = await disk.list({ prefix: pages, cursor });
98
+ all.push(...page.rows);
99
+ cursor = page.nextCursor;
100
+ } while (cursor !== null);
101
+ return all;
102
+ }
103
+
104
+ /**
105
+ * Oldest WRITE first — an object's `lastModified`, the one clock every replica shares. Not
106
+ * least recently used: a read that wrote would turn every hit into a PUT. An object whose disk
107
+ * reports no time goes first, so a listing that cannot age still stays bounded.
108
+ */
109
+ async function sweep(): Promise<void> {
110
+ const held = [...(await listPages())].sort(
111
+ (a, b) => (a.lastModified?.getTime() ?? 0) - (b.lastModified?.getTime() ?? 0),
112
+ );
113
+ let bytes = held.reduce((sum, entry) => sum + entry.size, 0);
114
+ let count = held.length;
115
+ for (const oldest of held) {
116
+ if (count <= bounds.maxEntries && bytes <= bounds.maxBytes) break;
117
+ await disk.delete(oldest.key);
118
+ count -= 1;
119
+ bytes -= oldest.size;
120
+ }
121
+ }
122
+
123
+ async function set(entry: IsrEntry): Promise<void> {
124
+ const body = encoder.encode(JSON.stringify(entry));
125
+ // Kept, it would evict every other page and still be over the cap on its own. Measured on
126
+ // the bytes written — the size the sweep counts — never on `html.length`.
127
+ if (body.byteLength > bounds.maxBytes) {
128
+ await disk.delete(pageKey(entry.path));
129
+ return;
130
+ }
131
+ await disk.put(pageKey(entry.path), body, { contentType: 'application/json' });
132
+ writes += 1;
133
+ if (writes % bounds.sweepEvery === 1 || bounds.sweepEvery === 1) await sweep();
134
+ }
135
+
136
+ async function get(path: string): Promise<IsrEntry | undefined> {
137
+ const text = await read(pageKey(path));
138
+ if (text === undefined) return undefined;
139
+ const entry = parseIsrEntry(text, path);
140
+ if (entry === undefined) logger.warn('isr.store.entry_invalid', { path });
141
+ return entry;
142
+ }
143
+
144
+ const reading = async (entities: readonly string[]): Promise<string> =>
145
+ (await Promise.all(entities.map(async (entity) => (await read(fenceKey(entity))) ?? '0'))).join(
146
+ ',',
147
+ );
148
+
149
+ /**
150
+ * A bump writes a TOKEN no other bump wrote, never a counter: two replicas incrementing at once
151
+ * would both write `n + 1`, and a slow one writing `n` back would make an older reading current
152
+ * again. Any bump that starts after a reading leaves a value that reading never held.
153
+ */
154
+ const tagFence: IsrTagFence = {
155
+ sample: reading,
156
+ bump: async (entities) => {
157
+ await Promise.all(
158
+ entities.map((entity) => disk.put(fenceKey(entity), encoder.encode(token()))),
159
+ );
160
+ },
161
+ /**
162
+ * Write, then check again — a disk has no compare-and-put. A bust whose bump lands after the
163
+ * second read began after this page was written, so its listing (`revalidateHeld` lists after
164
+ * it bumps) finds the page and takes it down; one that lands before is seen here, and the page
165
+ * is deleted again. Either way no page outlives a bust that its render predates.
166
+ */
167
+ setIfCurrent: async (entry, entities, sampled) => {
168
+ if ((await reading(entities)) !== sampled) return false;
169
+ await set(entry);
170
+ if ((await reading(entities)) === sampled) return true;
171
+ await disk.delete(pageKey(entry.path));
172
+ return false;
173
+ },
174
+ };
175
+
176
+ return {
177
+ tagFence,
178
+ get,
179
+ set,
180
+ markStale: async (path) => {
181
+ const entry = await get(path);
182
+ if (entry === undefined) return false;
183
+ // A read-modify-write: a page regenerated between the two is marked stale too, which costs
184
+ // one render and never serves a stale page as fresh.
185
+ await disk.put(pageKey(path), encoder.encode(JSON.stringify({ ...entry, stale: true })), {
186
+ contentType: 'application/json',
187
+ });
188
+ return true;
189
+ },
190
+ delete: (path) => disk.delete(pageKey(path)),
191
+ paths: async () =>
192
+ (await listPages()).map((entry) => unsegment(entry.key.slice(pages.length))).sort(),
193
+ };
194
+ }
@@ -7,6 +7,13 @@ import { finiteCount } from '@ultimat3/core';
7
7
 
8
8
  export type IsrState = 'miss' | 'hit' | 'stale';
9
9
 
10
+ /**
11
+ * What a store method answers: the value, or a promise of it. A store over a disk, a bucket or a
12
+ * database cannot answer synchronously, and one shared store is what makes three replicas one
13
+ * ISR cache instead of three (`storageIsrStore`). The controller awaits every call.
14
+ */
15
+ export type IsrAnswer<T> = T | Promise<T>;
16
+
10
17
  export interface IsrEntry {
11
18
  /**
12
19
  * The store key: the request's pathname AND its query, params sorted. Not the route's pattern
@@ -44,11 +51,11 @@ export interface IsrEntry {
44
51
  */
45
52
  export interface IsrTagFence {
46
53
  /** An opaque reading of these entities' generations, taken before a render reads its rows. */
47
- sample(entities: readonly string[]): string;
54
+ sample(entities: readonly string[]): IsrAnswer<string>;
48
55
  /** A bust of these entities happened: every reading taken before this call is void. */
49
- bump(entities: readonly string[]): void;
56
+ bump(entities: readonly string[]): IsrAnswer<void>;
50
57
  /** `set(entry)` only while `sampled` is still the reading. `false`: refused, nothing written. */
51
- setIfCurrent(entry: IsrEntry, entities: readonly string[], sampled: string): boolean;
58
+ setIfCurrent(entry: IsrEntry, entities: readonly string[], sampled: string): IsrAnswer<boolean>;
52
59
  }
53
60
 
54
61
  export interface IsrStore {
@@ -58,14 +65,28 @@ export interface IsrStore {
58
65
  * route purges (`X_ROUTE_MODE_INVALID`), rather than left to re-fill a purged page in silence.
59
66
  */
60
67
  readonly tagFence?: IsrTagFence;
61
- get(path: string): IsrEntry | undefined;
62
- set(entry: IsrEntry): void;
68
+ get(path: string): IsrAnswer<IsrEntry | undefined>;
69
+ set(entry: IsrEntry): IsrAnswer<void>;
63
70
  /**
64
71
  * Mark a held page stale IN PLACE — `false` when the store does not hold it. Its own method and
65
72
  * not `set({ ...entry, stale: true })`, because `set` means "this page was just generated" and a
66
73
  * store is entitled to order its eviction by that: the read-modify-write made the STALEST page
67
74
  * the newest, so a tag bust protected exactly the pages that most needed regenerating.
68
75
  */
76
+ markStale(path: string): IsrAnswer<boolean>;
77
+ delete(path: string): IsrAnswer<void>;
78
+ paths(): IsrAnswer<readonly string[]>;
79
+ }
80
+
81
+ /** `memoryIsrStore`'s own shape: every answer synchronous, so a test reads it without `await`. */
82
+ export interface MemoryIsrStore extends IsrStore {
83
+ readonly tagFence: {
84
+ sample(entities: readonly string[]): string;
85
+ bump(entities: readonly string[]): void;
86
+ setIfCurrent(entry: IsrEntry, entities: readonly string[], sampled: string): boolean;
87
+ };
88
+ get(path: string): IsrEntry | undefined;
89
+ set(entry: IsrEntry): void;
69
90
  markStale(path: string): boolean;
70
91
  delete(path: string): void;
71
92
  paths(): readonly string[];
@@ -73,18 +94,27 @@ export interface IsrStore {
73
94
 
74
95
  /**
75
96
  * How many rendered pages the default store holds. A route table supports `:params` and `*`, so
76
- `/blog/:slug` has as many ISR paths as the blog has slugs — 404-shaped ones that still render
97
+ * `/blog/:slug` has as many ISR paths as the blog has slugs — 404-shaped ones that still render
77
98
  * included. Unbounded, a crawler over 100k slugs is 100k HTML strings resident for the life of
78
99
  * the process.
79
100
  */
80
101
  export const DEFAULT_ISR_MAX_ENTRIES = 1_000;
81
102
 
103
+ /**
104
+ * How much html the default store holds, counted as `html.length` — one byte per code unit, which
105
+ * is what JSC stores a Latin-1 page in (twice that for a page with any other character). The count
106
+ * cap alone bounds nothing in bytes: 1,000 entries of a 7 MiB page is 7 GiB resident.
107
+ */
108
+ export const DEFAULT_ISR_MAX_BYTES = 256 * 1024 * 1024;
109
+
82
110
  export interface MemoryIsrStoreOptions {
83
- /** Pages retained. The least recently generated goes first. */
111
+ /** Pages retained. The least recently used goes first. */
84
112
  readonly maxEntries?: number;
113
+ /** Total `html.length` retained. A page larger than this alone is not kept at all. */
114
+ readonly maxBytes?: number;
85
115
  }
86
116
 
87
- export function memoryIsrStore(options: MemoryIsrStoreOptions = {}): IsrStore {
117
+ export function memoryIsrStore(options: MemoryIsrStoreOptions = {}): MemoryIsrStore {
88
118
  // `map.size > NaN` is false for every size, so a cap that arrived non-finite is not a bigger
89
119
  // cap — it is no cap, and this store is the one thing bounding a crawler over 100k slugs.
90
120
  const maxEntries = finiteCount(
@@ -92,20 +122,35 @@ export function memoryIsrStore(options: MemoryIsrStoreOptions = {}): IsrStore {
92
122
  'maxEntries',
93
123
  options.maxEntries ?? DEFAULT_ISR_MAX_ENTRIES,
94
124
  );
125
+ const maxBytes = finiteCount(
126
+ 'memoryIsrStore',
127
+ 'maxBytes',
128
+ options.maxBytes ?? DEFAULT_ISR_MAX_BYTES,
129
+ );
130
+ // The Map's iteration order IS recency: a `set` and a hit `get` re-insert, so the first key is
131
+ // the least recently used page.
95
132
  const map = new Map<string, IsrEntry>();
133
+ let bytes = 0;
96
134
  // One counter per tag entity ever busted — bounded by the entities an app declares.
97
135
  const generations = new Map<string, number>();
98
136
  const reading = (entities: readonly string[]): string =>
99
137
  entities.map((entity) => String(generations.get(entity) ?? 0)).join(',');
138
+ const remove = (path: string): void => {
139
+ const held = map.get(path);
140
+ if (held === undefined) return;
141
+ bytes -= held.html.length;
142
+ map.delete(path);
143
+ };
100
144
  const set = (entry: IsrEntry): void => {
101
- // Re-inserted rather than overwritten, so the Map's iteration order IS generation order and
102
- // the first key is the least recently generated page.
103
- map.delete(entry.path);
145
+ remove(entry.path);
146
+ // Kept, it would evict every other page and then itself be the only one over the cap.
147
+ if (entry.html.length > maxBytes) return;
104
148
  map.set(entry.path, entry);
105
- while (map.size > maxEntries) {
149
+ bytes += entry.html.length;
150
+ while (map.size > maxEntries || bytes > maxBytes) {
106
151
  const oldest = map.keys().next();
107
152
  if (oldest.done === true) break;
108
- map.delete(oldest.value);
153
+ remove(oldest.value);
109
154
  }
110
155
  };
111
156
  return {
@@ -121,19 +166,24 @@ export function memoryIsrStore(options: MemoryIsrStoreOptions = {}): IsrStore {
121
166
  return true;
122
167
  },
123
168
  },
124
- get: (path) => map.get(path),
169
+ get: (path) => {
170
+ const entry = map.get(path);
171
+ if (entry === undefined) return undefined;
172
+ map.delete(path);
173
+ map.set(path, entry);
174
+ return entry;
175
+ },
125
176
  set,
126
177
  // In place: `map.set` on a key the Map already holds keeps its position, and that position is
127
- // the eviction order. Never `delete` + `set` here — that is the bug this method exists to fix.
178
+ // the eviction order. Never `delete` + `set` here — a bust would make the stalest page the
179
+ // most recently used. Same html, so the byte count does not move.
128
180
  markStale: (path) => {
129
181
  const entry = map.get(path);
130
182
  if (entry === undefined) return false;
131
183
  map.set(path, { ...entry, stale: true });
132
184
  return true;
133
185
  },
134
- delete: (path) => {
135
- map.delete(path);
136
- },
186
+ delete: remove,
137
187
  paths: () => [...map.keys()].sort(),
138
188
  };
139
189
  }
@@ -85,12 +85,17 @@ export interface IsrController {
85
85
  serve(path: string, render: IsrRenderFn): Promise<IsrServeResult>;
86
86
  /** Single-flight: concurrent callers for the same path share one render. */
87
87
  regenerate(path: string, render: IsrRenderFn): Promise<IsrEntry>;
88
- markStale(path: string): boolean;
88
+ /**
89
+ * The page's fence is marked at once; the store's answer (`false`: it held no such page) arrives
90
+ * when the store does — a shared store is a round trip.
91
+ */
92
+ markStale(path: string): Promise<boolean>;
89
93
  /**
90
94
  * Invalidate every ISR page carrying one of these tags — the ones the cache graph knows AND the
91
- * ones only the store holds — as each page's route declared: marked stale, or purged.
95
+ * ones only the store holds — as each page's route declared: marked stale, or purged. Async:
96
+ * the store is asked which pages it holds, and a shared store answers over the network.
92
97
  */
93
- revalidateByTags(tags: readonly CacheTag[]): readonly string[];
98
+ revalidateByTags(tags: readonly CacheTag[]): Promise<readonly string[]>;
94
99
  inflight(): number;
95
100
  store(): IsrStore;
96
101
  /**