ps, logs, stop: JSON-RPC as a discriminated union
Relay’s first internal API was “send some JSON, get some JSON”. A caller sent { "stop": "web" }, and the answer was
sometimes { "ok": true }, sometimes { "stopped": "yes" } and sometimes the bare text error. Two requests in
flight swapped their answers, because nothing said which reply belonged to which request. Every caller wrote its own
guesses about the shape, and the guesses disagreed.
tsbox’s monitors need a real protocol for tsbox ps, tsbox logs and tsbox stop. Instead of inventing one, tsbox
uses JSON-RPC 2.0, a small public standard, and puts the types on top. The socket from lesson 6 carries it.
JSON-RPC 2.0 in one screen
Section titled “JSON-RPC 2.0 in one screen”A request names a method, carries parameters and an id. A response carries the same id and either a result or an
error, never both:
{"jsonrpc":"2.0","id":7,"method":"stop","params":{"id":"web","graceMs":500}}{"jsonrpc":"2.0","id":7,"result":{"stopped":true}}{"jsonrpc":"2.0","id":8,"method":"logs","params":{"id":"nope","tail":10}}{"jsonrpc":"2.0","id":8,"error":{"code":1,"message":"no such container: nope"}}The standard also reserves error codes: -32700 parse error, -32600 invalid request, -32601 method not found,
-32602 invalid params and -32603 internal error. The whole block from -32768 to -32000 is reserved, so codes of your own must stay outside it.
Framing: one message per line
Section titled “Framing: one message per line”A socket is a stream of bytes, with no message boundaries. Lesson 6 already showed that a chunk is not a line, so the
protocol takes the simplest framing there is: one JSON message per line, ended by "\n". JSON.stringify never emits
a raw newline (newlines inside strings become \n), so a line is always a whole message. Both sides run chunks
through the same line splitter, and a partial line at the end of a connection is dropped, since a half message is
garbage and not a request.
A method table that infers
Section titled “A method table that infers”The central type is one table. It says, for each method, what its params and its result are:
interface Methods { readonly ps: { readonly params: { readonly all: boolean }; readonly result: readonly { readonly id: string }[] } readonly logs: { readonly params: { readonly id: string; readonly tail: number }; readonly result: readonly string[] } readonly stop: { readonly params: { readonly id: string; readonly graceMs: number }; readonly result: { readonly stopped: boolean } }}
type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
declare function call<M extends keyof Methods>(method: M, params: Methods[M]["params"]): Promise<Result<Methods[M]["result"], string>>
const stopped = await call("stop", { id: "web", graceMs: 500 })if (stopped.ok) console.log(stopped.value.stopped)
// @ts-expect-error: "restart" is not a method in the tableawait call("restart", { id: "web" })
// @ts-expect-error: graceMs must be a numberawait call("stop", { id: "web", graceMs: "500" })M is inferred from the first argument. Methods[M]["params"] then checks the second one, and
Methods[M]["result"] is what the promise holds. One generic function gives every method its own signature, and
adding a method to the table adds it everywhere. The table is the single place that says what the protocol is.
The handler side is a mapped type over the same table (mapped types). A server must provide exactly one handler per method, and each handler’s types come from the table:
interface Methods { readonly ps: { readonly params: { readonly all: boolean }; readonly result: readonly string[] } readonly stop: { readonly params: { readonly id: string }; readonly result: { readonly stopped: boolean } }}
type Handlers = { readonly [M in keyof Methods]: (params: Methods[M]["params"]) => Promise<Methods[M]["result"]> }
// @ts-expect-error: the handler for "stop" is missingconst incomplete: Handlers = { async ps() { return [] },}Forget a handler and the compiler says so. Change a result type and every handler and every caller that disagrees fails to compile.
The types do not cross the wire
Section titled “The types do not cross the wire”Here is the catch. The method table is a promise made by the compiler of this program. The bytes that arrive were
written by another process, maybe another version of tsbox. Types vanish at runtime, so a result typed as
{ stopped: boolean } is only that if somebody checked.
So the table is paired with decoders: a function from unknown to Result<T, string> for each method’s params and for
each method’s result. They are typed with the same mapped-type trick, so a decoder whose output does not match the
table does not compile:
interface Methods { readonly stop: { readonly params: { readonly id: string; readonly graceMs: number }; readonly result: { readonly stopped: boolean } }}
type Decoder<T> = (input: unknown) => { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
const decodeStopResult: Decoder<Methods["stop"]["result"]> = (input) => { if (typeof input !== "object" || input === null) return { ok: false, error: "result: expected object" } const stopped = (input as Record<string, unknown>)["stopped"] if (typeof stopped !== "boolean") return { ok: false, error: "result.stopped: expected boolean" } return { ok: true, value: { stopped } }}That as Record<string, unknown> is the one cast the decoders need, and it is safe because the line before it proved
the value is a non-null object. In the exercise a small isRecord guard does the same without the cast.
The response itself becomes a discriminated union once it is decoded. On the wire the two shapes are told apart by
which field is present. In tsbox they are tagged, so a switch is exhaustive (discriminated unions):
type RpcResponse = | { readonly _tag: "Ok"; readonly id: number; readonly result: unknown } | { readonly _tag: "Err"; readonly id: number | null; readonly error: { readonly code: number; readonly message: string } }
function describe(response: RpcResponse): string { switch (response._tag) { case "Ok": return `reply to ${response.id}` case "Err": return `error ${response.error.code}: ${response.error.message}` }}The Err id can be null: a server that could not even parse the request does not know its id. A response with a
null id cannot be matched to any call, so the client ignores it. A caller that needs a deadline puts a timeout around
call (retry and timeout).
Correlation: ids and the pending map
Section titled “Correlation: ids and the pending map”The client numbers its requests. It keeps a map from id to “what to do with the answer”, writes the request, and returns a promise. A background loop reads response lines, decodes them and settles the promise with the matching id. Because replies are matched by id and not by order, a server may answer in any order, and two calls in flight cannot swap results.
What a call resolves to is also a union, Result<T, RpcError>, where RpcError is one of three tagged cases
(errors as values): Remote (the server answered with an error), Protocol (the answer was not the
shape the table promised) and Closed (the connection ended). A connection that ends while calls are waiting must
settle all of them with Closed. Otherwise tsbox stop hangs forever on a monitor that died mid-request.
The server: a dispatch table
Section titled “The server: a dispatch table”The server reads a line and answers with exactly one line, always, and never throws. The order of the checks is the
protocol: invalid JSON is -32700, a message that is not a request is -32600, a method not in the table is
-32601, params that fail their decoder are -32602, and then the handler runs. A handler may throw an RpcFailure
with its own code and message (no such container). Any other exception becomes -32603 Internal error with a fixed
message, never the exception’s text: a stack trace or a path from the monitor does not belong in a reply.
One subtle point is the method lookup. "toString" in handlers is true for every object, so a request for the method
toString would find a function. The lookup uses Object.hasOwn on the table instead.
The client and the server do not know about sockets. Both take a duplex: an async iterable of incoming text and a
write method. Bun.listen and Bun.connect from lesson 6 can be adapted to that shape in a few lines, and tests
use pipe.ts, a pair of in-memory ends where one side’s writes are the other side’s input. The server reads requests
one at a time, which keeps its logic simple. The cost is that a slow stop blocks a ps on the same connection, and
each CLI command opens its own connection, so that rarely matters.
Exercise
Section titled “Exercise”Local, because it has three source files. Copy main.starter.ts into the Relay project from
tooling as main.ts, copy pipe.ts unchanged, add the test file, and run bun test.
You write the encoders, the decoders for unknown, the line splitter, the RpcClient and the dispatch table. The
starter sends no jsonrpc field or newline, trusts every param and result with a cast, hands the answers to waiting
calls in order instead of by id, never reports Closed, and its dispatch throws on a bad request. The tests run the
client and the server against each other in memory and also use a hand-written server that answers out of order and
one that sends a wrong-shaped result. The type checks (@ts-expect-error on a bad method and bad params) are part of
the test file.
// tsbox talks to each container's monitor over a Unix socket: `tsbox ps`, `tsbox logs`, `tsbox stop`. The// first draft sent bare JSON with no framing and no ids, and trusted whatever came back: a monitor that// answered `stop` with { "stopped": "yes" } made the CLI print "stopped: yes" and exit 0, and two `ps`// calls in flight swapped their answers. pipe.ts (given: copy it unchanged) is an in-memory socket.// Rules (JSON-RPC 2.0, one message per line, "\n" ends a message):// - encodeRequest(id, method, params) = JSON { jsonrpc: "2.0", id, method, params } + "\n", and `params`// must match the method table (a wrong method or params is a COMPILE error).// - paramDecoders / resultDecoders check `unknown` against the table: "params: expected object",// `params.<field>: expected string|integer|boolean`, "result: expected array|object",// `result[<i>]: ...`, `result[<i>].status: expected created, running or exited`.// - decodeResponse(line) parses `unknown`: errors "invalid json", "response: expected object",// `response.jsonrpc: expected "2.0"`, "response.id: expected integer or null",// "response: expected exactly one of result and error", "response.id: expected integer" (a result// with a null id), "response.error: expected { code: integer, message: string }".// - lines(chunks): join chunks, yield complete lines (strip "\r"), drop a partial line at the end.// - the client matches each response to its call BY ID (answers may arrive out of order), checks the// result with resultDecoders (a bad shape is { _tag: "Protocol", message: `bad <method> result: <why>` }),// turns an error response into { _tag: "Remote", code, message }, and resolves every waiting call// (and every later call) with { _tag: "Closed" } when the connection ends.// - dispatch(handlers, line) never throws; it returns one response line: -32700 "Parse error" (id null),// -32600 "Invalid Request" (id of the request if it has one), -32601 `Method not found: <name>` (own// method names only), -32602 `Invalid params: <why>` (paramDecoders), a handler's RpcFailure as its own// code and message, any other throw as -32603 "Internal error" (never the cause).// - serve(handlers, duplex) answers requests one at a time until the peer hangs up; blank lines are ignored.import type { Duplex } from "./pipe.ts"
export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export interface ContainerInfo { readonly id: string readonly status: "created" | "running" | "exited"}
export interface Methods { readonly ps: { readonly params: { readonly all: boolean }; readonly result: readonly ContainerInfo[] } readonly logs: { readonly params: { readonly id: string; readonly tail: number }; readonly result: readonly string[] } readonly stop: { readonly params: { readonly id: string; readonly graceMs: number }; readonly result: { readonly stopped: boolean } }}export type MethodName = keyof Methods
export const ErrorCode = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603,} as const
export class RpcFailure extends Error { readonly code: number constructor(code: number, message: string) { super(message) this.code = code }}
type Decoder<T> = (input: unknown) => Result<T, string>
export const paramDecoders: { readonly [M in MethodName]: Decoder<Methods[M]["params"]> } = { ps: (input) => ({ ok: true, value: input as Methods["ps"]["params"] }), logs: (input) => ({ ok: true, value: input as Methods["logs"]["params"] }), stop: (input) => ({ ok: true, value: input as Methods["stop"]["params"] }),}
export const resultDecoders: { readonly [M in MethodName]: Decoder<Methods[M]["result"]> } = { ps: (input) => ({ ok: true, value: input as Methods["ps"]["result"] }), logs: (input) => ({ ok: true, value: input as Methods["logs"]["result"] }), stop: (input) => ({ ok: true, value: input as Methods["stop"]["result"] }),}
export function encodeRequest<M extends MethodName>(id: number, method: M, params: Methods[M]["params"]): string { return JSON.stringify({ id, method, params })}
export const encodeResult = (id: number, result: unknown): string => `${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`
export const encodeError = (id: number | null, code: number, message: string): string => `${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`
export type RpcResponse = | { readonly _tag: "Ok"; readonly id: number; readonly result: unknown } | { readonly _tag: "Err"; readonly id: number | null; readonly error: { readonly code: number; readonly message: string } }
export function decodeResponse(line: string): Result<RpcResponse, string> { const json = JSON.parse(line) return { ok: true, value: { _tag: "Ok", id: json.id, result: json.result } }}
export async function* lines(chunks: AsyncIterable<string>): AsyncGenerator<string> { for await (const chunk of chunks) yield chunk}
export type RpcError = | { readonly _tag: "Remote"; readonly code: number; readonly message: string } | { readonly _tag: "Protocol"; readonly message: string } | { readonly _tag: "Closed" }
export interface RpcClient { call<M extends MethodName>(method: M, params: Methods[M]["params"]): Promise<Result<Methods[M]["result"], RpcError>>}
export function createClient(duplex: Duplex): RpcClient { const waiting: Array<(value: unknown) => void> = [] void (async () => { for await (const line of lines(duplex.incoming)) waiting.shift()?.(JSON.parse(line).result) })() return { call(method, params) { return new Promise((resolve) => { waiting.push((value) => resolve({ ok: true, value: value as never })) duplex.write(encodeRequest(1, method, params)) }) }, }}
export type Handlers = { readonly [M in MethodName]: (params: Methods[M]["params"]) => Promise<Methods[M]["result"]> }
export async function dispatch(handlers: Handlers, line: string): Promise<string> { const request = JSON.parse(line) const result = await handlers[request.method as MethodName](request.params) return encodeResult(request.id, result)}
export async function serve(handlers: Handlers, duplex: Duplex): Promise<void> { for await (const line of lines(duplex.incoming)) duplex.write(await dispatch(handlers, line))}export interface Duplex { readonly incoming: AsyncIterable<string> write(text: string): void close(): void}
function channel() { const queue: string[] = [] let ended = false let wake: (() => void) | undefined return { push(text: string): void { if (ended) return queue.push(text) wake?.() }, end(): void { ended = true wake?.() }, async *[Symbol.asyncIterator](): AsyncGenerator<string> { for (;;) { const next = queue.shift() if (next !== undefined) { yield next } else if (ended) { return } else { await new Promise<void>((resolve) => { wake = resolve }) wake = undefined } } }, }}
export function duplexPair(): readonly [Duplex, Duplex] { const aToB = channel() const bToA = channel() return [ { incoming: bToA, write: (text) => aToB.push(text), close: () => aToB.end() }, { incoming: aToB, write: (text) => bToA.push(text), close: () => bToA.end() }, ]}import { expect, test } from "bun:test"import { ErrorCode, RpcFailure, createClient, decodeResponse, dispatch, encodeRequest, lines, serve,} from "./main.ts"import type { ContainerInfo, Handlers, Methods, RpcClient, RpcError } from "./main.ts"import { duplexPair } from "./pipe.ts"
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : falsetype Expect<T extends true> = T
const containers: readonly ContainerInfo[] = [ { id: "web", status: "running" }, { id: "job", status: "exited" },]
const handlers: Handlers = { async ps({ all }) { return all ? containers : containers.filter((c) => c.status === "running") }, async logs({ id, tail }) { if (id !== "web") throw new RpcFailure(1, `no such container: ${id}`) return ["one", "two", "three"].slice(-tail) }, async stop({ id }) { if (id === "boom") throw new Error("secret: /home/me/.tsbox/key") return { stopped: id === "web" } },}
async function connected() { const [clientEnd, serverEnd] = duplexPair() const served = serve(handlers, serverEnd) return { client: createClient(clientEnd), clientEnd, serverEnd, served }}
test("requests are one JSON line with jsonrpc 2.0", () => { expect(encodeRequest(7, "stop", { id: "web", graceMs: 500 })).toBe( '{"jsonrpc":"2.0","id":7,"method":"stop","params":{"id":"web","graceMs":500}}\n', )})
test("decodeResponse reads a result and an error", () => { expect(decodeResponse('{"jsonrpc":"2.0","id":3,"result":{"stopped":true}}')).toEqual({ ok: true, value: { _tag: "Ok", id: 3, result: { stopped: true } }, }) expect(decodeResponse('{"jsonrpc":"2.0","id":3,"error":{"code":-32601,"message":"Method not found: x"}}')).toEqual({ ok: true, value: { _tag: "Err", id: 3, error: { code: -32601, message: "Method not found: x" } }, }) expect(decodeResponse('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}')).toEqual({ ok: true, value: { _tag: "Err", id: null, error: { code: -32700, message: "Parse error" } }, })})
test("decodeResponse names what is wrong with a bad response", () => { const cases: ReadonlyArray<readonly [string, string]> = [ ["{nope", "invalid json"], ["[]", "response: expected object"], ['{"jsonrpc":"1.0","id":1,"result":1}', 'response.jsonrpc: expected "2.0"'], ['{"jsonrpc":"2.0","id":"1","result":1}', "response.id: expected integer or null"], ['{"jsonrpc":"2.0","id":1}', "response: expected exactly one of result and error"], ['{"jsonrpc":"2.0","id":1,"result":1,"error":{"code":1,"message":"x"}}', "response: expected exactly one of result and error"], ['{"jsonrpc":"2.0","id":null,"result":1}', "response.id: expected integer"], ['{"jsonrpc":"2.0","id":1,"error":{"code":"1","message":"x"}}', "response.error: expected { code: integer, message: string }"], ['{"jsonrpc":"2.0","id":1,"error":"boom"}', "response.error: expected { code: integer, message: string }"], ] for (const [line, error] of cases) expect(decodeResponse(line)).toEqual({ ok: false, error })})
test("lines joins chunks split anywhere and drops a trailing partial line", async () => { const [a, b] = duplexPair() for (const chunk of ['{"a":1}\n{"b"', ":2}\r\n", "\n", "partial"]) a.write(chunk) a.close() const seen: string[] = [] for await (const line of lines(b.incoming)) seen.push(line) expect(seen).toEqual(['{"a":1}', '{"b":2}', ""])})
test("dispatch answers each kind of bad request with its JSON-RPC code", async () => { const send = async (line: string) => JSON.parse(await dispatch(handlers, line)) const error = (id: number | null, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } })
expect(await send("{nope")).toEqual(error(null, ErrorCode.parse, "Parse error")) expect(await send("[]")).toEqual(error(null, ErrorCode.invalidRequest, "Invalid Request")) expect(await send('{"jsonrpc":"2.0","id":1}')).toEqual(error(1, ErrorCode.invalidRequest, "Invalid Request")) expect(await send('{"jsonrpc":"1.0","id":1,"method":"ps"}')).toEqual(error(1, ErrorCode.invalidRequest, "Invalid Request")) expect(await send('{"jsonrpc":"2.0","id":"x","method":"ps"}')).toEqual(error(null, ErrorCode.invalidRequest, "Invalid Request")) expect(await send('{"jsonrpc":"2.0","id":2,"method":"restart","params":{}}')).toEqual( error(2, ErrorCode.methodNotFound, "Method not found: restart"), ) expect(await send('{"jsonrpc":"2.0","id":3,"method":"toString","params":{}}')).toEqual( error(3, ErrorCode.methodNotFound, "Method not found: toString"), ) expect(await send('{"jsonrpc":"2.0","id":4,"method":"stop","params":{"id":"web","graceMs":"soon"}}')).toEqual( error(4, ErrorCode.invalidParams, "Invalid params: params.graceMs: expected integer"), ) expect(await send('{"jsonrpc":"2.0","id":5,"method":"ps"}')).toEqual( error(5, ErrorCode.invalidParams, "Invalid params: params: expected object"), )})
test("dispatch returns a result line, relays RpcFailure and hides other errors", async () => { const send = async (line: string) => JSON.parse(await dispatch(handlers, line)) expect(await send('{"jsonrpc":"2.0","id":1,"method":"ps","params":{"all":false}}')).toEqual({ jsonrpc: "2.0", id: 1, result: [{ id: "web", status: "running" }], }) expect(await send('{"jsonrpc":"2.0","id":2,"method":"logs","params":{"id":"nope","tail":1}}')).toEqual({ jsonrpc: "2.0", id: 2, error: { code: 1, message: "no such container: nope" }, }) const hidden = await dispatch(handlers, '{"jsonrpc":"2.0","id":3,"method":"stop","params":{"id":"boom","graceMs":0}}') expect(JSON.parse(hidden)).toEqual({ jsonrpc: "2.0", id: 3, error: { code: -32603, message: "Internal error" } }) expect(hidden.includes("secret")).toBe(false) expect(hidden.endsWith("\n")).toBe(true)})
test("client and server talk through an in-memory pipe, and each call infers its result", async () => { const { client } = await connected()
const running = await client.call("ps", { all: false }) const everything = await client.call("ps", { all: true }) const tail = await client.call("logs", { id: "web", tail: 2 }) const stopped = await client.call("stop", { id: "web", graceMs: 100 })
expect(running).toEqual({ ok: true, value: [{ id: "web", status: "running" }] }) expect(everything).toEqual({ ok: true, value: containers }) expect(tail).toEqual({ ok: true, value: ["two", "three"] }) expect(stopped).toEqual({ ok: true, value: { stopped: true } })
if (stopped.ok) { const value: { readonly stopped: boolean } = stopped.value expect(value.stopped).toBe(true) } if (tail.ok) { type Lines = Expect<Equal<typeof tail.value, readonly string[]>> const first: string | undefined = tail.value[0] expect(first).toBe("two") const check: Lines = true expect(check).toBe(true) }
// @ts-expect-error: "restart" is not in the method table void client.call("restart", { id: "web" }) // @ts-expect-error: graceMs is a number void client.call("stop", { id: "web", graceMs: "100" }) // @ts-expect-error: logs needs tail void client.call("logs", { id: "web" })})
test("the method table decides the types", () => { type StopResult = Methods["stop"]["result"] type Check = Expect<Equal<StopResult, { readonly stopped: boolean }>> const ok: Check = true expect(ok).toBe(true)})
test("a remote failure comes back as a Remote error value", async () => { const { client } = await connected() const reply = await client.call("logs", { id: "ghost", tail: 1 }) expect(reply).toEqual({ ok: false, error: { _tag: "Remote", code: 1, message: "no such container: ghost" } }) const hidden = await client.call("stop", { id: "boom", graceMs: 0 }) expect(hidden).toEqual({ ok: false, error: { _tag: "Remote", code: -32603, message: "Internal error" } })})
test("responses are matched to calls by id, even when they arrive out of order", async () => { const [clientEnd, serverEnd] = duplexPair() const client = createClient(clientEnd) const received: { id: number; method: string }[] = [] void (async () => { for await (const line of lines(serverEnd.incoming)) { const request = JSON.parse(line) as { id: number; method: string } received.push(request) if (received.length === 2) { const [first, second] = received if (first === undefined || second === undefined) return serverEnd.write(`{"jsonrpc":"2.0","id":${second.id},"result":["from-${second.method}"]}\n`) serverEnd.write(`{"jsonrpc":"2.0","id":${first.id},"result":[]}\n`) } } })() const [one, two] = await Promise.all([client.call("ps", { all: true }), client.call("logs", { id: "web", tail: 1 })]) expect(one).toEqual({ ok: true, value: [] }) expect(two).toEqual({ ok: true, value: ["from-logs"] }) expect(received.map((r) => r.id)).toEqual([1, 2])})
test("a result of the wrong shape is a Protocol error, not a wrong-typed value", async () => { const [clientEnd, serverEnd] = duplexPair() const client = createClient(clientEnd) void (async () => { for await (const _line of lines(serverEnd.incoming)) { serverEnd.write('{"jsonrpc":"2.0","id":1,"result":[{"id":"web","status":"sleeping"}]}\n') } })() const reply = await client.call("ps", { all: true }) expect(reply).toEqual({ ok: false, error: { _tag: "Protocol", message: "bad ps result: result[0].status: expected created, running or exited" }, })})
test("when the connection ends, waiting calls and later calls get Closed", async () => { const [clientEnd, serverEnd] = duplexPair() const client = createClient(clientEnd) const waiting = client.call("ps", { all: true }) serverEnd.close() const closed: { ok: false; error: RpcError } = { ok: false, error: { _tag: "Closed" } } expect(await waiting).toEqual(closed) expect(await client.call("ps", { all: true })).toEqual(closed)})
test("serve answers a request split across chunks and ends when the client hangs up", async () => { const [clientEnd, serverEnd] = duplexPair() const served = serve(handlers, serverEnd) const replies: string[] = [] const reading = (async () => { for await (const line of lines(clientEnd.incoming)) replies.push(line) })() const request = encodeRequest(9, "stop", { id: "web", graceMs: 1 }) clientEnd.write(request.slice(0, 20)) clientEnd.write(request.slice(20)) clientEnd.write("\n") clientEnd.close() await served serverEnd.close() await reading expect(replies).toEqual(['{"jsonrpc":"2.0","id":9,"result":{"stopped":true}}'])})- JSON-RPC 2.0 gives a request/response shape, ids, and reserved error codes. One JSON message per line is enough framing for a socket.
- One
Methodstable is the single source of truth.call<M extends keyof Methods>infers each result, and a mappedHandlerstype forces a handler for every method. - Types do not cross the wire: decode params and results from
unknown, and report a bad shape as aProtocolerror. - Decode a response into a tagged union, match answers to calls by id, and settle everything with
Closedwhen the connection ends. - The server never throws and never leaks: every request gets one response line, and unexpected errors become
-32603 Internal error.
Further reading
Section titled “Further reading”- JSON-RPC 2.0 Specification: requests, responses and reserved error codes.