Remote / foldkit-remote
Full walkthrough: one entity, one Surface
Six steps wire a project's name from a server to a screen, including update,
active subscriptions, and a client layer.
1. Declare an entity and what this screen needs of it
import { Schema } from 'effect'
import { Entity } from 'foldkit-entity'
const Project = Entity.define(
'Project',
Schema.Struct({
id: Schema.String,
name: Schema.String,
status: Schema.String,
}),
)
// A Selection is the exact server-owned shape this consumer needs.
const ProjectSummary = Entity.select(Project, {
id: true,
name: true,
})The entity comes from foldkit-entity, which declares a domain
without Remote in it, so the same declaration can serve the server's database
binding and your forms too. It is also what gives an entity
relations, derived members, and a
query body to point at. These declarations stay pure
values until a Subscription queries the server.
2. Give Remote a place in the Model, and route its Messages
import { defineMessageUnion } from 'foldkit/message'
import type * as Update from 'foldkit/update'
import { Remote, type RemoteClient } from 'foldkit-remote'
import { Surface } from 'foldkit-surface'
const Route = Schema.Union([
Schema.Struct({ _tag: Schema.Literal('home') }),
Schema.Struct({
_tag: Schema.Literal('project'),
projectId: Schema.String,
}),
])
const Model = Schema.Struct({
route: Route,
remote: Remote.Model,
})
type Model = typeof Model.Type
const Message = defineMessageUnion({
GotRemoteMessage: { message: Remote.Message },
})
type Message = typeof Message.Type
const App = Surface.application({
Model,
Message,
initial: {
route: { _tag: 'home' },
remote: Remote.initial,
},
update,
})
const Data = Remote.make({
model: App.model.remote,
entities: [Project],
})
// Remote under one variant of the union, the shape Foldkit gives a Submodel.
const foldData = Remote.fold(Data, message => Message.GotRemoteMessage({ message }))
function update(
model: Model,
message: Message,
): Update.Return<Model, Message, RemoteClient> {
return Message.match(message, {
// Remote owns the `remote` Submodel: everything it says goes through its reducer.
GotRemoteMessage: ({ message }) => foldData(model, message),
})
}Remote.Model lives inside the application Model as a Submodel, and Data
is the bound API for this domain: it knows where that Submodel lives and which
entities this application registered. update matches the union exhaustively;
Remote's own Messages arrive inside GotRemoteMessage and go straight to
Remote's reducer. (There is a shorter form for an update that only reduces;
see Routing Remote's Messages.)
3. Declare what the screen reads
const ProjectPage = App.surface('ProjectPage', {
params: { projectId: Schema.String },
model: ({ params }) => ({
// Pure Projection over Model plus a requirement for these fields; I/O runs in Subscriptions.
project: Data.get(ProjectSummary, params.projectId),
}),
})ProjectPage reads a RemoteData<{ id: string; name: string }> from the Model.
If those fields are absent, the Projection records the requirement and returns
Initial or Loading; the active Subscription decides when to fetch.
4. Let the active screen drive the fetching
import { Option } from 'effect'
import * as Subscription from 'foldkit/subscription'
const subscriptions = Subscription.make<Model, Message, RemoteClient>()(() =>
foldData.subscriptions({
project: Surface.at(ProjectPage, model =>
model.route._tag === 'project'
? Option.some({ projectId: model.route.projectId })
: Option.none(),
),
}),
)Surface.at makes activation a fact of the Model. When the route activates the
page, Remote sees its requirements, diffs them against the cache, and fetches
only what is missing. When the page is inactive, it creates no read work. This
is the one step that causes I/O, and it does so only while the screen is on.
A read that is not a Surface's, such as the record a detail pane shows, is made
active with Data.active: its function of the Model returns the read, or none
while there is nothing to read.
const detail = Data.active('ProjectDetail', model =>
model.route._tag === 'project'
? Option.some(Data.get(Entity.select(Project, { name: true }), model.route.projectId))
: Option.none(),
)
foldData.subscriptions({ detail })Its projectionOf(model) gives back that read, with its value's type. It
belongs to the domain's application and sends no Messages. A domain bound
to a raw optic (ModelRef.fromOptic) names no application, so Data.active
throws for one rather than guess.
5. Provide a client
The Subscription needs a RemoteClient. Before there is a server, a backend
held in memory answers through the same handlers a real one uses:
import { RemoteServer } from 'foldkit-remote-server'
const clientLayer = RemoteServer.memory({
domain: Data,
rows: { Project: [{ id: 'p1', name: 'Apollo', status: 'active' }] },
}).layerWith a server, hand Remote the Effect RPC client for RemoteRpc; the
server guide supplies the other side:
import { Effect, Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { RpcClient, RpcSerialization } from 'effect/rpc'
import { RemoteRpc } from 'foldkit-remote'
const overRpc = Layer.unwrap(
Effect.map(RpcClient.make(RemoteRpc), rpcClient => Remote.clientLayer(rpcClient)),
).pipe(
Layer.provide(Remote.rpcProtocolHttp('/rpc')),
Layer.provide([RpcSerialization.layerJson, FetchHttpClient.layer]),
)Remote.rpcProtocolHttp(url) is Effect's RpcClient.layerProtocolHttp({ url
}), except that a response whose status is not 2xx fails the call with its
status. Effect's own reads such a body as RPC frames and loses the status, so
a request the server refused (session middleware's 401 or 403, bodyLimit's
413) would read as unreachable, and a durable write would be sent again for
good.
Or, with no Effect RPC on the server, plain JSON over HTTP: each call a POST
of { operation, payload }, answered { result } or { error }.
RemoteServer.answer is the
other end:
const overHttp = Remote.clientLayer(
Remote.http('/remote', { headers: () => ({ 'x-session': 'the session token' }) }),
)Each is a Layer the runtime provides to subscriptions and Commands while
keeping transport outside Remote. See
RemoteServer.memory
for what the in-memory one supports, and
Clients and transports for the others (a worker or
a MessagePort, live data over HTTP), what a refused or unreachable call
does, and testing a server over HTTP.
6. Watch it arrive
The loop flows from ProjectPage's Projection to Data.subscriptions (which
plans missing fields), through RemoteClient to the server and back as a
Remote Message, and through Data.reduce into Remote.Model, where
ProjectPage reads Ready(...).
The walkthrough starts on the home route, so no project read runs yet. When
your route update activates { _tag: 'project', projectId: 'p1' } and the
runtime installs subscriptions, the page moves from Initial to Loading
during the first request and then to Ready once the result reduces. If it
stays Initial, see Why is it still Initial?.