Capabilities and callbacks
Typed capabilities#
A capability is a typed RPC client that can itself be sent as an RPC value. It combines two ideas:
a surface of methods, defined by an ordinary Effect
RpcGroup; andauthority to call one particular implementation of those methods.
For example, a session capability can remember an authenticated user, and a document capability can remember which document was opened. Their methods then need only the arguments relevant to each operation.
The receiver gets a typed Effect RPC client. Functions and closures remain on the side that created them.
Calling a capability method sends its opaque handle, method name, and schema-encoded payload back to its owner. The owner executes the handler with the captured Effect context.
Define a capability#
Define a capability from another ordinary RpcGroup:
import * as Capability from "effect-rpc-pipeline/Capability"
const SessionRpcs = RpcGroup.make(
Rpc.make("currentUser", { success: User }),
Rpc.make("listTodos", { success: Schema.Array(Todo) }),
Rpc.make("createTodo", {
payload: { title: Schema.String },
success: Todo
})
)
const Session = Capability.make("app/Session", SessionRpcs)
const OpenSession = Rpc.make("openSession", { success: Session.schema })
const AppRpcs = RpcGroup.make(OpenSession).middleware(Authenticated)Implement the methods#
The server returns an implementation with fromHandlers:
const AppHandlers = AppRpcs.of({
openSession: () => Effect.gen(function*() {
const user = yield* CurrentUser
return yield* Session.fromHandlers({
currentUser: () => CurrentUser,
listTodos: () => Effect.flatMap(CurrentUser, (user) => Todos.forUser(user.id)),
createTodo: ({ title }) => Effect.flatMap(
CurrentUser,
(user) => Todos.create({ ownerId: user.id, title })
)
}).pipe(Effect.provideService(CurrentUser, user))
})
})Session.fromHandlers accepts the same handlers, middleware, errors, and services as RpcGroup.toHandlers. It captures the Effect context where it is created.
Here each session captures its own CurrentUser. Later method calls use that user without requiring a token or user ID in each payload.
Use the session#
The client can authenticate once when opening the capability, then call its methods:
const session = yield* rpc.openSession().pipe(
RpcClient.withHeaders({ authorization: `Bearer ${token}` })
)
const result = yield* Effect.gen(function*() {
const todo = yield* session.createTodo({ title: "Learn Effect" })
const todos = yield* session.listTodos()
return { todo, todos }
})Authentication runs before the session is created. The session grants access to its declared methods for the captured user. The raw JWT is not stored in the handle or repeated in method payloads.
Expose only the methods needed#
A capability can offer a smaller API than the whole application. This editor exposes only two methods for one todo:
const TodoEditorRpcs = RpcGroup.make(
Rpc.make("rename", {
payload: { title: Schema.String },
success: Todo
}),
Rpc.make("complete", { success: Todo })
)
const TodoEditor = Capability.make("todos/Editor", TodoEditorRpcs)
const openTodo = Rpc.make("openTodo", {
payload: { id: Schema.String },
success: TodoEditor.schema,
error: TodoNotFound
})An openTodo handler can capture the validated todo ID and current user when it creates the editor. Its rename method then needs only the new title, and a caller holding the editor cannot list other users' todos or invoke unrelated application methods.
Connection lifetime and pipelining#
Over WebSocket, the returned capability can be retained and called in later requests:
const session = yield* rpc.openSession().pipe(
RpcClient.withHeaders({ authorization: `Bearer ${token}` })
)
const user = yield* session.currentUser()
const todos = yield* session.listTodos()
yield* Capability.release(session)The capability is scoped to its connection and is revoked automatically when that connection closes. Capability.release lets the client release it earlier.
Over HTTP, use the capability inside the pipeline that creates it:
const session = rpc.openSession()
const account = yield* Pipeline.all({
user: session.currentUser(),
todos: session.listTodos()
}).pipe(RpcClient.withHeaders({ authorization: `Bearer ${token}` }))An HTTP capability cannot be retained for another request.
This gives capabilities two useful lifetimes:
| Transport | Lifetime | Typical use |
|---|---|---|
| WebSocket | Until release or disconnect | Delegated sessions, resource handles, and callbacks |
| HTTP | The pipeline that creates the capability | Authenticate and perform dependent work in one round trip |
In the HTTP example, the server authenticates first, then runs the independent session calls concurrently. Only the selected account data comes back; the intermediate capability handle stays on the server.
Client callbacks#
Capabilities are bidirectional over WebSocket. A client can implement a capability, include it in a request, and let the server call it. This provides typed callbacks without callback URLs, a second protocol, polling, or function serialization.
Ask for checkout approval#
The server can ask the client to approve a checkout total and wait for its answer:
const ApprovalRpcs = RpcGroup.make(
Rpc.make("approve", {
payload: { total: Schema.Number },
success: Schema.Boolean,
error: ApprovalUnavailable
})
)
const Approval = Capability.make("checkout/Approval", ApprovalRpcs)
const CheckoutRpcs = RpcGroup.make(
Rpc.make("checkout", {
payload: {
cartId: Schema.String,
approval: Approval.schema
},
success: Receipt,
error: Schema.Union([
CheckoutFailed,
ApprovalUnavailable,
Capability.CapabilityUnavailable,
Capability.CapabilityTransportError
])
})
)The server uses the supplied capability like any other typed Effect RPC client:
const CheckoutHandlers = CheckoutRpcs.of({
checkout: ({ cartId, approval }) => Effect.gen(function*() {
const cart = yield* Carts.get(cartId)
const approved = yield* approval.approve({ total: cart.total })
if (!approved) {
return yield* Effect.fail(new CheckoutFailed({ reason: "declined" }))
}
return yield* Orders.complete(cart)
})
})const approval = yield* Approval.fromHandlers({
approve: ({ total }) => Dialog.confirm(`Approve $${total}?`)
})
const receipt = yield* rpc.checkout({ cartId, approval })The server receives approval as a typed RPC client and calls yield* approval.approve(...). The browser retains the dialog implementation and UI services; only an opaque reference and schema-encoded calls cross the connection.
Report progress and ask questions#
A longer workflow can expose several callbacks. This file import reports progress and asks before overwriting a file:
const ImportUiRpcs = RpcGroup.make(
Rpc.make("progress", {
payload: {
completed: Schema.Number,
total: Schema.Number,
message: Schema.String
},
success: Schema.Void
}),
Rpc.make("confirmOverwrite", {
payload: { path: Schema.String },
success: Schema.Boolean,
error: DialogUnavailable
})
)
const ImportUi = Capability.make("imports/Ui", ImportUiRpcs)
const ImportRpcs = RpcGroup.make(
Rpc.make("importArchive", {
payload: {
archiveId: Schema.String,
ui: ImportUi.schema
},
success: ImportSummary,
error: Schema.Union([
ImportFailed,
DialogUnavailable,
Capability.CapabilityUnavailable,
Capability.CapabilityTransportError
])
})
)The server can express the workflow directly with Effect.gen:
const ImportHandlers = ImportRpcs.of({
importArchive: ({ archiveId, ui }) => Effect.gen(function*() {
const entries = yield* Archives.entries(archiveId)
for (const [index, entry] of entries.entries()) {
if (yield* Files.exists(entry.path)) {
const overwrite = yield* ui.confirmOverwrite({ path: entry.path })
if (!overwrite) continue
}
yield* Files.write(entry)
yield* ui.progress({
completed: index + 1,
total: entries.length,
message: `Imported ${entry.path}`
})
}
return new ImportSummary({ imported: entries.length })
})
})The client supplies behavior using the same Effect-native handler API:
const ui = yield* ImportUi.fromHandlers({
progress: ({ completed, total, message }) =>
ImportScreen.update({ completed, total, message }),
confirmOverwrite: ({ path }) =>
Dialog.confirm(`Replace ${path}?`)
})
const summary = yield* rpc.importArchive({ archiveId, ui })The server waits for a typed response from the client at each interaction. The workflow remains an Effect, with its usual errors, interruption, and connection scope.
Other useful callback capabilities include:
requesting a signature while a private key stays on the client;
resolving an application-specific conflict during synchronization;
asking a worker for credentials only when an upstream service challenges; and
supplying a test implementation that deterministically drives an interactive server workflow.
Calls can run concurrently in either direction, and typed failures travel back to the caller. Interrupting the server’s wait interrupts the active client handler.
Client handlers can use captured Effect services, just like server capability handlers.
Choose streams or callbacks#
Use a stream to publish a sequence of values. Use a callback capability when the server needs to invoke a named client operation and receive its response, or when several related operations belong together.
Capability methods themselves cannot be streaming RPCs.
Operational boundaries#
Keep these rules in mind when exposing capabilities:
| Event | Behavior |
|---|---|
| Release a handle | Later calls fail with CapabilityUnavailable |
| Disconnect or reverse-call transport failure | Calls fail with CapabilityTransportError |
| Reconnect | The application must authenticate, acquire handles, and subscribe again |
| Return a handle as an HTTP result | Rejected; HTTP capabilities must stay inside their creating graph |
| Call a remote peer inside a SQL transaction | Rejected; finish the transaction before the interactive callback |
Handles are random, opaque authority values bound to their connection, duplex session, owner, and exact capability definition.
Payloads, results, and declared failures are schema-validated in both directions. Malformed peer values fail with CapabilityTransportError. Reconnection does not replay mutations.