Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 68 additions & 80 deletions docs/docs/languages/typescript/client-and-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,112 +3,102 @@
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. */
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<Message>;
history(params: ChatHistoryParams): Promise<Message[]>;
wipe(): Promise<void>;
note(params: ChatNoteParams): Promise<void>;
export interface Mail {
/** @throws {RecipientNotFoundError} */
send_message(params: MailSendMessageParams): Promise<string>;
fetch_inbox(): Promise<Message[]>;
}

/** @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<ChatClient> {
return new ChatClient(await Client.connect(transport, codec, IR_HASH, framing));
static async connect(transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise<MailClient> {
return new MailClient(await Client.connect(transport, codec, IR_HASH, framing));
}

async send(params: ChatSendParams): Promise<Message> { /* … */ }
async history(params: ChatHistoryParams): Promise<Message[]> { /* … */ }
async wipe(): Promise<void> { /* … */ }
async note(params: ChatNoteParams): Promise<void> { /* … */ }
async send_message(params: MailSendMessageParams): Promise<string> { /* … */ }
async fetch_inbox(): Promise<Message[]> { /* … */ }
}

export function serveChat(impl: Chat, transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise<void> {
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<void> {
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
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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
Expand All @@ -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<Message> {
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<string> {
if (!params.message.body) throw new RecipientNotFoundError({});
return `sent: ${params.message.body}`;
}
async history(): Promise<Message[]> { return []; }
async wipe(): Promise<void> {}
async note(): Promise<void> {}
async fetch_inbox(): Promise<Message[]> { 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.
Loading