foldkit-remote-server 0.20.0 → 0.22.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/fetch.mjs CHANGED
@@ -1,6 +1,126 @@
1
- import { d as declaresTooLarge, f as readJson, i as RemoteServer, p as tooLargeAnswer, v as unauthenticatedAnswer, y as serverDefect } from "./src-D8azLxgd.mjs";
2
- import { Cause, Deferred, Duration, Effect, Exit, Layer, Result, Schedule, Schema, Scope, Stream } from "effect";
3
- import { DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationError } from "foldkit-remote";
1
+ import { b as cachedReadDiffers, d as declaresTooLarge, f as discardBody, i as RemoteServer, m as tooLargeAnswer, p as readJson, x as serverDefect, y as unauthenticatedAnswer } from "./src-B1JAs_gH.mjs";
2
+ import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Result, Schedule, Schema, Scope, Stream } from "effect";
3
+ import { CacheStore, CachedRead, DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, MutationResult, PageReads, QueryRequest, QueryResult, ReadBatch, ReadBatchResult, Remote, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, listTag, maxAgeSeconds, rowTag, shorterPolicy, stableStringify } from "foldkit-remote";
4
+ // src/edgeCache.ts
5
+ /**
6
+ * Which reads a server may share between whoever asks, and the tags a store
7
+ * keeps them under (#428).
8
+ *
9
+ * A read is public only where the server can prove nothing about it depends
10
+ * on who asks: every source it passes through has no `authorize`, no
11
+ * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s
12
+ * `readable`) and no member answered per viewer, and every one declares how
13
+ * long it stays fresh. Those rules are functions of the principal this
14
+ * module cannot read, so it does not try: a source with one is private,
15
+ * even where its rule happens to read only the row. A public read is then
16
+ * answered as the visitor, whoever asks, so even a source's own `read` that
17
+ * looks at the principal gives everyone one answer, never someone's own.
18
+ */
19
+ /** A source's freshness, where nothing it runs is a rule about who asks. */
20
+ const sourcePolicy = (source) => source === void 0 || source.authorize !== void 0 || source.filter !== void 0 || source.visible !== void 0 || (source.perViewer ?? []).length > 0 ? Option.none() : Option.fromUndefinedOr(source.cache);
21
+ /** Two policies' shorter, none when either is none. */
22
+ const both = (a, b) => Option.flatMap(a, (left) => Option.map(b, (right) => shorterPolicy(left, right)));
23
+ /** A slice's policy: its entity's, and every relation's it reaches. */
24
+ const slicePolicy = (server, slice) => Object.values(slice.relations ?? {}).reduce((policy, relation) => both(policy, slicePolicy(server, relation)), sourcePolicy(server.entities.get(slice.entity)));
25
+ /** A read batch's policy: none for an empty one, which keeps nothing worth a key. */
26
+ const readPolicy = (server, batch) => batch.requests.length === 0 ? Option.none() : batch.requests.map((request) => slicePolicy(server, request)).reduce(both);
27
+ /** A query's policy: its own, its rows' and what its `select` reaches. */
28
+ const queryPolicy = (server, request) => {
29
+ const source = server.queries.get(request.query);
30
+ if (source === void 0 || source.visible !== void 0) return Option.none();
31
+ const own = both(Option.fromUndefinedOr(source.cache), sourcePolicy(server.entities.get(source.entity)));
32
+ return request.select === void 0 ? own : both(own, slicePolicy(server, request.select));
33
+ };
34
+ const rowTags = (rows) => rows.map((row) => rowTag(row.entity, row.id));
35
+ /** What a read's answer holds: each row asked for, found or not, and each it reached. */
36
+ const readTags = (batch, result) => [.../* @__PURE__ */ new Set([
37
+ ...rowTags(batch.requests),
38
+ ...rowTags(result.entities),
39
+ ...rowTags(result.settled)
40
+ ])];
41
+ /** What a query's answer holds: every list of its entity, and each row on the page. */
42
+ const queryTags = (server, request, result) => [.../* @__PURE__ */ new Set([
43
+ ...Option.toArray(Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), (source) => listTag(source.entity))),
44
+ ...rowTags(result.edges),
45
+ ...rowTags(result.entities ?? [])
46
+ ])];
47
+ const decodeMutationResult = Schema.decodeUnknownOption(MutationResult);
48
+ /**
49
+ * What a write's answer names, as tags to purge: each row it wrote, deleted,
50
+ * moved in a list or read back, and every list of each of their entities,
51
+ * which a changed row can join or leave. A write naming nothing purges nothing.
52
+ */
53
+ const writeTags = (result) => Option.match(decodeMutationResult(result), {
54
+ onNone: () => [],
55
+ onSome: (answer) => {
56
+ const rows = [
57
+ ...answer.entities,
58
+ ...answer.deleted ?? [],
59
+ ...(answer.connections ?? []).map((change) => change.edge),
60
+ ...answer.read?.result.entities ?? [],
61
+ ...(answer.lists ?? []).flatMap((list) => [...list.result.edges, ...list.result.entities ?? []])
62
+ ];
63
+ return [.../* @__PURE__ */ new Set([...rowTags(rows), ...rows.map((row) => listTag(row.entity))])];
64
+ }
65
+ });
66
+ /** An answer as anyone may be given it: without whom it was for. */
67
+ const unaddressed = (answer) => {
68
+ const { principal: _, ...rest } = answer;
69
+ return rest;
70
+ };
71
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ /**
73
+ * The key a request's answer is kept under: the SHA-256 of `text` (the
74
+ * request as stable JSON), under the request's own origin, since the Workers
75
+ * Cache API keys by URL.
76
+ */
77
+ const cacheKey = (url, kind, text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`));
78
+ /** The most rows a private read names: a batch can ask for hundreds. */
79
+ const NAMED_ROWS = 3;
80
+ /** What a read batch asked for, as a refusal names it: its first rows, and how many more. */
81
+ const batchName = (batch) => {
82
+ const rows = batch.requests.map((request) => `${request.entity} ${request.id}`);
83
+ const more = rows.length - NAMED_ROWS;
84
+ return `${rows.slice(0, NAMED_ROWS).join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
85
+ };
86
+ /**
87
+ * Handlers that answer every read and query proved public as `visitor`, and
88
+ * note each read in the render's `PageReads`: public with its policy and
89
+ * tags, or private. Without a visitor every read is private, and so is one
90
+ * that fails, since a page drawn without its read is no page to keep.
91
+ */
92
+ const notingHandlers = (server, own, visitor) => {
93
+ const note = (read) => Effect.flatMap(Effect.service(PageReads), (noted) => Effect.sync(() => Option.map(noted, (add) => add(read))));
94
+ return {
95
+ ...own,
96
+ FoldkitRemoteRead: (batch) => {
97
+ const unshared = note(CachedRead.Private({ read: batchName(batch) }));
98
+ return Option.match(Option.flatMap(visitor, (handlers) => Option.map(readPolicy(server, batch), (policy) => ({
99
+ handlers,
100
+ policy
101
+ }))), {
102
+ onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), unshared),
103
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteRead(batch), (result) => Effect.as(note(CachedRead.Public({
104
+ policy,
105
+ tags: readTags(batch, result)
106
+ })), unaddressed(result))).pipe(Effect.onError(() => unshared))
107
+ });
108
+ },
109
+ FoldkitRemoteQuery: (request) => {
110
+ const unshared = note(CachedRead.Private({ read: `query ${request.query}` }));
111
+ return Option.match(Option.flatMap(visitor, (handlers) => Option.map(queryPolicy(server, request), (policy) => ({
112
+ handlers,
113
+ policy
114
+ }))), {
115
+ onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), unshared),
116
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteQuery(request), (result) => Effect.as(note(CachedRead.Public({
117
+ policy,
118
+ tags: queryTags(server, request, result)
119
+ })), unaddressed(result))).pipe(Effect.onError(() => unshared))
120
+ });
121
+ }
122
+ };
123
+ };
4
124
  // src/fetch.ts
