diff --git a/docs/docs/languages/typescript/client-and-server.md b/docs/docs/languages/typescript/client-and-server.md index 50c4318..e8cfa11 100644 --- a/docs/docs/languages/typescript/client-and-server.md +++ b/docs/docs/languages/typescript/client-and-server.md @@ -3,35 +3,29 @@ A protocol on the lockstep `datagram` framing (`@framing = "datagram"`) gets a client and a server. This page is only that case; every other protocol runs on a [connection](connections.md), the default, with its own `serve` and `connect` -([What you use](index.md#what-you-use) says which is which). This page -follows the runtime's own test fixture — a lockstep `Chat` protocol with a -throwing call, a plain call, a `()` return, and a one-way call: +([What you use](index.md#what-you-use) says which is which). This page assumes +a schema like [Protocols](../../guides/idl/protocol.md)'s `Mail` example has +been generated to TypeScript: ```ids -struct Message { - body: string - seq: u64 -} - -error Rejected { - reason: string -} - @framing = "datagram" -protocol Chat { - function send(text: string) -> Message ! Rejected; - function history(limit: u32) -> Message[]; - function wipe(); - function note(text: string); +protocol Mail { + @timeout_ms = 1000 + function send_message(message: Message) -> string ! RecipientNotFound; + function fetch_inbox() -> Message[]; } ``` ## What codegen emits +Full details are [Code generation](../../guides/codegen/index.md)'s job, not +this page's — but the shapes below are what the generated file actually +contains, so the rest of this page can refer to them by name. + ```typescript /** Canonical digest of the frozen IR this file was generated from — the * two ends of a connection must agree on it. */ -export const IR_HASH = 0x222ffe8dc03c4d62n; +export const IR_HASH = 0x7ea94b595fcf4393n; /** The package's wire format (`wire.format`): what this file's helpers * encode with, and what the peer has to speak too. */ @@ -39,76 +33,72 @@ export const Format: Codec = new PackedCodec(); export interface Message { body: string; - seq: bigint; } -export const MessageLayout: Layout = { struct: [["body", "string"], ["seq", "u64"]] }; +export const MessageLayout: Layout = { struct: [["body", "string"]] }; -export class RejectedError extends Error { +export class RecipientNotFoundError extends Error { static readonly ordinal = 0; - readonly data: Rejected; - constructor(data: Rejected) { /* … */ } + readonly data: RecipientNotFound; + constructor(data: RecipientNotFound) { /* … */ } } -export interface ChatSendParams { - text: string; +export interface MailSendMessageParams { + message: Message; } /** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; - -// … ChatHistoryParams and ChatNoteParams, and their layouts, the same way. +export const MailSendMessageParamsLayout: Layout = { struct: [["message", () => MessageLayout]] }; -export interface Chat { - /** @throws {RejectedError} */ - send(params: ChatSendParams): Promise; - history(params: ChatHistoryParams): Promise; - wipe(): Promise; - note(params: ChatNoteParams): Promise; +export interface Mail { + /** @throws {RecipientNotFoundError} */ + send_message(params: MailSendMessageParams): Promise; + fetch_inbox(): Promise; } /** @internal */ -export const CHAT_CALLS = ["send", "history", "wipe", "note"] as const; +export const MAIL_CALLS = ["send_message", "fetch_inbox"] as const; -export class ChatDispatcher implements Dispatch { - constructor(impl: Chat) { /* … */ } +export class MailDispatcher implements Dispatch { + constructor(impl: Mail) { /* … */ } // … } -export class ChatClient { +export class MailClient { constructor(client: Client) { /* … */ } - static async connect(transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { - return new ChatClient(await Client.connect(transport, codec, IR_HASH, framing)); + static async connect(transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { + return new MailClient(await Client.connect(transport, codec, IR_HASH, framing)); } - async send(params: ChatSendParams): Promise { /* … */ } - async history(params: ChatHistoryParams): Promise { /* … */ } - async wipe(): Promise { /* … */ } - async note(params: ChatNoteParams): Promise { /* … */ } + async send_message(params: MailSendMessageParams): Promise { /* … */ } + async fetch_inbox(): Promise { /* … */ } } -export function serveChat(impl: Chat, transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { - return new Server(new ChatDispatcher(impl), codec, framing).serve(transport, IR_HASH); +export function serveMail(impl: Mail, transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { + return new Server(new MailDispatcher(impl), codec, framing).serve(transport, IR_HASH); } ``` A lockstep protocol's file has no entry-point comment; in `lib` mode the -package's `index.ts` lists its `serveChat` and `ChatClient.connect`. - -- `seq` is a `u64`, so it's a `bigint`. `number` holds integers exactly only - up to 2^53, so every 64- and 128-bit integer is a `bigint`, and a constant - of one is written `7n`. Every type gets a `Layout` of the same name plus - `Layout` (`MessageLayout`), which the generated client and dispatcher pass to - the codec: it reads a `u64` as a `bigint`, and says how wide each integer is. -- `Chat` is the interface your implementation fills in — every method +package's `index.ts` lists its `serveMail` and `MailClient.connect`. + +- A 64- or 128-bit integer is a `bigint`: `number` holds integers exactly only + up to 2^53, and a constant of one is written `7n`, as `IR_HASH` is. `Message` + has none, but a `u64` field would be a `bigint`. Every type gets a `Layout` of + the same name plus `Layout` (`MessageLayout`), which the generated client and + dispatcher pass to the codec: it reads a `u64` as a `bigint`, and says how + wide each integer is. +- `Mail` is the interface your implementation fills in — every method `async`/`Promise`-returning, a thrown `*Error` class per declared `!` (several, comma-separated, if the function lists several). -- `ChatDispatcher` wraps an implementation and implements the runtime's +- `MailDispatcher` wraps an implementation and implements the runtime's `Dispatch` interface. -- `ChatClient` wraps a `Client` and gives you one method per function. -- `serveChat` is the generated convenience function: build a - `ChatDispatcher`, run the handshake, serve. There's no dispatcher +- `MailClient` wraps a `Client` and gives you one method per function. + `@timeout_ms` is not applied by it: the Rust client passes it to + `call_with_timeout`, and this one makes a plain `call`. +- `serveMail` is the generated convenience function: build a + `MailDispatcher`, run the handshake, serve. There's no dispatcher "class method" for this — it's a standalone function alongside the classes. - `Format` and `IR_HASH` are exported by this file. A package that also has a @@ -138,19 +128,19 @@ the frame past that point, to queue it or write it later, must copy it first. ```typescript import { duplex } from "@comline/runtime"; -import { ChatClient, serveChat } from "./generated/chat.js"; +import { MailClient, serveMail } from "./generated/mail.js"; const [clientSide, serverSide] = duplex(); -serveChat(new MyChat(), serverSide); +serveMail(new MyMail(), serverSide); -const client = await ChatClient.connect(clientSide); -const message = await client.send({ text: "hello" }); -await client.note({ text: "fire and forget" }); // no response awaited +const client = await MailClient.connect(clientSide); +const receipt = await client.send_message({ message: { body: "hello" } }); +const inbox = await client.fetch_inbox(); ``` Both encode with the package's `Format` unless given another `Codec`. -`ChatClient.connect` builds a `Handshake` from `IR_HASH` and the codec's +`MailClient.connect` builds a `Handshake` from `IR_HASH` and the codec's name, sends it, reads the peer's, and rejects with `RuntimeError.handshake()` on a mismatch — the same check the Rust runtime does, byte-compatible with it (see [Framing & wire @@ -161,10 +151,10 @@ normal `try`/`catch` (or `instanceof`) handles it: ```typescript try { - await client.send({ text: "" }); + await client.send_message({ message: { body: "" } }); } catch (e) { - if (e instanceof RejectedError) { - console.log("rejected:", e.data.reason); + if (e instanceof RecipientNotFoundError) { + console.log("no such recipient"); } else { throw e; // a RuntimeError, or something else entirely } @@ -181,7 +171,7 @@ publish your internals to everyone who calls you. ```typescript try { - await client.history({ limit: 10 }); + await client.fetch_inbox(); } catch (e) { if (e instanceof RuntimeError && e.is("provider")) { // the call reached the provider and it broke; retrying may help @@ -199,29 +189,27 @@ failure, and the next one still works. ## Serving ```typescript -import { serveChat } from "./generated/chat.js"; +import { serveMail } from "./generated/mail.js"; -class MyChat implements Chat { - async send(params: ChatSendParams): Promise { - if (!params.text) throw new RejectedError({ reason: "empty message" }); - return { body: params.text, seq: 1n }; +class MyMail implements Mail { + async send_message(params: MailSendMessageParams): Promise { + if (!params.message.body) throw new RecipientNotFoundError({}); + return `sent: ${params.message.body}`; } - async history(): Promise { return []; } - async wipe(): Promise {} - async note(): Promise {} + async fetch_inbox(): Promise { return []; } } -await serveChat(new MyChat(), transport); +await serveMail(new MyMail(), transport); ``` Like the Rust runtime, there's no listener/accept loop built in — -`serveChat` (and the lower-level `Server` class it wraps) serves **one** +`serveMail` (and the lower-level `Server` class it wraps) serves **one** already-connected `Transport` until it closes. Accepting multiple connections concurrently is ordinary `Promise`-based concurrency on your -side: call `serveChat` once per connection and let them run. +side: call `serveMail` once per connection and let them run. For manual control over the handshake, the `Server` class underneath exposes `serveOne` (one call), `serveUnverified` (loop, no handshake), and `serve(transport, irHash, handshake?)` (the handshake, `comline@1` -unless given, then the loop) — `serveChat` is just `serve` with the +unless given, then the loop) — `serveMail` is just `serve` with the dispatcher and `IR_HASH` already filled in for you.