foldkit-remote-server 0.21.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/README.md +200 -27
- package/dist/fetch.d.mts +18 -4
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +41 -24
- package/dist/fetch.mjs.map +1 -1
- package/dist/{index-pMrHmWZt.d.mts → index-lJvjBBDL.d.mts} +37 -2
- package/dist/index-lJvjBBDL.d.mts.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{src-CHkHaItI.mjs → src-B1JAs_gH.mjs} +40 -4
- package/dist/src-B1JAs_gH.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/index-pMrHmWZt.d.mts.map +0 -1
- package/dist/src-CHkHaItI.mjs.map +0 -1
package/dist/fetch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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/**\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 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), note(CachedRead.Private())),\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(() => note(CachedRead.Private()))),\n },\n ),\n FoldkitRemoteQuery: request =>\n Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(queryPolicy(server, request), policy => ({ handlers, policy })),\n ),\n {\n onNone: () =>\n Effect.ensuring(own.FoldkitRemoteQuery(request), note(CachedRead.Private())),\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(() => note(CachedRead.Private()))),\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 RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n} from 'foldkit-remote'\nimport { declaresTooLarge, 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 */\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 * 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 * `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 /** `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 /**\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* 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 { 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 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' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'\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 return (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(config.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,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,yCAAyC,CAAC,CAC/E;GACF,yBACE,OAAO,KAAK,IAAI,gBAAgB,EAAE,SAAS,qCAAqC,CAAC,CAAC;EACtF,CAAC;CACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC;AAC3C"}
|
|
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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
|
256
256
|
/**
|
|
257
257
|
* What a writer's `delete` did. `Deleted`: the row is gone, with `cascaded`,
|
|
258
258
|
* the rows declared to go with it (`Relation.one(…, { onDelete: 'cascade' })`)
|
|
259
|
-
* that the principal may see
|
|
259
|
+
* that the principal may see, and `cleared`, those whose link to it was
|
|
260
|
+
* cleared (`onDelete: 'setNull'`), which stay. `Absent`: no row, so nothing to delete (a
|
|
260
261
|
* retry's case). `Moved`: the row is there at another revision, and stays.
|
|
262
|
+
* `Referenced`: rows still point at it through `relation` (`Like.post`),
|
|
263
|
+
* declared `onDelete: 'restrict'`, so it stays; which rows is not said.
|
|
261
264
|
*/
|
|
262
265
|
type DeleteOutcome = Data.TaggedEnum<{
|
|
263
266
|
Deleted: {
|
|
264
267
|
readonly cascaded: ReadonlyArray<CascadedRow>;
|
|
268
|
+
readonly cleared: ReadonlyArray<EntityRef>;
|
|
265
269
|
};
|
|
266
270
|
Absent: {};
|
|
267
271
|
Moved: {};
|
|
272
|
+
Referenced: {
|
|
273
|
+
readonly entity: string;
|
|
274
|
+
readonly relation: string;
|
|
275
|
+
};
|
|
268
276
|
}>;
|
|
269
277
|
declare const DeleteOutcome: Data.TaggedEnum.Constructor<{
|
|
270
278
|
readonly _tag: "Absent";
|
|
271
279
|
} | {
|
|
272
280
|
readonly _tag: "Deleted";
|
|
273
281
|
readonly cascaded: ReadonlyArray<CascadedRow>;
|
|
282
|
+
readonly cleared: ReadonlyArray<EntityRef>;
|
|
274
283
|
} | {
|
|
275
284
|
readonly _tag: "Moved";
|
|
285
|
+
} | {
|
|
286
|
+
readonly _tag: "Referenced";
|
|
287
|
+
readonly entity: string;
|
|
288
|
+
readonly relation: string;
|
|
276
289
|
}>;
|
|
277
290
|
interface EntityWriter<P, R = never> {
|
|
278
291
|
readonly entity: string;
|
|
@@ -346,6 +359,23 @@ interface EntityWriter<P, R = never> {
|
|
|
346
359
|
* cascades through a writer without it.
|
|
347
360
|
*/
|
|
348
361
|
readonly cascades?: true;
|
|
362
|
+
/**
|
|
363
|
+
* Whether `delete` refuses, in the statement that deletes, a row that rows
|
|
364
|
+
* point at through a relation declared `onDelete: 'restrict'`
|
|
365
|
+
* (`Entity.restricting`), answering `Referenced`. `RemoteServer.write`
|
|
366
|
+
* refuses a delete of an Entity something restricts through a writer
|
|
367
|
+
* without it.
|
|
368
|
+
*/
|
|
369
|
+
readonly restricts?: true;
|
|
370
|
+
/**
|
|
371
|
+
* Whether `delete` clears, in the transaction that deletes the row, the link
|
|
372
|
+
* of every row pointing at it through a relation declared `onDelete:
|
|
373
|
+
* 'setNull'` (`Entity.clearing`), answers the rows the principal may see as
|
|
374
|
+
* `cleared`, and holds them to the `clearing` requirements it is given,
|
|
375
|
+
* refusing the whole delete where one fails. `RemoteServer.write` refuses a
|
|
376
|
+
* delete of an Entity something clears through a writer without it.
|
|
377
|
+
*/
|
|
378
|
+
readonly clears?: true;
|
|
349
379
|
/**
|
|
350
380
|
* Why this writer cannot land `write`, each a sentence; none when it can.
|
|
351
381
|
* `RemoteServer.write` asks once, where the write is registered, for what
|
|
@@ -442,6 +472,11 @@ interface EntityWriter<P, R = never> {
|
|
|
442
472
|
* `cascades` is given them.
|
|
443
473
|
*/
|
|
444
474
|
readonly cascading?: ReadonlyArray<CascadeRequirement> | undefined;
|
|
475
|
+
/**
|
|
476
|
+
* What each row whose link the delete clears must hold, by Entity: its
|
|
477
|
+
* `Update` rules over the link. Only a writer with `clears` is given them.
|
|
478
|
+
*/
|
|
479
|
+
readonly clearing?: ReadonlyArray<CascadeRequirement> | undefined;
|
|
445
480
|
readonly principal: P;
|
|
446
481
|
}) => Effect.Effect<DeleteOutcome, RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet, R>;
|
|
447
482
|
/**
|
|
@@ -1032,4 +1067,4 @@ declare const RemoteServer: {
|
|
|
1032
1067
|
handlers: <P, R, I = never>(server: ServerDefinition<P, R>, principal: P | Context.Key<I, P>, options?: HandlerOptions<P, R>) => RemoteRpcClient<R | I>;
|
|
1033
1068
|
};
|
|
1034
1069
|
export { RemoteUnmet as A, RemoteServerDiagnostic as B, QueryPage as C, RemoteServer as D, RemoteInvalid as E, exprContext as F, assertSupported$1 as G, bodyLimit as H, AnswerUnread as I, evaluate$1 as K, CachedReadDiffers as L, ServerDefinition as M, WriteRequirement as N, RemoteServerError as O, WriteWhen as P, ClockSkewed as R, MutationSource as S, ReadPlan as T, QueryEvaluateError as U, ServerDefect as V, Row as W, MemoryRows as _, EntityRecord as a, MutationOutcome as b, EntityWriter as c, LiveQuery as d, LiveSource as f, MemoryReadable as g, MemoryConfig as h, DeleteOutcome as i, RowRequirement as j, RemoteTaken as k, HandlerOptions as l, MemoryBackend as m, CascadedRow as n, EntitySource as o, MemoryAnswering as p, supported as q, ConnectionChange as r, EntitySourceContext as s, CascadeRequirement as t, LiveHub as u, MemoryServed as v, QuerySource as w, MutationRefused as x, MemoryStore as y, PublishFailed as z };
|
|
1035
|
-
//# sourceMappingURL=index-
|
|
1070
|
+
//# sourceMappingURL=index-lJvjBBDL.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-lJvjBBDL.d.mts","names":[],"sources":["../src/body.ts","../src/diagnostics.ts","../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;cAmIa,YAAS,uBAEnB,GAAG,GAAC,UACO,OAAO,OAAO,mBAAmB,oBAAoB,GAAG,OACjE,OAAO,OACR,mBAAmB,oBACnB,GACA,IAAI,kBAAkB;;UC7HT,qBAAqB;WAC3B;WACA,OAAO,MAAM;;;;;;UAOP,qBAAqB;WAC3B;WACA;;WAEA;;;UAIM,sBAAsB;WAC5B;WACA;WACA,OAAO,MAAM;;;;;;;UAQP,oBAAoB;WAC1B;WACA;;WAEA;;WAEA;;WAEA;;;;;;;;UASM,0BAA0B;WAChC;;WAEA;;;KAIC,yBACR,eACA,eACA,gBACA,cACA;;;;cCmCS,0BAA0B;;;;;;;;;cAY1B,oBAAoB;;;;;;;;;;cAUpB,oBA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AAgB,IAAI"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as RemoteUnmet, B as RemoteServerDiagnostic, C as QueryPage, D as RemoteServer, E as RemoteInvalid, F as exprContext, G as assertSupported, H as bodyLimit, I as AnswerUnread, K as evaluate, L as CachedReadDiffers, M as ServerDefinition, N as WriteRequirement, O as RemoteServerError, P as WriteWhen, R as ClockSkewed, S as MutationSource, T as ReadPlan, U as QueryEvaluateError, V as ServerDefect, W as Row, _ as MemoryRows, a as EntityRecord, b as MutationOutcome, c as EntityWriter, d as LiveQuery, f as LiveSource, g as MemoryReadable, h as MemoryConfig, i as DeleteOutcome, j as RowRequirement, k as RemoteTaken, l as HandlerOptions, m as MemoryBackend, n as CascadedRow, o as EntitySource, p as MemoryAnswering, q as supported, r as ConnectionChange, s as EntitySourceContext, t as CascadeRequirement, u as LiveHub, v as MemoryServed, w as QuerySource, x as MutationRefused, y as MemoryStore, z as PublishFailed } from "./index-
|
|
1
|
+
import { A as RemoteUnmet, B as RemoteServerDiagnostic, C as QueryPage, D as RemoteServer, E as RemoteInvalid, F as exprContext, G as assertSupported, H as bodyLimit, I as AnswerUnread, K as evaluate, L as CachedReadDiffers, M as ServerDefinition, N as WriteRequirement, O as RemoteServerError, P as WriteWhen, R as ClockSkewed, S as MutationSource, T as ReadPlan, U as QueryEvaluateError, V as ServerDefect, W as Row, _ as MemoryRows, a as EntityRecord, b as MutationOutcome, c as EntityWriter, d as LiveQuery, f as LiveSource, g as MemoryReadable, h as MemoryConfig, i as DeleteOutcome, j as RowRequirement, k as RemoteTaken, l as HandlerOptions, m as MemoryBackend, n as CascadedRow, o as EntitySource, p as MemoryAnswering, q as supported, r as ConnectionChange, s as EntitySourceContext, t as CascadeRequirement, u as LiveHub, v as MemoryServed, w as QuerySource, x as MutationRefused, y as MemoryStore, z as PublishFailed } from "./index-lJvjBBDL.mjs";
|
|
2
2
|
export { type AnswerUnread, type CachedReadDiffers, CascadeRequirement, CascadedRow, type ClockSkewed, ConnectionChange, DeleteOutcome, EntityRecord, EntitySource, EntitySourceContext, EntityWriter, HandlerOptions, LiveHub, LiveQuery, LiveSource, MemoryAnswering, MemoryBackend, MemoryConfig, MemoryReadable, MemoryRows, MemoryServed, MemoryStore, MutationOutcome, MutationRefused, MutationSource, type PublishFailed, QueryEvaluateError, QueryPage, QuerySource, ReadPlan, RemoteInvalid, RemoteServer, type RemoteServerDiagnostic, RemoteServerError, RemoteTaken, RemoteUnmet, type Row, RowRequirement, type ServerDefect, ServerDefinition, WriteRequirement, WriteWhen, assertSupported, bodyLimit, evaluate, exprContext, supported };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as DeleteOutcome, n as MutationRefused,
|
|
1
|
+
export { t as DeleteOutcome, n as MutationRefused, h as QueryEvaluateError, r as RemoteInvalid, i as RemoteServer, a as RemoteServerError, o as RemoteTaken, s as RemoteUnmet, c as RowRequirement, g as assertSupported, u as bodyLimit, _ as evaluate, l as exprContext, v as supported } from "./src-B1JAs_gH.mjs";
|
|
@@ -78,6 +78,28 @@ const declaresTooLarge = (request, limit) => {
|
|
|
78
78
|
return Number.isFinite(length) && length > limit;
|
|
79
79
|
};
|
|
80
80
|
/**
|
|
81
|
+
* Consumes a body nobody read, before a refusal is answered: workerd drops the
|
|
82
|
+
* connection the next request shares when an answer leaves a body unread, and
|
|
83
|
+
* cancelling it is not enough. Read up to `limit` bytes and discarded, then
|
|
84
|
+
* cancelled, so a refusal never reads more than a request may carry.
|
|
85
|
+
*/
|
|
86
|
+
const discardBody = async (request, limit) => {
|
|
87
|
+
if (request.body === null || request.bodyUsed) return;
|
|
88
|
+
const reader = request.body.getReader();
|
|
89
|
+
let total = 0;
|
|
90
|
+
try {
|
|
91
|
+
for (;;) {
|
|
92
|
+
const { done, value } = await reader.read();
|
|
93
|
+
if (done) return;
|
|
94
|
+
total += value.byteLength;
|
|
95
|
+
if (total > limit) break;
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
await reader.cancel().catch(() => {});
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
81
103
|
* `request`'s body, at most `limit` bytes of it. Rejects with `BodyTooLarge`
|
|
82
104
|
* once more arrive, having cancelled the rest, or with the stream's own error.
|
|
83
105
|
*/
|
|
@@ -1211,15 +1233,21 @@ const RemoteServer = {
|
|
|
1211
1233
|
const pointers = pointersOf(write.input.entity);
|
|
1212
1234
|
const cascadePointers = /* @__PURE__ */ new Map();
|
|
1213
1235
|
if (kind.deletes) {
|
|
1236
|
+
const named = (entity) => Entity.restricting(entity).map(({ relation, owner }) => `${owner.name}.${relation.key}`).join(", ");
|
|
1214
1237
|
const reach = (entity) => {
|
|
1215
1238
|
for (const { owner } of Entity.cascading(entity)) {
|
|
1216
1239
|
if (cascadePointers.has(owner.name)) continue;
|
|
1240
|
+
if (Entity.clearing(owner).length > 0) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose cascade takes ${owner.name} rows, whose links ${Entity.clearing(owner).map(({ relation, owner: from }) => `${from.name}.${relation.key}`).join(", ")} clear (onDelete: 'setNull'); a cascade into such an Entity is not supported`);
|
|
1241
|
+
if (Entity.restricting(owner).length > 0) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose cascade takes ${owner.name} rows, which ${named(owner)} restricts (onDelete: 'restrict'); a cascade into a restricted Entity is not supported: restrict ${write.input.entity.name} instead, or cascade ${owner.name}'s pointers too`);
|
|
1217
1242
|
cascadePointers.set(owner.name, pointersOf(owner));
|
|
1218
1243
|
reach(owner);
|
|
1219
1244
|
}
|
|
1220
1245
|
};
|
|
1221
1246
|
reach(write.input.entity);
|
|
1222
1247
|
if (cascadePointers.size > 0 && writer.cascades !== true) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose rows take ${[...cascadePointers.keys()].join(", ")} with them (onDelete: 'cascade'), but its writer does not remove them (cascades)`);
|
|
1248
|
+
if (Entity.restricting(write.input.entity).length > 0 && writer.restricts !== true) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, which ${named(write.input.entity)} restricts (onDelete: 'restrict'), but its writer does not refuse a row they point at (restricts)`);
|
|
1249
|
+
const cleared = Entity.clearing(write.input.entity);
|
|
1250
|
+
if (cleared.length > 0 && writer.clears !== true) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose rows ${cleared.map(({ relation, owner }) => `${owner.name}.${relation.key}`).join(", ")} point at (onDelete: 'setNull'), but its writer does not clear them (clears)`);
|
|
1223
1251
|
}
|
|
1224
1252
|
/** What a removed row pointed at that its removal moves, as refs. */
|
|
1225
1253
|
const pointedBy = (row) => (cascadePointers.get(row.entity) ?? []).flatMap((key) => Option.match(Option.flatten(Option.fromUndefinedOr(row.links[key])), {
|
|
@@ -1397,8 +1425,16 @@ const RemoteServer = {
|
|
|
1397
1425
|
});
|
|
1398
1426
|
return yield* DeleteOutcome.$match(outcome, {
|
|
1399
1427
|
Moved: () => Effect.fail(conflict(bound)),
|
|
1428
|
+
Referenced: ({ entity, relation }) => Effect.fail(RemoteServer.refuse(mutation, Refusal.referenced.make({
|
|
1429
|
+
entity,
|
|
1430
|
+
relation
|
|
1431
|
+
}), `${bound.entity} ${bound.id} is still pointed at through ${entity}.${relation}`)),
|
|
1400
1432
|
Absent: () => Effect.succeed(gone([])),
|
|
1401
|
-
Deleted: ({ cascaded }) => Effect.succeed(naming(gone(cascaded), [
|
|
1433
|
+
Deleted: ({ cascaded, cleared }) => Effect.succeed(naming(gone(cascaded), [
|
|
1434
|
+
...before,
|
|
1435
|
+
...cascaded.flatMap(pointedBy),
|
|
1436
|
+
...cleared
|
|
1437
|
+
]))
|
|
1402
1438
|
});
|
|
1403
1439
|
})
|
|
1404
1440
|
}));
|
|
@@ -1647,7 +1683,7 @@ const RemoteServer = {
|
|
|
1647
1683
|
status: 500,
|
|
1648
1684
|
body: { error: error.message }
|
|
1649
1685
|
} : {
|
|
1650
|
-
status: Refusal.isTaken(error.refusal) ? 409 : 422,
|
|
1686
|
+
status: Refusal.isTaken(error.refusal) || Refusal.isReferenced(error.refusal) ? 409 : 422,
|
|
1651
1687
|
body: {
|
|
1652
1688
|
error: error.message,
|
|
1653
1689
|
refusal: error.refusal
|
|
@@ -1784,6 +1820,6 @@ const RemoteServer = {
|
|
|
1784
1820
|
};
|
|
1785
1821
|
}
|
|
1786
1822
|
};
|
|
1787
|
-
export {
|
|
1823
|
+
export { evaluate$1 as _, RemoteServerError as a, cachedReadDiffers as b, RowRequirement as c, declaresTooLarge as d, discardBody as f, assertSupported$1 as g, QueryEvaluateError as h, RemoteServer as i, exprContext as l, tooLargeAnswer as m, MutationRefused as n, RemoteTaken as o, readJson as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, supported as v, serverDefect as x, unauthenticatedAnswer as y };
|
|
1788
1824
|
|
|
1789
|
-
//# sourceMappingURL=src-
|
|
1825
|
+
//# sourceMappingURL=src-B1JAs_gH.mjs.map
|