5
125
  /**
6
126
  * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
@@ -15,6 +135,41 @@ import { DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, Remote, RemoteLiv
15
135
  * binding, a session), and the Sources' requirements are provided per
16
136
  * request from the environment (a D1 binding, a connection string).
17
137
  */
138
+ const decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest);
139
+ const decodeBatch = Schema.decodeUnknownOption(ReadBatch);
140
+ const decodeQuery = Schema.decodeUnknownOption(QueryRequest);
141
+ const decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult);
142
+ const decodeQueryResult = Schema.decodeUnknownOption(QueryResult);
143
+ /** `body`, when it is a read or query every source of which is public. */
144
+ const shareableOf = (server, body) => Option.flatMap(decodeRequest(body), ({ operation, payload }) => ({
145
+ read: () => Option.flatMap(decodeBatch(payload), (batch) => Option.map(readPolicy(server, batch), (policy) => ({
146
+ policy,
147
+ tagsOf: (result) => Option.match(decodeReadResult(result), {
148
+ onNone: () => [],
149
+ onSome: (read) => readTags(batch, read)
150
+ })
151
+ }))),
152
+ query: () => Option.flatMap(decodeQuery(payload), (request) => Option.map(queryPolicy(server, request), (policy) => ({
153
+ policy,
154
+ tagsOf: (result) => Option.match(decodeQueryResult(result), {
155
+ onNone: () => [],
156
+ onSome: (page) => queryTags(server, request, page)
157
+ })
158
+ }))),
159
+ mutate: () => Option.none()
160
+ })[operation]());
161
+ /** An answer as anyone may be given it: its result without whom it was for. */
162
+ const unaddressedAnswer = (answer) => {
163
+ if (!("result" in answer) || typeof answer.result !== "object" || answer.result === null) return answer;
164
+ const { principal: _, ...result } = answer.result;
165
+ return { result };
166
+ };
167
+ /** Whether `body` is a write: what it names, a cache purges. */
168
+ const isWrite = (body) => Option.exists(decodeRequest(body), (request) => request.operation === "mutate");
169
+ /** A visitor the server's `viewer` names a row for is someone: their reads are their own. */
170
+ const refuseSomeone = (server, cache) => {
171
+ if (cache !== void 0 && server.viewer !== void 0 && Option.isSome(server.viewer(cache.visitor))) throw new Error("foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it");
172
+ };
18
173
  /** A live open over fetch: the requirements and the cursor it resumes after. */
