Remote / foldkit-remote-server

Over fetch (Workers)

serveFetch from foldkit-remote-server/fetch is that route as a value: a (request: Request, env: Env) => Promise<Response> for a Worker's fetch, or any other runtime that speaks Request/Response. Each request is one Effect: layer is built from the environment, then resolvePrincipal says who is asking, then the request is answered as them. The resolver may need what layer provides (a session store, an auth service):

ts
import { serveFetch } from 'foldkit-remote-server/fetch'

// `server` is your RemoteServer.make; `databaseLayer` and `drizzle` provide what its Sources need.
export default {
  fetch: serveFetch({
    server,
    resolvePrincipal: request =>
      Effect.succeed({ isAdmin: request.headers.get('x-role') === 'admin' }),
    layer: (env: Env) => databaseLayer(drizzle(env.DB)),
  }),
}

Only POSTs to path (default /remote) are answered; anything else is a 404. A body larger than maxBodyBytes (default 1 MiB) is a 413 with { error, tooLarge: { limit } }: one whose content-length says so before the layer is built or the principal resolved, any other once the bytes read pass the limit, its stream cancelled there. Give the client the same number (Remote.clientLayer(Remote.http('/remote'), { maxBodyBytes })) and it cuts its reads to fit; Remote.http reads a 413 as the call's own error, so a durable write is not resent. A body that is not UTF-8 JSON, or not a request, is a 400 that reaches no handler; a failure on this side a 500 that says Internal error and the incident its cause was reported under (When the server fails). Every response, refusals and errors included, says cache-control: private, no-store unless headers gives a cache-control of its own: each answer is one principal's rows (and may), so no shared cache may keep one. The one exception is a read the server proves public, with cache (below).

A resolver refuses the caller by failing with RemoteServer.unauthenticated(reason?): a 401 whose body is { error, unauthenticated: { reason? } }, as answer's 403 carries forbidden, and whose reason is the only thing the caller learns. Anything else this side breaks, the resolver's defects and the layer included, is a 500 that says nothing of it but its incident. A visitor is not a refusal: resolve one to the principal your Sources treat as nobody, and refuse only a credential that was sent and no longer holds.

headers: principal => ({ … }) adds headers to every answer to that principal, a live stream's included; a refusal answered no one and carries none. foldkit-auth's AuthServer.answered uses it to say whom each answer was for.

revalidate: { every, key? } asks resolvePrincipal again, of the same request, every every while a live stream is open. A refusal ends the stream with Unauthenticated; a principal whose key differs from the one it opened with ends it as a live error, which the client opens again after, as the new principal. key is who a principal is, as liveHub's key: with guards, key: Policy.keyOf. Without revalidate a stream serves the principal it opened with, a revoked session included, until it closes.

A body that opens live ({ operation: 'live', payload }) is answered with the stream as text/event-stream: one data: frame per LiveChange, then a terminal event: error frame carrying the failure's message when the stream fails rather than ends. A payload no live stream speaks is a 400 that subscribes to nothing. httpWithLive (foldkit-remote/live) is the other end; a client that disconnects interrupts the subscription, as closing the RPC stream would.

The stream moves on its own even when nothing changes: a : ping comment opens it, and another follows every liveHeartbeat (default 15 seconds), so proxies and worker runtimes do not drop an idle connection. The heartbeat stops with the events it serves, so a stream with nothing to serve still ends.

live takes a hub whose changed/deleted signals reach these streams. What calls it must be able to wake the subscriber's fiber: in a worker, one request cannot wake another's stream, so a hub fed from a second request delivers nothing and ends the first stream. Poll the shared store from inside the subscriber's own request instead: foldkit-remote-drizzle's pollLive does, with a trigger-kept row log (rowChangeLog, rowLog) so a quiet tick reads no rows. A hub is right for a long-lived process that owns both sides.

A page's reads, in the same process: pageReader

A Worker that renders pages reads what each page shows before rendering it (Data.satisfy), as the reader who asked. pageReader is that reader, made from the same config serveFetch takes: the request's RemoteClient as a Layer, answered by the server's own handlers with no HTTP in between. The server, its layer and its limits are the ones /remote answers with.

ts
import { pageReader, serveFetch } from 'foldkit-remote-server/fetch'

const remote = { server, resolvePrincipal, layer: (env: Env) => databaseLayer(drizzle(env.DB)) }
const served = serveFetch(remote)
const reader = pageReader({ ...remote, resolvePrincipal: resolvePage })

export default {
  fetch: (request: Request, env: Env) =>
    new URL(request.url).pathname === '/remote'
      ? served(request, env)
      : pages.fetch(PageContext.attach(request, { reader: reader(request, env) })),
}

pages is the fetch handler Foldkit's build emits, and PageContext an SSR.requestContext that carries the reader to renderPage (foldkit-ssr).

The resolver is the page's own: a page GET is a navigation, which carries no header a script adds, so a resolver that asks for one (Yielded's CSRF header) refuses it. With foldkit-auth, give AuthServer.host's navigation. pageReader hands its resolver a NavigationRequest and serveFetch a ScriptedRequest (types from foldkit-remote, nothing at run time): a resolver typed for one does not fit the other, while one taking any Request, as here, fits both. When the reader is provided, the principal is resolved and layer built, and layer closes when that Effect ends, so provide it to the pre-read itself (Data.satisfy(…).pipe(Effect.provide(reader))). A refusal fails it with Unauthenticated, as a 401 would.

The reader only reads. A mutation fails with RemoteMutationError and a live open with RemoteLiveError: another site can start a navigation, so the principal it resolves must never write, and a render keeps no stream.

