@procedures/peer

Transport-agnostic peer for bidirectional RPC - exposes procedures and generates manifests
Overview
client-server is a comprehensive server infrastructure package that enables transport-agnostic bidirectional RPC communication. It provides a peer-to-peer architecture where each peer can both expose procedures and call procedures on remote peers. The package supports multiple transport layers (HTTP, WebSocket, local) and includes automatic procedure discovery and manifest generation.
Key Features
- Transport-Agnostic: Supports HTTP, WebSocket, and in-process transports
- Bidirectional RPC: Peers can both expose and call procedures
- Automatic Discovery: Peers exchange procedure manifests on connection
- Manifest Generation: Generate TypeScript and JSON manifests from registered procedures
- Connection Management: Track and manage multiple peer connections
- One procedures host:
createProcedureHost() gives the parts of a service of @mark1russell7/service (CLI-7). It has no framework: the listener is the httpTransport of @mark1russell7/service/http.
- Zero Configuration: Auto-register all procedures from the global registry
Architecture
graph TB
subgraph "Peer A"
PA[Peer Instance]
PS[Procedure Server]
REG[Procedure Registry]
HT[HTTP Transport]
WT[WebSocket Transport]
PA --> PS
PS --> REG
PS --> HT
PS --> WT
end
subgraph "Peer B"
PB[Peer Instance]
CL[Client]
CT[Client Transport]
DISC[Discovery]
PB --> CL
CL --> CT
CL --> DISC
end
HT -.HTTP.-> CT
WT -.WebSocket.-> CT
DISC -.Discovery Protocol.-> PS
style PA fill:#e1f5ff
style PB fill:#ffe1f5
style DISC fill:#fff4e1
Component Hierarchy
graph TD
SERVER[client-server] --> PEER[Peer]
SERVER --> CONN[Connection Manager]
SERVER --> DISC[Discovery System]
SERVER --> MAN[Manifest Generator]
PEER --> PSERV[Procedure Server]
PEER --> TRANS[Transports]
TRANS --> HTTP[HTTP Transport]
TRANS --> WS[WebSocket Transport]
TRANS --> LOCAL[Local Transport]
CONN --> CLIENT[Client]
CONN --> CTRANS[Client Transports]
DISC --> ANNOUNCE[Announce Procedure]
DISC --> WATCH[Procedure Watcher]
MAN --> TS[TypeScript Generator]
MAN --> JSON[JSON Generator]
style SERVER fill:#4a90e2
style PEER fill:#7ed321
style CONN fill:#f5a623
style DISC fill:#bd10e0
style MAN fill:#50e3c2
Installation
npm install @procedures/peer
Or with pnpm:
pnpm add @procedures/peer
Dependencies
This package depends on:
@procedures/client - Core client/procedure system
zod - Schema validation
zod-to-json-schema - JSON schema generation
@mark1russell7/service - The runner: the contracts of the parts, and httpTransport of ./http
@mark1russell7/files - The containment check of the paths of staticFace()
Usage
The procedures host
createProcedureHost() builds one procedures server with its faces, and gives the parts of a service. It starts nothing and installs no signal handler. The service of the process declares the parts, and only the entry of the process starts run() (decision D2).
import { localDev, service } from "@mark1russell7/service";
import { hostPolicy, seconds } from "@procedures/client";
import { mcpFace } from "@procedures/mcp-server";
import { createProcedureHost, LOCAL_LISTENER_KNOBS } from "@procedures/peer";
const host = createProcedureHost({
registry,
policy: hostPolicy({ token }),
faces: { http: true, ws: true, mcp: mcpFace() },
listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
collections: { notes: storage },
});
const svc = host
.declare(service("app").profile(localDev))
.readiness({ type: "debounce", interval: seconds(5), failAfter: 3, recoverAfter: 1 })
.liveness({ type: "window", failAfter: seconds(45) })
.startup(seconds(30));
await svc.run();
- The parts.
host.parts are the transports: the procedure server, the stop parts of each face, and an httpTransport for each listener. host.dependencies has one dependency handle for each storage. host.controllers has one route pattern for each face.
- The faces.
http and ws are the faces of this package (httpFace(), wsFace()). mcp takes mcpFace() of @procedures/mcp-server. A face of another package is a function with the same shape.
- The local face.
localFace() gives a face factory and a transport of @procedures/client (CLI-26). A Client on the transport sends its calls to the host from the same process, through the request tracking of the service. Each call has LOCAL_CREDENTIALS, and the drain aborts its signal. The cold mode of mark uses it.
const local = localFace();
const host = createProcedureHost({ registry, faces: { local: local.face } });
const life = await host.declare(service("tool").profile(ephemeral)).run();
const client = new Client({ transport: local.transport });
- The listeners. The faces of a listener mount on its mount list, so they share one port. Without
listen, the app mounts host.handler and host.upgrade on its own listener.
- A face sets the stage at which its mount stops with the property
until of its handler, as a RequestHandler of the service does (CLI-74). The default is stop intake.
- The MCP face stays until
close transports. Thus the listener stays open through the drain, and a call in progress gets the answer of an elicitation and its cancel.
- The request tracking. Each call goes through
life.request, with the route <face> <procedure>. The function of the pattern gives the idempotency of each call: a repeatable procedure, a keyed call, or a call that runs one time (decision D3).
- The readiness of the calls. The option
controller.requires names the dependencies of the service that each call needs. While a check of one of them fails readiness, the service refuses each call with UNAVAILABLE (CLI-45).
- The streams. Each call is a stream, and a unary call is a stream of one (decision D4). A stream stays in flight until its end. A cut after the first item ends the stream with an error line. Each cut has the code
UNAVAILABLE, and its flag retryable tells if a retry is safe (CLI-48). Before the first item, the HTTP face answers 503 for a retryable cut and 500 for another cut.
- The collections. The option
collections gives the storages. The host serves collections.<name>.* for each one.
- The expose rule. The rule of the policy applies to each procedure that the host serves, also to the collection procedures (CLI-47). A host with an expose rule must list the collection procedures that it serves, for example
collections.notes.*. An exclude hides one of them, for example collections.notes.clear. The option expose of the host wins over the rule of the policy, for the server and for each face.
- Always on.
host.health, host.info, host.metrics and events.subscribe stay on, whatever the expose rule says. The host pins them with registerProcedures(procedures, { alwaysOn: true }). The topic rule is the expose rule of events.subscribe.
- No
/health route. The probes come from the runner (probeHandler or probeServer). A client checks a lockfile with host.info and the token of the lockfile.
- The probes. Each listener of the host answers the probes of the service under
/_probes (CLI-9, decision D5). The handler is probeHandler() of @mark1russell7/service/http, and it mounts before the faces.
GET /_probes/startup, /_probes/readiness and /_probes/liveness answer 200, or 503 with Retry-After. /_probes/readiness/<controller> gives the readiness of one controller.
- The probes answer each caller without the token and the browser checks. They give only the status. Each other path goes to the faces, with the token and the browser checks as before.
- A listener does not answer the report (
/_probes/report), because it names the checks and the dependencies. host.health gives the details with the token.
- The probes stop when the intake stops. Then the listener closes, as without the probes, and a new connection is refused.
probes: { until: "close transports" } keeps the listener open through the drain: the probes answer 503, and each other request gets 503 with Retry-After. A face until close transports keeps the listener open in the same way, for example the MCP face (CLI-74).
probes: { prefix } changes the prefix. probes: false turns the probes off, for example when the process has a probe server on a port of its own (probeServer(), or the option probes of runProcedureHost()).
host.info.probes() gives the base URL of the probes on each listener. Without listen, the app mounts probeHandler() on its own listener.
A read-only face for a browser
httpFace() and wsFace() take two optional options for the calls of the face (AG1-B). With them, a host serves a second face pair next to its full faces. The server enforces the rules of each face, so a page cannot go around them.
import { createProcedureHost, httpFace, wsFace, LOCAL_LISTENER_KNOBS } from "@procedures/peer";
const read = {
narrowing: { effects: { writes: [] } },
expose: ["programs.list", "programs.get", "procedure.get", "client.trace", "api.*"],
};
const host = createProcedureHost({
registry,
faces: {
http: { basePath: "/rpc" },
ws: { path: "/rpc/ws" },
readHttp: httpFace({ basePath: "/rpc/read", ...read }),
readWs: wsFace({ path: "/rpc/read/ws", ...read }),
},
listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
});
// The page opens a second WebSocketTransport to /rpc/read/ws for its read calls
narrowing (CapabilityRequest or a list of them): a narrower capability for each call of the face, as mcpFace({ narrowing }) (CLI-43). The face adds it as one more source of the narrowing key (CLI-30). The server applies the meet of all the sources, so a Procedure-Narrowing header of the page cannot make the face wider. The nested calls of a call get the narrowed capability. Thus client.chain and a program of procedure.define cannot write through the face. A narrowing that is not valid stops the host with an error.
expose (a list of patterns, a tool surface or a function): the procedures that the callers of the face reach, as hostPolicy({ expose }). The server meets it with the expose rule of the host, for the call and for each nested call. A call outside it gets NOT_FOUND, and a nested call of a data-driven procedure outside it gets NOT_EXPOSED. The rule applies to each procedure, also to host.health, host.info, host.metrics and events.subscribe.
- A face without these options serves the same calls as before. The option objects of
faces.http and faces.ws take them too.
The built files of a page
staticFace() serves the files of a folder, for example the dist folder of a Vite build. Thus an app with a page needs only the one listener of its host.
import { createProcedureHost, staticFace, LOCAL_LISTENER_KNOBS } from "@procedures/peer";
const host = createProcedureHost({
registry,
faces: {
http: true,
ws: true,
page: staticFace({ root: "dist", headers: { "Content-Security-Policy": "default-src 'self'; frame-ancestors 'self'" } }),
},
listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
});
- Put the face last. The first face that takes a request serves it, so the procedure faces keep their paths.
- The face takes each
GET and HEAD request under its basePath (default /). The face adds a / at the start of a base path that has none.
- Each path stays in
root. A path that leaves it, also through a symbolic link, gets 404.
- A path with a segment that starts with
. gets 404, so the .env or .git of a root stay hidden. Only .well-known is served.
- A missing root gives 404. The next request reads the root again, so the files of a later build are served.
- A folder gives its
index.html. A path with no file and no extension is a route of the page. A request that accepts text/html gets the fallback file (default index.html). Another request, for example a probe, gets 404. With fallback: false, each route gets 404.
- A route with a dot in its last segment, for example
/u/john.doe, has an extension. It gets 404, not the fallback.
- By default, only a page of the same origin can show the files in a frame:
DEFAULT_STATIC_HEADERS has Content-Security-Policy: frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN.
- A header of
headers replaces the default header of the same name, in any case. A policy of your own replaces the default policy, so put a frame-ancestors rule in it.
- Each response also has
X-Content-Type-Options: nosniff. A file has an ETag, and the same tag in If-None-Match gets 304.
- The request tracking of the host tracks each request, so the drain of a stop waits for it.
Creating a Server Peer
createPeer() is for a process that has no service of its own: a test, or a host that a procedure starts (server.create). The peer builds a host with createProcedureHost(), declares its parts in a service of its own, and starts run() of @mark1russell7/service on a process port that installs no signal handler and never ends the process. stop() asks that lifecycle for its shutdown. A process that has a service of its own uses createProcedureHost() and host.declare(svc) in place of a peer.
A peer has one token, and it starts one time. The WebSocket face refuses an upgrade that the server does not admit: 401 without the token or for a refusal of the request hook, and 403 for a failed browser check.
import { createPeer } from "@procedures/peer";
// Create a peer with HTTP and WebSocket transports
const peer = await createPeer({
id: "my-server",
transports: [
{
type: "http",
port: 3000,
host: "0.0.0.0",
basePath: "/api",
cors: true,
},
{
type: "websocket",
port: 3001,
host: "0.0.0.0",
path: "/ws",
},
],
autoRegister: true, // Auto-register all procedures from global registry
});
// Start all transports
await peer.start();
// Get active endpoints
console.log(peer.getEndpoints());
// [
// { type: "http", address: "http://localhost:3000/api" },
// { type: "websocket", address: "ws://localhost:3001/ws" }
// ]
// Stop the peer
await peer.stop();
Using Server Procedures
import { Client, LocalTransport, PROCEDURE_REGISTRY } from "@procedures/client";
import "@procedures/peer/register"; // registers its procedures
const client = new Client(new LocalTransport({ registry: PROCEDURE_REGISTRY }));
// Create a server
const result = await client.exec(["server", "create"], {
transports: [
{ type: "http", port: 3000 },
{ type: "websocket", port: 3001 },
],
autoRegister: true,
});
console.log(result);
// {
// serverId: "peer-1234567890-abc123",
// endpoints: [
// { type: "http", address: "http://localhost:3000/api" },
// { type: "websocket", address: "ws://localhost:3001/ws" }
// ],
// procedureCount: 42
// }
Connecting to Remote Peers