@ogygia/postrender 0.12.0 → 0.14.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/dist/registry.js CHANGED
@@ -1,107 +1,249 @@
1
- import { memory_store } from "./memory-store.js";
2
- import { normalize_prefix } from "./key.js";
1
+ import { MemoryStore } from "./memory-store.js";
2
+ import { in_subtree, normalize_prefix } from "./key.js";
3
3
  import { postrender_app } from "./app.js";
4
+ import { OgygiaError, warn } from "./messages.js";
5
+ import { buggify, flights, machine, outbox, policy, registry, say, scope, slot } from "@ogygia/machine";
4
6
  import { sourceTag } from "@ogygia/core/plugin/utils";
5
7
  // src/registry.ts
6
- const slot = globalThis[Symbol.for("ogygia.postrender.v1")] ??= {
7
- installed: null,
8
- handled: /* @__PURE__ */ new WeakMap(),
9
- fallback: null
10
- };
8
+ /** Dev and rules builds (a buggify point); folded out of any other. */
9
+ const RULES = import.meta.env?.DEV || (typeof __OGYGIA_RULES__ !== "undefined" ? __OGYGIA_RULES__ : false);
10
+ const slot$1 = slot({
11
+ name: "ogygia.postrender",
12
+ version: 1,
13
+ make: () => ({
14
+ installed: null,
15
+ handled: /* @__PURE__ */ new WeakMap(),
16
+ fallback: null
17
+ })
18
+ });
11
19
  /** A server event into the current request's devtools stream (a no-op unless devtools is on). */
12
20
  function record(event) {
13
21
  postrender_app()?.devtools(event);
14
22
  }
15
- let warned_replica_blindspot = false;
23
+ /** Said once for the process (a test's reset says it again). */
24
+ const replica_blindspot = say({ max: 1 });
25
+ const BLINDSPOT = "postrender_edges_without_shared_store";
16
26
  /** `postrender.handle(options)`'s first half: make these settings this server's runtime. */
17
27
  function install(options) {
18
28
  const edges = [...options.edge ?? []];
19
- if (edges.length && !options.store && !warned_replica_blindspot) {
20
- warned_replica_blindspot = true;
21
- console.warn("[ogygia] postrender: edge adapters are configured but the store is the per-instance memory default — invalidations cannot reach other replicas. Use a shared store (valkey / upstash / cloudflareKv) in multi-instance deploys.");
22
- }
29
+ if (edges.length && !options.store) replica_blindspot.once(BLINDSPOT, () => warn("postrender_edges_without_shared_store"));
23
30
  const runtime = {
24
- store: options.store ?? memory_store(),
31
+ store: options.store ?? new MemoryStore(),
25
32
  edges
26
33
  };
27
- slot.installed = runtime;
34
+ slot$1.installed = runtime;
28
35
  return runtime;
29
36
  }
30
37
  /** The handle's per-request half: this request came through it, with these settings. */
31
38
  function mark_handled(event, runtime) {
32
- slot.handled.set(event.request, runtime);
39
+ slot$1.handled.set(event.request, runtime);
33
40
  }
34
41
  /** The runtime of the `postrender.handle()` that saw this request first, or null. */
35
42
  function handled_runtime(event) {
36
- return slot.handled.get(event.request) ?? null;
43
+ return slot$1.handled.get(event.request) ?? null;
37
44
  }
38
45
  /** The latest `postrender.handle()` made in this process, or null when hooks.server.ts has none. */
39
46
  function installed_runtime() {
40
- return slot.installed;
47
+ return slot$1.installed;
41
48
  }
42
49
  /** This server's runtime: its handle's, else the memory default. */