With cache, the reader answers each read it proves public as the visitor, and notes every read for the render (PageReads): public with its freshness and the rows it holds, or private, named by the rows or query it asked for (Price a, Price b, query Search). foldkit-ssr's SSR.entry keeps a page only when every read it made was public, and refuses a prerendered page naming the first read that was not.

Keeping public reads: cache

A read every visitor gets the same answer to costs the same work every time it is asked. With cache, serveFetch keeps public reads in a store and answers them without asking a Source:

  • Public read (no per-caller rule and freshness declared): answered as the visitor and kept in the store for maxAge.
  • Private read: answered as the authenticated caller with Cache-Control: private, no-store.
  • Write: purges every kept read holding a row it names and every list of that row's entity.

The domain declares how long a read stays fresh; it never says who may share it. An Entity says it with EdgeCache.of, a Query with cache:

ts
import { Effect, Layer, Schema } from 'effect'
import { Entity } from 'foldkit-entity'
import { CacheStore, EdgeCache, Query, REMOTE_PROTOCOL_VERSION } from 'foldkit-remote'
import { RemoteServer } from 'foldkit-remote-server'
import { checkCache, serveFetch } from 'foldkit-remote-server/fetch'

const Price = Entity.define(
  'Price',
  Schema.Struct({ id: Schema.String, amount: Schema.Number }),
).pipe(Entity.annotate(EdgeCache.of({ maxAge: '60 seconds' })))
const Cheap = Query.make('Cheap', { Input: {}, Result: Price, cache: { maxAge: '30 seconds' } })

const server = RemoteServer.make({
  entities: [
    RemoteServer.entity(Price, {
      read: ({ ids }) => Effect.succeed(ids.map(id => ({ id, values: { id, amount: 12 } }))),
    }),
  ],
})

const config = {
  server,
  resolvePrincipal: (request: Request) =>
    Effect.succeed({ userId: request.headers.get('x-user') ?? undefined }),
  layer: () => Layer.empty,
}
export const fetch = serveFetch({
  ...config,
  cache: { store: CacheStore.memory(), visitor: { userId: undefined } },
})

Whether a read is public is the server's to prove, from the Sources it passes through: a read or query is public only when no Source on its way (its Entity's, each relation's it reaches, a query's own and its select's) has an authorize, a filter, a visible rule or a member answered per viewer (Derived.exists), and each declares a freshness. Those rules are functions of the principal the server cannot read, so a Source with one is private even where its rule happens to read only the row: a guarded Entity (foldkit-guard), a Drizzle binding with visible, a memory backend with readable. Nothing is cached that the server could not prove.

A public read is answered as visitor, whoever asks: one answer, right for everyone, and never someone's own, even from a Source whose read looks at the principal. visitor must be no one: serveFetch refuses one the server's viewer names a row for. The answer names nobody it was for (no principal), says cache-control: public, max-age=… for the shortest freshness it reaches, and is kept by the SHA-256 of its body under /__foldkit/cache/remote/ on the request's origin. A refusal or a failure is not kept. Everything else (a write, a live stream, a read that is not public) says private, no-store.

A write answered here purges what its answer names: each row it wrote, deleted, moved in a list or read back (shown, carried lists), and every list of each of their entities, which a changed row can join or leave. A write that is not answered by this serveFetch (another server, a job, a database trigger) purges nothing: what it changed is served as it was kept until maxAge.

CacheStore.memory({ limit }) keeps answers in the process, for Node, a dev server and tests (1,000 by default, the oldest dropped first). CacheStore.workers(caches.default) keeps them in the Workers Cache API; which answers a tag names is known to the isolate that kept them, so a write purges what this isolate kept, and another isolate's or data centre's copy stays until its maxAge. Give pageReader the same config, and pages read through it are judged the same way (foldkit-ssr's cache).

CacheStore.kv(env.CACHE) keeps them in a Workers KV namespace: one copy for every isolate and data centre. KV's free plan allows 1,000 writes a day, so an answer is written only when it is asked for a second time; this isolate's memory counts the asking, since counting in KV would spend the write the count saves. What KV refuses or fails never fails a request: a failed read is a miss, a refused write (the day's writes spent, a key over 512 bytes) keeps nothing, and each is logged as a warning. KV keeps an entry a minute at least; the store serves it for its maxAge alone. Its purge, like the Workers store's, reaches what this isolate kept. Its keep option is for pages (foldkit-ssr): with it, kv returns a PageCacheStore, which serveFetch's cache.store refuses as a type error, since a read's answer carries no age and one served past its maxAge would read as fresh.

The checker answers each public read as two principals. cache.check answers it as who asks too, and where the two differ reports CachedReadDiffers and gives the asker their own: a development mode. checkCache(config, requests, env) is the same, for a test: it serves each request twice with check and a store in memory, and rejects a difference, or a set of requests with no public read, which would check nothing:

ts
const asking = (user?: string) => () =>
  new Request('https://shop.test/remote', {
    method: 'POST',
    headers: user === undefined ? {} : { 'x-user': user },
    body: JSON.stringify({
      operation: 'read',
      payload: {
        version: REMOTE_PROTOCOL_VERSION,
        requests: [{ entity: 'Price', id: 'a', fields: ['amount'] }],
      },
    }),
  })

export const checked = checkCache(
  { ...config, cache: { visitor: { userId: undefined } } },
  [asking(), asking('u1')],
  undefined,
)

Cheap is a Query a server registers with RemoteServer.query; its answer is kept for 30 seconds, the shorter of its own and Price's.