19
174
  const LiveFetchRequest = Schema.Struct({
20
175
  operation: Schema.Literal("live"),
@@ -103,9 +258,11 @@ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) =
103
258
  */
104
259
  const serveFetch = (config) => {
105
260
  const path = config.path ?? "/remote";
261
+ refuseSomeone(config.server, config.cache);
106
262
  const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
107
263
  const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
108
264
  if (config.revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)) throw new Error("serveFetch: revalidate.every must be longer than zero");
265
+ const resolvePrincipal = config.resolvePrincipal;
109
266
  /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */
110
267
  const reportingFor = (request) => (effect) => {
111
268
  const { diagnostics } = config;
@@ -115,11 +272,53 @@ const serveFetch = (config) => {
115
272
  const revalidation = (request, env, opened) => {
116
273
  const { revalidate } = config;
117
274
  if (revalidate === void 0) return Stream.empty;
118
- return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(Stream.mapEffect(() => config.resolvePrincipal(request, env)), Stream.mapEffect((now) => revalidate.key === void 0 || revalidate.key(opened) === revalidate.key(now) ? Effect.void : Effect.fail(new RemoteLiveError({ message: "Who is asking changed: open the stream again" }))), Stream.drain);
275
+ return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(Stream.mapEffect(() => resolvePrincipal(request, env)), Stream.mapEffect((now) => revalidate.key === void 0 || revalidate.key(opened) === revalidate.key(now) ? Effect.void : Effect.fail(new RemoteLiveError({ message: "Who is asking changed: open the stream again" }))), Stream.drain);
119
276
  };
277
+ /**
278
+ * A public read: the visitor's answer, from the store or answered and kept.
279
+ * Under `check`, also the asker's own, which is given instead where they differ.
280
+ */
281
+ const answerShared = (request, body, cache, shareable, own, headers) => Effect.gen(function* () {
282
+ const asked = stableStringify(body);
283
+ const key = yield* cacheKey(request.url, "remote", asked);
284
+ const kept = yield* cache.store.match(key);
285
+ let text;
286
+ if (Option.isSome(kept)) text = kept.value;
287
+ else {
288
+ const visitor = RemoteServer.handlers(config.server, cache.visitor, {
289
+ maxIdsPerEntity: config.maxIdsPerEntity,
290
+ maxDepth: config.maxDepth
291
+ });
292
+ const answered = yield* RemoteServer.answer(visitor, body);
293
+ if (answered.status !== 200) return Response.json(answered.body, {
294
+ status: answered.status,
295
+ headers
296
+ });
297
+ text = JSON.stringify(unaddressedAnswer(answered.body));
298
+ yield* cache.store.put(key, text, {
299
+ maxAge: shareable.policy.maxAge,
300
+ tags: shareable.tagsOf("result" in answered.body ? answered.body.result : {})
301
+ });
302
+ }
303
+ if (cache.check === true) {
304
+ const mine = yield* RemoteServer.answer(own, body);
305
+ if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {
306
+ yield* Diagnostics.report(cachedReadDiffers(asked));
307
+ return Response.json(mine.body, {
308
+ status: mine.status,
309
+ headers
310
+ });
311
+ }
312
+ }
313
+ return new Response(text, { headers: {
314
+ "content-type": "application/json",
315
+ "cache-control": `public, max-age=${maxAgeSeconds(shareable.policy)}`,
316
+ ...headers
317
+ } });
318
+ });
120
319
  /** `live` is whether the response streams, and so owns `scope` until it ends. */
121
320
  const respond = (request, env, scope) => Effect.gen(function* () {
122
- const principal = yield* config.resolvePrincipal(request, env);
321
+ const principal = yield* resolvePrincipal(request, env);
123
322
  const headers = config.headers?.(principal) ?? {};
124
323
  const body = yield* Effect.result(readJson(request, maxBodyBytes));
125
324
  if (Result.isFailure(body)) {
@@ -144,7 +343,14 @@ const serveFetch = (config) => {
144
343
  live: response.status === 200
145
344
  };
146
345
  }
346
+ const { cache } = config;
347
+ const shareable = cache === void 0 ? Option.none() : shareableOf(config.server, body.success);
348
+ if (cache !== void 0 && Option.isSome(shareable)) return {
349
+ response: yield* answerShared(request, body.success, cache, shareable.value, handlers, headers),
350
+ live: false
351
+ };
147
352
  const answered = yield* RemoteServer.answer(handlers, body.success);
353
+ if (cache !== void 0 && answered.status === 200 && isWrite(body.success)) yield* cache.store.purge(writeTags("result" in answered.body ? answered.body.result : {}));
148
354
  return {
149
355
  response: Response.json(answered.body, {
150
356
  status: answered.status,
@@ -172,11 +378,39 @@ const serveFetch = (config) => {
172
378
  };
173
379
  return async (request, env) => {
174
380
  const response = await served(request, env);
175
- if (!response.headers.has("cache-control")) response.headers.set("cache-control", "no-store");
381
+ await discardBody(request, maxBodyBytes);
382
+ if (!response.headers.has("cache-control")) response.headers.set("cache-control", "private, no-store");
176
383
  return response;
177
384
  };
178
385
  };
179
386
  /**
387
+ * The cache's checker, for a test: serves each request twice through
388
+ * `serveFetch` with `cache.check` and a store in memory, so every public read
389
+ * is answered both as the visitor (kept, then from the store) and as whoever
390
+ * the request resolves to. Rejects naming each read whose answers differ, and
391
+ * when no read was public, which would check nothing. Give requests from at
392
+ * least two principals, a visitor's and someone's; each is a function, since
393
+ * a body is read once.
394
+ */
395
+ const checkCache = async (config, requests, env) => {
396
+ const store = CacheStore.memory();
397
+ const differs = [];
398
+ const serve = serveFetch({
399
+ ...config,
400
+ cache: {
401
+ ...config.cache,
402
+ store,
403
+ check: true
404
+ },
405
+ diagnostics: (diagnostic) => Effect.sync(() => {
406
+ if (diagnostic._tag === "CachedReadDiffers") differs.push(diagnostic.message);
407
+ })
408
+ });
409
+ for (const _round of [1, 2]) for (const make of requests) await serve(make(), env);
410
+ if (differs.length > 0) throw new Error(differs.join("\n"));
411
+ if (store.size() === 0) throw new Error("checkCache: no request was a public read, so nothing was checked");
412
+ };
413
+ /**
180
414
  * The reader a page render reads through, in the same process: the request's
181
415
  * `RemoteClient`, answered by the server's own handlers with no HTTP between
182
416
  * them. Give it `serveFetch`'s config with the resolver a page's request
@@ -189,18 +423,29 @@ const serveFetch = (config) => {
189
423
  * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only
190
424
  * reads: a mutation fails with `RemoteMutationError` and a live open with
191
425
  * `RemoteLiveError`, since a navigation can be started from another site.
426
+ *
427
+ * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):
428
+ * with `cache`, one proved public as `serveFetch` proves it is answered as
429
+ * `cache.visitor` and noted public; every other read, and every read without
430
+ * `cache`, is noted private, which keeps the page from being cached.
192
431
  */
193
- const pageReader = (config) => (request, env) => Layer.unwrap(Effect.map(config.resolvePrincipal(request, env), (principal) => {
194
- const handlers = RemoteServer.handlers(config.server, principal, {
432
+ const pageReader = (config) => {
433
+ refuseSomeone(config.server, config.cache);
434
+ const limits = {
195
435
  maxIdsPerEntity: config.maxIdsPerEntity,
196
436
  maxDepth: config.maxDepth
197
- });
198
- return Remote.clientLayer({
199
- ...handlers,
200
- FoldkitRemoteMutate: () => Effect.fail(new RemoteMutationError({ message: "A page render reads; it does not write" })),
201
- FoldkitRemoteLive: () => Stream.fail(new RemoteLiveError({ message: "A page render keeps no live stream" }))
202
- });
203
- })).pipe(Layer.provide(config.layer(env)));
204
- export { pageReader, serveFetch };
437
+ };
438
+ const visitor = Option.map(Option.fromUndefinedOr(config.cache), (cache) => RemoteServer.handlers(config.server, cache.visitor, limits));
439
+ const resolvePrincipal = config.resolvePrincipal;
440
+ return (request, env) => Layer.unwrap(Effect.map(resolvePrincipal(request, env), (principal) => {
441
+ const handlers = notingHandlers(config.server, RemoteServer.handlers(config.server, principal, limits), visitor);
442
+ return Remote.clientLayer({
443
+ ...handlers,
444
+ FoldkitRemoteMutate: () => Effect.fail(new RemoteMutationError({ message: "A page render reads; it does not write" })),
445
+ FoldkitRemoteLive: () => Stream.fail(new RemoteLiveError({ message: "A page render keeps no live stream" }))
446
+ });
447
+ })).pipe(Layer.provide(config.layer(env)));
448
+ };
449
+ export { checkCache, pageReader, serveFetch };
205
450
 
206
451
  //# sourceMappingURL=fetch.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport {\n Cause,\n Deferred,\n Duration,\n Effect,\n Exit,\n Layer,\n Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\n Diagnostics,\n LiveRequirement,\n Remote,\n RemoteLiveError,\n RemoteMutationError,\n type Diagnostic,\n type RemoteClient,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n} from 'foldkit-remote'\nimport { declaresTooLarge, readJson, tooLargeAnswer } from './body.js'\nimport { serverDefect } from './diagnostics.js'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env, RP = never> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /**\n * Who this request is, from the request and the environment. Fails with\n * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.\n * What it needs (a session store, an auth service) comes from `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /**\n * What the Sources and the resolver need, from the environment. Built per\n * request, so kept cheap, and closed when the answer is sent, or, for a\n * live stream, when the stream ends.\n */\n readonly layer: (env: Env) => Layer.Layer<R | RP>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /**\n * Headers every answer to `principal` carries, a live stream's included;\n * a refusal has no principal and carries none. Whom the request was\n * answered as, say, for a client to repeat (`foldkit-auth`'s\n * `AuthServer.answered`).\n */\n readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /**\n * Asks `resolvePrincipal` again, of the same request, every `every` while a\n * live stream is open. A refusal ends the stream with `Unauthenticated`,\n * which the client reads as a lost session; a principal whose `key`\n * differs from the one the stream opened with (`Policy.keyOf`, as\n * `liveHub`'s `key`) ends it as a live error, which the client opens again\n * after, as the new principal; without `key` only a refusal ends it.\n * Without `revalidate` a stream serves the principal it opened with until\n * it closes, a revoked session included.\n * `every` must be longer than zero: each pass asks the session store.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: P) => unknown) | undefined\n }\n | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /**\n * Where this request's diagnostics go, with the request: each failure\n * answered \"Internal error\" or ending a live stream (a `ServerDefect`: a\n * broken layer or resolver, a handler's defect), whose cause the caller is\n * never told, and what the handlers report. The reporter in the Effect\n * context (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n /** A read batch may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many levels; default 8. */\n readonly maxDepth?: number | undefined\n /**\n * A request body may not be larger than this many bytes; default 1 MiB. A\n * larger one is a 413 with Remote's `tooLarge` answer, refused before it is\n * decoded: by its `content-length` before the principal is resolved, or\n * once the bytes read pass the limit. Give the client the same number\n * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.\n */\n readonly maxBodyBytes?: number | undefined\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/**\n * A terminal stream failure, so the client fails with its message instead of\n * hanging; a refusal of who is asking says so, as a 401's body does.\n */\nconst errorFrame = (\n message: string,\n refusal: Partial<RemoteJsonAnswer> | { readonly refused: true } = {},\n): string => `event: error\\ndata: ${JSON.stringify({ message, ...refusal })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n): Stream.Stream<Uint8Array, never, R | RC> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n // The checks fail the stream, or stop with it.\n const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, {\n haltStrategy: 'left',\n }).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error => Stream.succeed(errorFrame(error.message)),\n // The client reads `refused` as asking again being refused again.\n RemoteLiveRefused: error => Stream.succeed(errorFrame(error.message, { refused: true })),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n Unauthenticated: error =>\n Stream.succeed(\n errorFrame(error.message, {\n unauthenticated: unauthenticatedAnswer(error).body.unauthenticated,\n }),\n ),\n }),\n // A defect says nothing of itself to the client, as a 500 does, and is\n // reported; an interruption is the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.fromEffect(\n Effect.as(Diagnostics.report(serverDefect(cause)), errorFrame('Internal error')),\n ),\n ),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing. Once the stream\n * runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n release: Effect.Effect<void>,\n headers: Readonly<Record<string, string>>,\n): Effect.Effect<Response, never, R | RC> =>\n Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(\n Effect.matchEffect({\n onFailure: () =>\n Effect.succeed(\n Response.json(\n { error: 'The live payload is not a requirement' },\n { status: 400, headers },\n ),\n ),\n onSuccess: requirement =>\n Effect.map(\n Stream.toReadableStreamEffect(\n liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release)),\n ),\n body =>\n new Response(body, {\n headers: {\n ...headers,\n 'content-type': 'text/event-stream',\n },\n }),\n ),\n }),\n )\n\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. Each request is one Effect, with `layer` built once for it:\n * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`\n * (a 401, its `reason` the only words the caller reads); then the body. A\n * body that is not JSON, or not a request, is a 400 that reaches no handler;\n * a handler's failure a 500 with its message; anything else this side\n * breaks, the resolver's defects and the layer included, a 500 that says\n * nothing of it. A live open is answered with the stream instead. Each\n * answer is one principal's, so every response says `cache-control:\n * no-store`, unless `headers` gives a `cache-control` of its own.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env, RP = never>(\n config: FetchConfig<P, R, Env, RP>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT\n if (\n config.revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)\n )\n throw new Error('serveFetch: revalidate.every must be longer than zero')\n /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */\n const reportingFor =\n (request: Request) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n const { diagnostics } = config\n return diagnostics === undefined\n ? effect\n : Effect.provideService(effect, Diagnostics.Reporter, diagnostic =>\n diagnostics(diagnostic, request),\n )\n }\n /** The live stream's principal, asked again of its request while it runs. */\n const revalidation = (\n request: Request,\n env: Env,\n opened: P,\n ): Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RP> => {\n const { revalidate } = config\n if (revalidate === undefined) return Stream.empty\n return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(\n Stream.mapEffect(() => config.resolvePrincipal(request, env)),\n Stream.mapEffect(now =>\n revalidate.key === undefined || revalidate.key(opened) === revalidate.key(now)\n ? Effect.void\n : Effect.fail(\n new RemoteLiveError({ message: 'Who is asking changed: open the stream again' }),\n ),\n ),\n Stream.drain,\n )\n }\n /** `live` is whether the response streams, and so owns `scope` until it ends. */\n const respond = (\n request: Request,\n env: Env,\n scope: Scope.Closeable,\n ): Effect.Effect<{ readonly response: Response; readonly live: boolean }, never, R | RP> =>\n Effect.gen(function* () {\n const principal = yield* config.resolvePrincipal(request, env)\n const headers = config.headers?.(principal) ?? {}\n const body = yield* Effect.result(readJson(request, maxBodyBytes))\n if (Result.isFailure(body)) {\n const { status, answer } = body.failure\n return { response: Response.json(answer, { status, headers }), live: false }\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body.success)) {\n const response = yield* liveResponse(\n handlers,\n body.success.payload,\n heartbeat,\n revalidation(request, env, principal),\n Scope.close(scope, Exit.void),\n headers,\n )\n // A 400 for a payload no stream speaks has no stream to close it.\n return { response, live: response.status === 200 }\n }\n const answered = yield* RemoteServer.answer(handlers, body.success)\n return {\n response: Response.json(answered.body, { status: answered.status, headers }),\n live: false,\n }\n }).pipe(\n Effect.catchTag('Unauthenticated', refusal => {\n const { status, body } = unauthenticatedAnswer(refusal)\n return Effect.succeed({ response: Response.json(body, { status }), live: false })\n }),\n )\n const served = async (request: Request, env: Env): Promise<Response> => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n // Refused on what it says of itself: no layer built, no principal asked, nothing read.\n if (declaresTooLarge(request, maxBodyBytes)) {\n return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 })\n }\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n // Not Effect.provide(layer), which closes it when `respond` returns,\n // before a live stream has served a frame: the stream's re-reads and\n // revalidation would run on released resources.\n const scope = yield* Scope.make()\n const answered = yield* Layer.buildWithScope(config.layer(env), scope).pipe(\n Effect.flatMap(context => Effect.provide(respond(request, env, scope), context)),\n Effect.onExit(exit =>\n Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit),\n ),\n )\n return answered.response\n }).pipe(reportingFor(request)),\n )\n if (Exit.isSuccess(exit)) return exit.value\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what; the diagnostics learn what. `answer`\n // already maps its own failures and defects to 400/500 answers.\n await Effect.runPromise(\n Diagnostics.report(serverDefect(exit.cause)).pipe(reportingFor(request)),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Every answer is read as one principal: no cache may keep it for another.\n // A `cache-control` of the application's own (`headers`) stands.\n return async (request, env) => {\n const response = await served(request, env)\n if (!response.headers.has('cache-control')) response.headers.set('cache-control', 'no-store')\n return response\n }\n}\n\n/** What `pageReader` reads of a `serveFetch` config: the server, its Sources' layer and its limits. */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth'\n>\n\n/**\n * The reader a page render reads through, in the same process: the request's\n * `RemoteClient`, answered by the server's own handlers with no HTTP between\n * them. Give it `serveFetch`'s config with the resolver a page's request\n * needs: a page `GET` is a navigation, which carries no header a script adds\n * (`AuthServer.resolver({ …, requests: 'navigation' })`).\n *\n * The principal is resolved, and `layer` built, when the reader is provided,\n * and `layer` closes when the Effect it was provided to ends, so provide it to\n * the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A\n * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only\n * reads: a mutation fails with `RemoteMutationError` and a live open with\n * `RemoteLiveError`, since a navigation can be started from another site.\n */\nexport const pageReader =\n <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) =>\n (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(config.resolvePrincipal(request, env), principal => {\n const handlers = RemoteServer.handlers(config.server, principal, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n return Remote.clientLayer<R>({\n ...handlers,\n FoldkitRemoteMutate: () =>\n Effect.fail(\n new RemoteMutationError({ message: 'A page render reads; it does not write' }),\n ),\n FoldkitRemoteLive: () =>\n Stream.fail(new RemoteLiveError({ message: 'A page render ke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OAAO,OAAO,SAAS,QAAQ;EAC7B,MAAM,WAAW,MAAM,OAAO,SAAS,GAAG;EAC1C,IAAI,CAAC,SAAS,QAAQ,IAAI,eAAe,GAAG,SAAS,QAAQ,IAAI,iBAAiB,UAAU;EAC5F,OAAO;CACT;AACF;;;;;;;;;;;;;;;AAsBA,MAAa,cACa,YACvB,SAAkB,QACjB,MAAM,OACJ,OAAO,IAAI,OAAO,iBAAiB,SAAS,GAAG,IAAG,cAAa;CAC7D,MAAM,WAAW,aAAa,SAAS,OAAO,QAAQ,WAAW;EAC/D,iBAAiB,OAAO;EACxB,UAAU,OAAO;CACnB,CAAC;CACD,OAAO,OAAO,YAAe;EAC3B,GAAG;EACH,2BACE,OAAO,KACL,IAAI,oBAAoB,EAAE,SAAS,yCAAyC,CAAC,CAC/E;EACF,yBACE,OAAO,KAAK,IAAI,gBAAgB,EAAE,SAAS,qCAAqC,CAAC,CAAC;CACtF,CAAC;AACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC"}
1
+ {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/edgeCache.ts","../src/fetch.ts"],"sourcesContent":["/**\n * Which reads a server may share between whoever asks, and the tags a store\n * keeps them under (#428).\n *\n * A read is public only where the server can prove nothing about it depends\n * on who asks: every source it passes through has no `authorize`, no\n * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s\n * `readable`) and no member answered per viewer, and every one declares how\n * long it stays fresh. Those rules are functions of the principal this\n * module cannot read, so it does not try: a source with one is private,\n * even where its rule happens to read only the row. A public read is then\n * answered as the visitor, whoever asks, so even a source's own `read` that\n * looks at the principal gives everyone one answer, never someone's own.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport {\n CachedRead,\n MutationResult,\n PageReads,\n QueryResult,\n ReadBatchResult,\n listTag,\n rowTag,\n shorterPolicy,\n type CachePolicy,\n type ReadBatch,\n type QueryRequest,\n type RelationRequirement,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport type { EntitySource, ServerDefinition } from './index.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype QueryAsked = Schema.Schema.Type<typeof QueryRequest>\n\n/** A source's freshness, where nothing it runs is a rule about who asks. */\nconst sourcePolicy = <P, R>(source: EntitySource<P, R> | undefined): Option.Option<CachePolicy> =>\n source === undefined ||\n source.authorize !== undefined ||\n source.filter !== undefined ||\n source.visible !== undefined ||\n (source.perViewer ?? []).length > 0\n ? Option.none()\n : Option.fromUndefinedOr(source.cache)\n\n/** Two policies' shorter, none when either is none. */\nconst both = (a: Option.Option<CachePolicy>, b: Option.Option<CachePolicy>) =>\n Option.flatMap(a, left => Option.map(b, right => shorterPolicy(left, right)))\n\n/** A slice's policy: its entity's, and every relation's it reaches. */\nconst slicePolicy = <P, R>(\n server: ServerDefinition<P, R>,\n slice: RelationRequirement,\n): Option.Option<CachePolicy> =>\n Object.values(slice.relations ?? {}).reduce(\n (policy, relation) => both(policy, slicePolicy(server, relation)),\n sourcePolicy(server.entities.get(slice.entity)),\n )\n\n/** A read batch's policy: none for an empty one, which keeps nothing worth a key. */\nexport const readPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n batch: Batch,\n): Option.Option<CachePolicy> =>\n batch.requests.length === 0\n ? Option.none()\n : batch.requests.map(request => slicePolicy(server, request)).reduce(both)\n\n/** A query's policy: its own, its rows' and what its `select` reaches. */\nexport const queryPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n): Option.Option<CachePolicy> => {\n const source = server.queries.get(request.query)\n if (source === undefined || source.visible !== undefined) return Option.none()\n const own = both(\n Option.fromUndefinedOr(source.cache),\n sourcePolicy(server.entities.get(source.entity)),\n )\n return request.select === undefined ? own : both(own, slicePolicy(server, request.select))\n}\n\ntype Row = { readonly entity: string; readonly id: string }\n\nconst rowTags = (rows: ReadonlyArray<Row>): ReadonlyArray<string> =>\n rows.map(row => rowTag(row.entity, row.id))\n\n/** What a read's answer holds: each row asked for, found or not, and each it reached. */\nexport const readTags = (\n batch: Batch,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n): ReadonlyArray<string> => [\n ...new Set([...rowTags(batch.requests), ...rowTags(result.entities), ...rowTags(result.settled)]),\n]\n\n/** What a query's answer holds: every list of its entity, and each row on the page. */\nexport const queryTags = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n result: Schema.Schema.Type<typeof QueryResult>,\n): ReadonlyArray<string> => [\n ...new Set([\n ...Option.toArray(\n Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), source =>\n listTag(source.entity),\n ),\n ),\n ...rowTags(result.edges),\n ...rowTags(result.entities ?? []),\n ]),\n]\n\nconst decodeMutationResult = Schema.decodeUnknownOption(MutationResult)\n\n/**\n * What a write's answer names, as tags to purge: each row it wrote, deleted,\n * moved in a list or read back, and every list of each of their entities,\n * which a changed row can join or leave. A write naming nothing purges nothing.\n */\nexport const writeTags = (result: unknown): ReadonlyArray<string> =>\n Option.match(decodeMutationResult(result), {\n onNone: () => [],\n onSome: answer => {\n const rows: ReadonlyArray<Row> = [\n ...answer.entities,\n ...(answer.deleted ?? []),\n ...(answer.connections ?? []).map(change => change.edge),\n ...(answer.read?.result.entities ?? []),\n ...(answer.lists ?? []).flatMap(list => [\n ...list.result.edges,\n ...(list.result.entities ?? []),\n ]),\n ]\n return [...new Set([...rowTags(rows), ...rows.map(row => listTag(row.entity))])]\n },\n })\n\n/** An answer as anyone may be given it: without whom it was for. */\nconst unaddressed = <A extends { readonly principal?: unknown }>(\n answer: A,\n): Omit<A, 'principal'> => {\n const { principal: _, ...rest } = answer\n return rest\n}\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('')\n\n/**\n * The key a request's answer is kept under: the SHA-256 of `text` (the\n * request as stable JSON), under the request's own origin, since the Workers\n * Cache API keys by URL.\n */\nexport const cacheKey = (url: string, kind: string, text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`),\n )\n\n/** The most rows a private read names: a batch can ask for hundreds. */\nconst NAMED_ROWS = 3\n\n/** What a read batch asked for, as a refusal names it: its first rows, and how many more. */\nconst batchName = (batch: Batch): string => {\n const rows = batch.requests.map(request => `${request.entity} ${request.id}`)\n const more = rows.length - NAMED_ROWS\n return `${rows.slice(0, NAMED_ROWS).join(', ')}${more > 0 ? ` and ${more} more` : ''}`\n}\n\n/**\n * Handlers that answer every read and query proved public as `visitor`, and\n * note each read in the render's `PageReads`: public with its policy and\n * tags, or private. Without a visitor every read is private, and so is one\n * that fails, since a page drawn without its read is no page to keep.\n */\nexport const notingHandlers = <P, R>(\n server: ServerDefinition<P, R>,\n own: RemoteRpcClient<R>,\n visitor: Option.Option<RemoteRpcClient<R>>,\n): RemoteRpcClient<R> => {\n const note = (read: CachedRead) =>\n Effect.flatMap(Effect.service(PageReads), noted =>\n Effect.sync(() => Option.map(noted, add => add(read))),\n )\n return {\n ...own,\n FoldkitRemoteRead: batch => {\n const unshared = note(CachedRead.Private({ read: batchName(batch) }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(readPolicy(server, batch), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteRead(batch), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: readTags(batch, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n FoldkitRemoteQuery: request => {\n const unshared = note(CachedRead.Private({ read: `query ${request.query}` }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(queryPolicy(server, request), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteQuery(request), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: queryTags(server, request, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n }\n}\n","/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport {\n Cause,\n Deferred,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\n CacheStore,\n Diagnostics,\n LiveRequirement,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n Remote,\n RemoteJsonRequest,\n RemoteLiveError,\n RemoteMutationError,\n maxAgeSeconds,\n stableStringify,\n type CachePolicy,\n type Diagnostic,\n type RemoteClient,\n type NavigationRequest,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n type ScriptedRequest,\n} from 'foldkit-remote'\nimport { declaresTooLarge, discardBody, readJson, tooLargeAnswer } from './body.js'\nimport { cachedReadDiffers, serverDefect } from './diagnostics.js'\nimport {\n cacheKey,\n notingHandlers,\n queryPolicy,\n queryTags,\n readPolicy,\n readTags,\n writeTags,\n} from './edgeCache.js'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env, RP = never> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /**\n * Who this request is, from the request and the environment. Fails with\n * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.\n * What it needs (a session store, an auth service) comes from `layer`.\n * A resolver taking any `Request` fits; one typed for a navigation\n * (`NavigationRequest`) does not, since `/remote` writes.\n */\n readonly resolvePrincipal: (\n request: ScriptedRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /**\n * What the Sources and the resolver need, from the environment. Built per\n * request, so kept cheap, and closed when the answer is sent, or, for a\n * live stream, when the stream ends.\n */\n readonly layer: (env: Env) => Layer.Layer<R | RP>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /**\n * Headers every answer to `principal` carries, a live stream's included;\n * a refusal has no principal and carries none. Whom the request was\n * answered as, say, for a client to repeat (`foldkit-auth`'s\n * `AuthServer.answered`).\n */\n readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /**\n * Asks `resolvePrincipal` again, of the same request, every `every` while a\n * live stream is open. A refusal ends the stream with `Unauthenticated`,\n * which the client reads as a lost session; a principal whose `key`\n * differs from the one the stream opened with (`Policy.keyOf`, as\n * `liveHub`'s `key`) ends it as a live error, which the client opens again\n * after, as the new principal; without `key` only a refusal ends it.\n * Without `revalidate` a stream serves the principal it opened with until\n * it closes, a revoked session included.\n * `every` must be longer than zero: each pass asks the session store.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: P) => unknown) | undefined\n }\n | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /**\n * Where this request's diagnostics go, with the request: each failure\n * answered \"Internal error\" or ending a live stream (a `ServerDefect`: a\n * broken layer or resolver, a handler's defect), whose cause the caller is\n * never told, and what the handlers report. The reporter in the Effect\n * context (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n /** A read batch may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many levels; default 8. */\n readonly maxDepth?: number | undefined\n /**\n * A request body may not be larger than this many bytes; default 1 MiB. A\n * larger one is a 413 with Remote's `tooLarge` answer, refused before it is\n * decoded: by its `content-length` before the principal is resolved, or\n * once the bytes read pass the limit. Give the client the same number\n * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.\n */\n readonly maxBodyBytes?: number | undefined\n /**\n * Keeps public reads in `store` (#428). A read or query is public where\n * none of the sources it passes through has a rule about who asks\n * (`authorize`, `filter`, `visible`, a member per viewer) and each declares\n * how long it stays fresh (`EdgeCache.of` on its Entity, `cache` on its\n * Query). A public read is answered as `visitor`, whoever asks, so one\n * answer is right for everyone, and kept for the shortest `maxAge` it\n * reaches; it says `cache-control: public, max-age=…`. Every other answer\n * says `private, no-store`. A write answered here purges the kept reads\n * holding a row it names, and every list of that row's entity.\n *\n * `store` is a `CacheStore`, which serves nothing past its `maxAge`: an\n * answer carries no age, so one kept longer would read as fresh. A\n * `PageCacheStore` (`CacheStore.kv` with `keep`) is refused.\n *\n * `visitor` is the principal of someone not signed in: refused when the\n * server's `viewer` names a row for it. With `check`, for development and\n * tests, each public read is also answered as who asks, and a difference\n * is reported (`CachedReadDiffers`) and answered with the asker's own.\n */\n readonly cache?:\n | {\n readonly store: CacheStore\n readonly visitor: P\n readonly check?: boolean | undefined\n }\n | undefined\n}\n\n/** A read or query a cache may keep: how long, and the tags of its answer. */\ninterface Shareable {\n readonly policy: CachePolicy\n readonly tagsOf: (result: unknown) => ReadonlyArray<string>\n}\n\nconst decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest)\nconst decodeBatch = Schema.decodeUnknownOption(ReadBatch)\nconst decodeQuery = Schema.decodeUnknownOption(QueryRequest)\nconst decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult)\nconst decodeQueryResult = Schema.decodeUnknownOption(QueryResult)\n\n/** `body`, when it is a read or query every source of which is public. */\nconst shareableOf = <P, R>(\n server: ServerDefinition<P, R>,\n body: unknown,\n): Option.Option<Shareable> =>\n Option.flatMap(decodeRequest(body), ({ operation, payload }) =>\n ({\n read: () =>\n Option.flatMap(decodeBatch(payload), batch =>\n Option.map(readPolicy(server, batch), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeReadResult(result), {\n onNone: () => [],\n onSome: read => readTags(batch, read),\n }),\n })),\n ),\n query: () =>\n Option.flatMap(decodeQuery(payload), request =>\n Option.map(queryPolicy(server, request), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeQueryResult(result), {\n onNone: () => [],\n onSome: page => queryTags(server, request, page),\n }),\n })),\n ),\n mutate: () => Option.none<Shareable>(),\n })[operation](),\n )\n\n/** An answer as anyone may be given it: its result without whom it was for. */\nconst unaddressedAnswer = (answer: RemoteJsonAnswer): RemoteJsonAnswer => {\n if (!('result' in answer) || typeof answer.result !== 'object' || answer.result === null)\n return answer\n const { principal: _, ...result } = answer.result as Readonly<Record<string, unknown>>\n return { result }\n}\n\n/** Whether `body` is a write: what it names, a cache purges. */\nconst isWrite = (body: unknown): boolean =>\n Option.exists(decodeRequest(body), request => request.operation === 'mutate')\n\n/** A visitor the server's `viewer` names a row for is someone: their reads are their own. */\nconst refuseSomeone = <P, R>(\n server: ServerDefinition<P, R>,\n cache: { readonly visitor: P } | undefined,\n): void => {\n if (\n cache !== undefined &&\n server.viewer !== undefined &&\n Option.isSome(server.viewer(cache.visitor))\n )\n throw new Error(\n 'foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it',\n )\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/**\n * A terminal stream failure, so the client fails with its message instead of\n * hanging; a refusal of who is asking says so, as a 401's body does.\n */\nconst errorFrame = (\n message: string,\n refusal: Partial<RemoteJsonAnswer> | { readonly refused: true } = {},\n): string => `event: error\\ndata: ${JSON.stringify({ message, ...refusal })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n): Stream.Stream<Uint8Array, never, R | RC> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n // The checks fail the stream, or stop with it.\n const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, {\n haltStrategy: 'left',\n }).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error => Stream.succeed(errorFrame(error.message)),\n // The client reads `refused` as asking again being refused again.\n RemoteLiveRefused: error => Stream.succeed(errorFrame(error.message, { refused: true })),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n Unauthenticated: error =>\n Stream.succeed(\n errorFrame(error.message, {\n unauthenticated: unauthenticatedAnswer(error).body.unauthenticated,\n }),\n ),\n }),\n // A defect says nothing of itself to the client, as a 500 does, and is\n // reported; an interruption is the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.fromEffect(\n Effect.as(Diagnostics.report(serverDefect(cause)), errorFrame('Internal error')),\n ),\n ),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing. Once the stream\n * runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n release: Effect.Effect<void>,\n headers: Readonly<Record<string, string>>,\n): Effect.Effect<Response, never, R | RC> =>\n Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(\n Effect.matchEffect({\n onFailure: () =>\n Effect.succeed(\n Response.json(\n { error: 'The live payload is not a requirement' },\n { status: 400, headers },\n ),\n ),\n onSuccess: requirement =>\n Effect.map(\n Stream.toReadableStreamEffect(\n liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release)),\n ),\n body =>\n new Response(body, {\n headers: {\n ...headers,\n 'content-type': 'text/event-stream',\n },\n }),\n ),\n }),\n )\n\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. Each request is one Effect, with `layer` built once for it:\n * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`\n * (a 401, its `reason` the only words the caller reads); then the body. A\n * body that is not JSON, or not a request, is a 400 that reaches no handler;\n * a handler's failure a 500 with its message; anything else this side\n * breaks, the resolver's defects and the layer included, a 500 that says\n * nothing of it. A live open is answered with the stream instead. Each\n * answer is one principal's, so every response says `cache-control:\n * no-store`, unless `headers` gives a `cache-control` of its own.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env, RP = never>(\n config: FetchConfig<P, R, Env, RP>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n refuseSomeone(config.server, config.cache)\n const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT\n if (\n config.revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)\n )\n throw new Error('serveFetch: revalidate.every must be longer than zero')\n // Every request answered here is a `ScriptedRequest`: the brand is only what keeps a navigation's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */\n const reportingFor =\n (request: Request) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n const { diagnostics } = config\n return diagnostics === undefined\n ? effect\n : Effect.provideService(effect, Diagnostics.Reporter, diagnostic =>\n diagnostics(diagnostic, request),\n )\n }\n /** The live stream's principal, asked again of its request while it runs. */\n const revalidation = (\n request: Request,\n env: Env,\n opened: P,\n ): Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RP> => {\n const { revalidate } = config\n if (revalidate === undefined) return Stream.empty\n return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(\n Stream.mapEffect(() => resolvePrincipal(request, env)),\n Stream.mapEffect(now =>\n revalidate.key === undefined || revalidate.key(opened) === revalidate.key(now)\n ? Effect.void\n : Effect.fail(\n new RemoteLiveError({ message: 'Who is asking changed: open the stream again' }),\n ),\n ),\n Stream.drain,\n )\n }\n /**\n * A public read: the visitor's answer, from the store or answered and kept.\n * Under `check`, also the asker's own, which is given instead where they differ.\n */\n const answerShared = (\n request: Request,\n body: unknown,\n cache: NonNullable<FetchConfig<P, R, Env, RP>['cache']>,\n shareable: Shareable,\n own: RemoteRpcClient<R>,\n headers: Readonly<Record<string, string>>,\n ): Effect.Effect<Response, never, R> =>\n Effect.gen(function* () {\n const asked = stableStringify(body)\n const key = yield* cacheKey(request.url, 'remote', asked)\n const kept = yield* cache.store.match(key)\n let text: string\n if (Option.isSome(kept)) {\n text = kept.value\n } else {\n const visitor = RemoteServer.handlers(config.server, cache.visitor, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n const answered = yield* RemoteServer.answer(visitor, body)\n // A refusal or a failure is nobody's to keep.\n if (answered.status !== 200) {\n return Response.json(answered.body, { status: answered.status, headers })\n }\n text = JSON.stringify(unaddressedAnswer(answered.body))\n yield* cache.store.put(key, text, {\n maxAge: shareable.policy.maxAge,\n tags: shareable.tagsOf('result' in answered.body ? answered.body.result : {}),\n })\n }\n if (cache.check === true) {\n const mine = yield* RemoteServer.answer(own, body)\n if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {\n yield* Diagnostics.report(cachedReadDiffers(asked))\n return Response.json(mine.body, { status: mine.status, headers })\n }\n }\n return new Response(text, {\n headers: {\n 'content-type': 'application/json',\n 'cache-control': `public, max-age=${maxAgeSeconds(shareable.policy)}`,\n ...headers,\n },\n })\n })\n /** `live` is whether the response streams, and so owns `scope` until it ends. */\n const respond = (\n request: Request,\n env: Env,\n scope: Scope.Closeable,\n ): Effect.Effect<{ readonly response: Response; readonly live: boolean }, never, R | RP> =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal(request, env)\n const headers = config.headers?.(principal) ?? {}\n const body = yield* Effect.result(readJson(request, maxBodyBytes))\n if (Result.isFailure(body)) {\n const { status, answer } = body.failure\n return { response: Response.json(answer, { status, headers }), live: false }\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body.success)) {\n const response = yield* liveResponse(\n handlers,\n body.success.payload,\n heartbeat,\n revalidation(request, env, principal),\n Scope.close(scope, Exit.void),\n headers,\n )\n // A 400 for a payload no stream speaks has no stream to close it.\n return { response, live: response.status === 200 }\n }\n const { cache } = config\n const shareable =\n cache === undefined ? Option.none<Shareable>() : shareableOf(config.server, body.success)\n if (cache !== undefined && Option.isSome(shareable)) {\n const response = yield* answerShared(\n request,\n body.success,\n cache,\n shareable.value,\n handlers,\n headers,\n )\n return { response, live: false }\n }\n const answered = yield* RemoteServer.answer(handlers, body.success)\n if (cache !== undefined && answered.status === 200 && isWrite(body.success)) {\n yield* cache.store.purge(writeTags('result' in answered.body ? answered.body.result : {}))\n }\n return {\n response: Response.json(answered.body, { status: answered.status, headers }),\n live: false,\n }\n }).pipe(\n Effect.catchTag('Unauthenticated', refusal => {\n const { status, body } = unauthenticatedAnswer(refusal)\n return Effect.succeed({ response: Response.json(body, { status }), live: false })\n }),\n )\n const served = async (request: Request, env: Env): Promise<Response> => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n // Refused on what it says of itself: no layer built, no principal asked, nothing read.\n if (declaresTooLarge(request, maxBodyBytes)) {\n return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 })\n }\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n // Not Effect.provide(layer), which closes it when `respond` returns,\n // before a live stream has served a frame: the stream's re-reads and\n // revalidation would run on released resources.\n const scope = yield* Scope.make()\n const answered = yield* Layer.buildWithScope(config.layer(env), scope).pipe(\n Effect.flatMap(context => Effect.provide(respond(request, env, scope), context)),\n Effect.onExit(exit =>\n Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit),\n ),\n )\n return answered.response\n }).pipe(reportingFor(request)),\n )\n if (Exit.isSuccess(exit)) return exit.value\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what; the diagnostics learn what. `answer`\n // already maps its own failures and defects to 400/500 answers.\n await Effect.runPromise(\n Diagnostics.report(serverDefect(exit.cause)).pipe(reportingFor(request)),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Every answer but a public read's is read as one principal: no cache may\n // keep it for another. A `cache-control` of the application's own (`headers`) stands.\n return async (request, env) => {\n const response = await served(request, env)\n await discardBody(request, maxBodyBytes)\n if (!response.headers.has('cache-control')) {\n response.headers.set('cache-control', 'private, no-store')\n }\n return response\n }\n}\n\n/**\n * The cache's checker, for a test: serves each request twice through\n * `serveFetch` with `cache.check` and a store in memory, so every public read\n * is answered both as the visitor (kept, then from the store) and as whoever\n * the request resolves to. Rejects naming each read whose answers differ, and\n * when no read was public, which would check nothing. Give requests from at\n * least two principals, a visitor's and someone's; each is a function, since\n * a body is read once.\n */\nexport const checkCache = async <P, R, Env, RP = never>(\n config: Omit<FetchConfig<P, R, Env, RP>, 'cache' | 'diagnostics'> & {\n readonly cache: { readonly visitor: P }\n },\n requests: ReadonlyArray<() => Request>,\n env: Env,\n): Promise<void> => {\n const store = CacheStore.memory()\n const differs: Array<string> = []\n const serve = serveFetch({\n ...config,\n cache: { ...config.cache, store, check: true },\n diagnostics: diagnostic =>\n Effect.sync(() => {\n // tag-check: open -- a Diagnostic's tag is any package's; this one is ours.\n if (diagnostic._tag === 'CachedReadDiffers') differs.push(diagnostic.message)\n }),\n })\n for (const _round of [1, 2]) {\n for (const make of requests) await serve(make(), env)\n }\n if (differs.length > 0) throw new Error(differs.join('\\n'))\n if (store.size() === 0) {\n throw new Error('checkCache: no request was a public read, so nothing was checked')\n }\n}\n\n/**\n * What `pageReader` reads of a `serveFetch` config: the server, its Sources'\n * layer, its limits, and the cache's `visitor`.\n */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'\n> & {\n /**\n * Who a page request is. A resolver taking any `Request` fits; one typed\n * for a script's request (`ScriptedRequest`) does not, since a navigation\n * carries no header a script adds and that resolver would refuse every\n * signed-in reader.\n */\n readonly resolvePrincipal: (\n request: NavigationRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n}\n\n/**\n * The reader a page render reads through, in the same process: the request's\n * `RemoteClient`, answered by the server's own handlers with no HTTP between\n * them. Give it `serveFetch`'s config with the resolver a page's request\n * needs: a page `GET` is a navigation, which carries no header a script adds\n * (`AuthServer.resolver({ …, requests: 'navigation' })`).\n *\n * The principal is resolved, and `layer` built, when the reader is provided,\n * and `layer` closes when the Effect it was provided to ends, so provide it to\n * the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A\n * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only\n * reads: a mutation fails with `RemoteMutationError` and a live open with\n * `RemoteLiveError`, since a navigation can be started from another site.\n *\n * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):\n * with `cache`, one proved public as `serveFetch` proves it is answered as\n * `cache.visitor` and noted public; every other read, and every read without\n * `cache`, is noted private, which keeps the page from being cached.\n */\nexport const pageReader = <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => {\n refuseSomeone(config.server, config.cache)\n const limits = { maxIdsPerEntity: config.maxIdsPerEntity, maxDepth: config.maxDepth }\n const visitor = Option.map(Option.fromUndefinedOr(config.cache), cache =>\n RemoteServer.handlers(config.server, cache.visitor, limits),\n )\n // Every request read for is a page's: the brand is only what keeps a script's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n return (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(resolvePrincipal(request, env), principal => {\n const handlers = notingHandlers(\n config.server,\n RemoteServer.handlers(config.server, principal, limits),\n visitor,\n )\n return Remote.clientLayer<R>({\n ...handlers,\n FoldkitRemoteMutate: () =>\n Effect.fail(\n new RemoteMutationError({ message: 'A page render reads; it does not write' }),\n ),\n FoldkitRemoteLive: () =>\n Stream.fail(new RemoteLiveError({ message: 'A page render keeps no live stream' })),\n })\n }),\n ).pipe(Layer.provide(config.layer(env)))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAsB,WAC1B,WAAW,KAAA,KACX,OAAO,cAAc,KAAA,KACrB,OAAO,WAAW,KAAA,KAClB,OAAO,YAAY,KAAA,MAClB,OAAO,aAAa,CAAC,EAAA,CAAG,SAAS,IAC9B,OAAO,KAAK,IACZ,OAAO,gBAAgB,OAAO,KAAK;;AAGzC,MAAM,QAAQ,GAA+B,MAC3C,OAAO,QAAQ,IAAG,SAAQ,OAAO,IAAI,IAAG,UAAS,cAAc,MAAM,KAAK,CAAC,CAAC;;AAG9E,MAAM,eACJ,QACA,UAEA,OAAO,OAAO,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,QAClC,QAAQ,aAAa,KAAK,QAAQ,YAAY,QAAQ,QAAQ,CAAC,GAChE,aAAa,OAAO,SAAS,IAAI,MAAM,MAAM,CAAC,CAChD;;AAGF,MAAa,cACX,QACA,UAEA,MAAM,SAAS,WAAW,IACtB,OAAO,KAAK,IACZ,MAAM,SAAS,KAAI,YAAW,YAAY,QAAQ,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI;;AAG7E,MAAa,eACX,QACA,YAC+B;CAC/B,MAA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