43
50
  function current_runtime() {
44
- return slot.installed ?? (slot.fallback ??= {
45
- store: memory_store(),
51
+ return slot$1.installed ?? (slot$1.fallback ??= {
52
+ store: new MemoryStore(),
46
53
  edges: []
47
54
  });
48
55
  }
49
56
  /** Harness/test escape hatch: no handle made, a fresh memory default. */
50
57
  function reset_for_tests() {
51
- slot.installed = null;
52
- slot.handled = /* @__PURE__ */ new WeakMap();
53
- slot.fallback = null;
54
- warned_replica_blindspot = false;
58
+ slot$1.installed = null;
59
+ slot$1.handled = /* @__PURE__ */ new WeakMap();
60
+ slot$1.fallback = null;
61
+ replica_blindspot.ok(BLINDSPOT);
62
+ store_health = health_def.create();
63
+ renders.drop(() => true);
64
+ writes_life.close();
65
+ writes_life = scope();
55
66
  }
56
67
  function notify_thaw(tags) {
57
- postrender_app()?.notify.invalidated(tags);
68
+ postrender_app()?.notify.invalidated(tags).catch(() => {});
58
69
  }
59
70
  /** Evict every stored page carrying ANY of `tags` (origin + every edge). The receiving half of a
60
71
  * thaw notice; also what `invalidate(fn, args)` does for one receipt tag. */
61
72
  async function invalidate_tags(tags, runtime = current_runtime()) {
73
+ return (await evict_tags(tags, runtime)).keys;
74
+ }
75
+ /** `invalidate_tags`, with what the store failed to evict: the shared hook (a peer's thaw) must not
76
+ * answer "done" for a tag that is still stored (#287). */
77
+ async function evict_tags(tags, runtime = current_runtime()) {
78
+ stale_flights("all");
62
79
  const { store, edges } = runtime;
63
80
  const evict_by_tag = store.evictByTag?.bind(store);
64
81
  if (!evict_by_tag) {
65
- console.warn("[ogygia] postrender: the configured store has no evictByTag — tag invalidation needs it (memory/valkey/upstash/cloudflareKv all provide it).");
66
- return [];
82
+ warn("postrender_store_no_evict_by_tag");
83
+ return {
84
+ keys: [],
85
+ failed: []
86
+ };
67
87
  }
68
88
  const keys = /* @__PURE__ */ new Set();
89
+ const failed = [];
69
90
  for (const tag of tags) try {
70
91
  for (const key of await evict_by_tag(tag)) keys.add(key);
71
92
  } catch (e) {
72
- console.warn(`[ogygia] postrender.invalidate(tags): the store failed to evict tag ${tag} (evictByTag); its pages stay stored until they expire —`, e);
93
+ warn("postrender_tag_evict_failed", { tag }, e);
94
+ failed.push(e);
73
95
  }
74
96
  const jobs = [];
75
97
  for (const key of keys) for (const edge of edges) jobs.push(edge_job(edge, (e) => e.purgeUrl(key)));
76
98
  await settle_all("invalidate(tags)", jobs);
77
- return [...keys];
99
+ return {
100
+ keys: [...keys],
101
+ failed
102
+ };
103
+ }
104
+ const health_def = machine()({
105
+ name: "postrender store",
106
+ initial: "ok",
107
+ steps: {
108
+ ok: ["failing"],
109
+ failing: ["failing", "ok"]
110
+ }
111
+ });
112
+ let store_health = health_def.create();
113
+ function store_failed(op, key, error) {
114
+ const was = store_health.now.kind;
115
+ store_health.go("failing");
116
+ if (was === "ok") warn("postrender_store_failed", {
117
+ op,
118
+ key
119
+ }, error);
78
120
  }
79
- async function store_get(runtime, key) {
121
+ /** A store call that started in `mark` answered: the streak ends, unless a call failed since. */
122
+ function store_answered(mark) {
123
+ if (store_health.now === mark && mark.kind === "failing") store_health.go("ok");
124
+ }
125
+ /** `work` against the store: its failure is said, then thrown (for a caller that tries again). */
126
+ async function store_call(op, key, work) {
127
+ const mark = store_health.now;
80
128
  try {
81
- return await runtime.store.get(key);
82
- } catch {
83
- return null;
129
+ if (RULES && buggify.fires("postrender.store-down")) throw new Error("store down (buggify)");
130
+ const out = await work();
131
+ store_answered(mark);
132
+ return out;
133
+ } catch (error) {
134
+ store_failed(op, key, error);
135
+ throw error;
84
136
  }
85
137
  }
86
- async function store_put(runtime, key, entry, options) {
138
+ /** `work` against the store: its failure is said and answered `fallback`. */
139
+ async function guarded(op, key, work, fallback) {
87
140
  try {
88
- await runtime.store.put(key, entry, options);
89
- } catch {}
141
+ return await store_call(op, key, work);
142
+ } catch {
143
+ return fallback;
144
+ }
90
145
  }
91
- const inflight = /* @__PURE__ */ new Map();
92
- function join_flight(key) {
93
- return inflight.get(key) ?? null;
146
+ function store_get(runtime, key) {
147
+ return guarded("get", key, () => runtime.store.get(key), null);
94
148
  }
95
- function begin_flight(key) {
96
- let settle;
97
- const flight = new Promise((res) => {
98
- settle = res;
99
- });
100
- inflight.set(key, flight);
101
- return (outcome) => {
102
- inflight.delete(key);
103
- settle(outcome);
149
+ function store_put(runtime, key, entry, options) {
150
+ return guarded("put", key, () => runtime.store.put(key, entry, options), void 0);
151
+ }
152
+ /** The writes out now, each held from its start until it settles (and all of them until a test
153
+ * harness reset ends `writes_life`). */
154
+ const writes = registry();
155
+ let writes_life = scope();
156
+ /**
157
+ * Store a render's page. An invalidation that starts while the write is out ends the render's
158
+ * flight (it may have read what the invalidation changes), and its evict may run before the write
159
+ * lands: the page is then taken back out, through the same tried-again evict a post waits for.
160
+ * True when it stays stored.
161
+ *
162
+ * From the moment its flight goes stale until that evict ends, the page is RETRACTING: what the
163
+ * store holds for it may be the page from before the invalidation, so no hit is served from it
164
+ * (#332).
165
+ */
166
+ async function store_render(runtime, key, entry, options, flight) {
167
+ const write = {
168
+ key,
169
+ flight
104
170
  };
171
+ const settled = writes.add(write, writes_life);
172
+ try {
173
+ await store_put(runtime, key, entry, options);
174
+ if (!flight.stale) return true;
175
+ const mark = store_health.now;
176
+ if (await self_evicts.put({
177
+ runtime,
178
+ key
179
+ })) store_answered(mark);
180
+ return false;
181
+ } finally {
182
+ settled();
183
+ }
184
+ }
185
+ /** A stale render's page is being taken back out of the store: a hit for it is a miss. */
186
+ function retracting(key) {
187
+ for (const w of writes) if (w.key === key && w.flight.stale) return true;
188
+ return false;
189
+ }
190
+ /**
191
+ * One page's render, opened by the request that renders it: that request settles it exactly once,
192
+ * however it ends (the plugin's `done` settles one nothing else did), with what it stored, or null.
193
+ * An invalidation that would have evicted its page ends it while it renders (`stale`: what it read
194
+ * may be the page from before the publish): it is not stored, and the requests that joined it are
195
+ * let go at once to ask again (#194).
196
+ */
197
+ var Flight = class {
198
+ key;
199
+ outcome;
200
+ #settle;
201
+ #settled = false;
202
+ /** the flight's own signal: it aborts when an invalidation ends the flight */
203
+ #signal = null;
204
+ constructor(key) {
205
+ this.key = key;
206
+ this.outcome = new Promise((settle) => this.#settle = settle);
207
+ }
208
+ /** An invalidation ended it while it rendered. */
209
+ get stale() {
210
+ return !this.#settled && this.#signal?.aborted === true;
211
+ }
212
+ /** Settle it (once: a second settle does nothing). */
213
+ settle(outcome) {
214
+ if (this.#settled) return;
215
+ this.#settled = true;
216
+ this.#settle(outcome);
217
+ }
218
+ /** The flight's work: its outcome, once its request settles it. */
219
+ _fly(signal) {
220
+ this.#signal = signal;
221
+ return this.outcome;
222
+ }
223
+ };
224
+ /** The renders in progress, one per page: nothing is kept (the store keeps what they stored). The
225
+ * request that opens one holds it until it settles it. */
226
+ const renders = flights.keyed()({
227
+ name: "postrender flight",
228
+ key: ["key"],
229
+ ignore: { _fly: "the request that opens a page render runs it: the others join it" },
230
+ keep: 0,
231
+ run: (flight, signal) => flight._fly(signal)
232
+ });
233
+ /** The render of `key` in progress: join it (its outcome, `STALE` when an invalidation ended it),
234
+ * or, with none out, open it (`opened`: this request renders the page, and settles it however it
235
+ * ends). */
236
+ function enter_flight(key) {
237
+ const flight = new Flight(key);
238
+ const opens = renders.peek({ key }) === void 0;
239
+ const outcome = renders.get(flight);
240
+ return opens ? { opened: flight } : { joined: outcome };
241
+ }
242
+ /** An invalidation is starting: a render still out for a page it evicts may have read what it
243
+ * changes. It ends the renders whose page it would have evicted, had it been stored; the others go
244
+ * on and store. */
245
+ function stale_flights(evicts) {
246
+ renders.drop(({ key }) => evicts === "all" || ("url" in evicts ? key === evicts.url : in_subtree(key, evicts.prefix)));
105
247
  }
106
248
  /** A call as a promise, a synchronous throw included. */
107
249
  const attempt = (call) => Promise.resolve().then(call);
@@ -115,7 +257,10 @@ const edge_job = (edge, call) => ({
115
257
  });
116
258
  async function settle_all(label, jobs) {
117
259
  (await Promise.allSettled(jobs.map((job) => job.run))).forEach((r, i) => {
118
- if (r.status === "rejected") console.warn(`[ogygia] postrender.${label}: ${jobs[i].what} —`, r.reason);
260
+ if (r.status === "rejected") warn("postrender_fanout_failed", {
261
+ label,
262
+ what: jobs[i].what
263
+ }, r.reason);
119
264
  });
120
265
  }
121
266
  /**
@@ -128,6 +273,7 @@ async function settle_all(label, jobs) {
128
273
  */
129
274
  async function invalidate(target, args) {
130
275
  if (typeof target === "string") {
276
+ stale_flights({ url: target });
131
277
  record({
132
278
  domain: "server",
133
279
  name: "server.postrender",
@@ -142,7 +288,7 @@ async function invalidate(target, args) {
142
288
  return;
143
289
  }
144
290
  const tag = sourceTag(target, args ?? []);
145
- if (!tag) throw new Error("[ogygia] postrender.invalidate(fn, args): the function is not a declared source — wrap its definition: `export const fn = import.meta.og.source(async (…) => …)`.");
291
+ if (!tag) throw new OgygiaError("postrender_invalidate_not_source");
146
292
  await invalidate_tags([tag]);
147
293
  notify_thaw([tag]);
148
294
  }
@@ -151,6 +297,7 @@ async function invalidate(target, args) {
151
297
  * Cloudflare: prefix purge). */
152
298
  async function invalidateWhere(filter) {
153
299
  const prefix = normalize_prefix(filter.prefix);
300
+ stale_flights({ prefix });
154
301
  record({
155
302
  domain: "server",
156
303
  name: "server.postrender",
@@ -163,15 +310,39 @@ async function invalidateWhere(filter) {
163
310
  await settle_all("invalidateWhere", jobs);
164
311
  notify_thaw("all");
165
312
  }
166
- /** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the
167
- * edge copy follows via its s-maxage or the app's explicit invalidate; fire-and-forget). */
168
- function self_evict(runtime, pathname) {
313
+ /** How the origin store is tried again for an evict a response waits for: three quick tries within
314
+ * 2 s. The post's answer waits for it, so a store that is down costs the visitor that, not more. */
315
+ const STORE_POLICY = policy({
316
+ attempts: 3,
317
+ backoff: [50, 250],
318
+ jitter: .2,
319
+ deadline: 2e3
320
+ });
321
+ /** A post's evicts: tried again, kept alive by the platform past the response when the post does
322
+ * not wait (it does: `self_evict`'s caller), and said with the store's failure when given up. */
323
+ const self_evicts = outbox({
324
+ name: "postrender self-evict",
325
+ send: (e) => e.runtime.store.evict(e.key),
326
+ retry: STORE_POLICY,
327
+ giveUp: (e, error) => store_failed("evict", e.key, error),
328
+ waitUntil: (work) => postrender_app()?.keepAlive(work)
329
+ });
330
+ /** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the edge
331
+ * copy follows via its s-maxage or the app's explicit invalidate). Settles once the store took it
332
+ * out, or gave up (it never rejects): the response waits for it, so the redirect's GET right after
333
+ * cannot be answered with the page from before the post (#283). */
334
+ async function self_evict(runtime, pathname) {
335
+ stale_flights({ url: pathname });
169
336
  record({
170
337
  domain: "server",
171
338
  name: "server.postrender",
172
339
  op: "self-evict",
173
340
  url: pathname
174
341
  });
175
- runtime.store.evict(pathname).catch(() => {});
342
+ const mark = store_health.now;
343
+ if (await self_evicts.put({
344
+ runtime,
345
+ key: pathname
346
+ })) store_answered(mark);
176
347
  }
177
- export { begin_flight, current_runtime, handled_runtime, install, installed_runtime, invalidate, invalidateWhere, invalidate_tags, join_flight, mark_handled, reset_for_tests, self_evict, store_get, store_put };
348
+ export { Flight, current_runtime, enter_flight, evict_tags, handled_runtime, install, installed_runtime, invalidate, invalidateWhere, invalidate_tags, mark_handled, reset_for_tests, retracting, self_evict, store_call, store_get, store_put, store_render };
package/dist/server.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { FlightOutcome, Runtime } from "./registry.js";
1
+ import { Flight, Runtime } from "./registry.js";
2
2
  import { Observation } from "./observe.js";
3
3
  import { PostrenderEntry } from "./types.js";
4
4
  import { ServerPlugin } from "@ogygia/core/plugin";
@@ -13,20 +13,18 @@ export interface PostrenderServerOptions {
13
13
  interface State {
14
14
  /** the store + edges this request reads and writes (its `postrender.handle()`'s) */
15
15
  runtime: Runtime | null;
16
- /** settles the stampede flight this request opened (null when it opened none) */
17
- settle: ((outcome: FlightOutcome) => void) | null;
16
+ /** the stampede flight this request opened, until it settled it (registry.ts: `stale` once a
17
+ * publish landed while it rendered, so it is not stored) */
18
+ flight: Flight | null;
18
19
  /** the personalization observation (eligible requests only) */
19
20
  obs: Observation | null;
20
21
  /** the request was eligible to be stored */
21
22
  eligible: boolean;
23
+ /** its render is not stored: the request carried the visitor's credentials */
24
+ credentials: boolean;
22
25
  }
23
26
  export declare const MISSING_HANDLE: string;
24
27
  export declare const MISORDERED_HANDLE: string;
25
- /** Rebuild a Response from a stored page. `via` rides a debug header the harness asserts on.
26
- * With the incoming `request`, a matching validator answers 304 — plain-HTTP conditional
27
- * requests (RFC 9110), which is what makes a CDN or browser revalidation of a stored page cost
28
- * zero body bytes. Validators live on the ENTRY, never in edge adapters: they are the render's
29
- * identity, not a CDN dialect. */
30
28
  export declare function postrender_response(entry: PostrenderEntry, via: "hit" | "join" | "stored", request?: Request): Response;
31
29
  declare const server: ServerPlugin<PostrenderServerOptions, State>;
32
30
  export { server as default };