# Calls

> Ask the room to do something and get its answer, with names, args and replies typed from one declaration.

A **call** is a request from one client that the room answers: buy an
item, claim a seat, look something up. On both sides it's a function:
the client calls `room.calls.buy(args)` and awaits the reply, or the
error the room threw, and the room's `buy(args, { room, connection })`
returns it. Use calls for actions that need an answer;
for changes everyone sees, the answer can be the state itself, and for
fire-and-forget events, send a message.

## Declaring calls

Calls are declared once, in the schema module the room and its clients
both import. `defineCalls` takes an object with a `call(...)` for each
call, which declares its args with the field types entity kinds use:

```ts
// schema.ts
import { call, defineCalls, defineSchema, entity } from "@irtio/room";

export const prices: Record<string, number> = { sword: 50, shield: 30 };

export const Wallet = entity("wallet", { coins: "u32" });

export const schema = defineSchema({
  private: Wallet,
  calls: defineCalls({
    buy: call({ item: "string", count: "u8" }).returns<{ coins: number }>(),
    balance: call().returns<number>(),
  }),
});
```

- `call()` takes no args, and `call({ ... })` takes an object with
  those fields. Every field type but `bytes` works, including
  `json<T>()` for a nested value of type `T` and `string(max)` for a
  string of at most `max` characters, such as `call({ id: string(64) })`.
- `.returns<T>()` declares the reply's type. Without it the reply is
  `void`. It's only a type; the room doesn't check what a handler
  returns.
- The room checks args against the fields before the handler runs.
  Every field must be there, with the same rules a write of that field
  type gets: a `u8` is an integer from 0 to 255, a `string` at most 16
  KB, a `string(64)` at most 64 characters, an `f32`, `f64` or `angle`
  a finite number, a `quat` an object with finite `x`, `y`, `z` and
  `w`. Keys that aren't declared are dropped. Args that fail reject the
  call with a message naming the field, such as `the args of buy are
  invalid: count is 300; u8 holds 0 to 255`, and the room logs nothing.
- The client runs the same check before it sends, so bad args reject
  at once with that message, after `call <name> failed: ` rather than
  `call <name> failed in the room: `, and nothing is sent. What it sends
  is what the check returns: a `THREE.Quaternion` passed for a `quat`
  goes as `{ x, y, z, w }`, not the array its `toJSON` gives. The room
  still checks, since a client can be changed.
- The fields check types and ranges, not meaning: `item` above is any
  string, so the handler still looks it up in `prices`.

### Declaring a call's signature

For args fields can't describe, such as bytes, a union or an array at
the top level, declare the calls' signatures as a type instead, each
with at most one argument and its reply. The object passed to
`defineCalls` is then optional and holds a `parse` function for any
call that needs one:

```ts
// upload.ts
import { defineCalls, defineSchema } from "@irtio/room";

export const schema = defineSchema({
  calls: defineCalls<{
    upload(args: Uint8Array): number;
    pick(args: "rock" | "paper" | "scissors"): void;
  }>({
    upload(raw) {
      if (!(raw instanceof Uint8Array) || raw.length > 4096) throw new Error("must be at most 4096 bytes");
      return raw;
    },
    pick(raw) {
      if (raw !== "rock" && raw !== "paper" && raw !== "scissors") throw new Error("must be rock, paper or scissors");
      return raw;
    },
  }),
});
```

The types are only types here: a modified client can send anything. A
`parse` function runs on the room before the handler, gets the decoded
JSON, or the bytes, and returns the args or throws, which rejects the
call as a failed field check does. Without one, the handler gets the
decoded JSON unchecked. One `defineCalls` takes either `call(...)`
declarations or signatures, not both.

## In the room

The room's `calls` has a handler for each declared call. It takes the
args first, as the function the client called does, then the room and
the calling connection. TypeScript checks that none is missing, that
the args have the declared type, and that the handler returns, or
resolves to, the declared reply.

```ts
// room.ts
import { CallRejected, defineRoom } from "@irtio/room";
import { prices, schema } from "./schema.js";

export default defineRoom({
  schema,
  onJoin(room, conn) {
    const wallet = room.private(conn);
    if (wallet.coins === 0) wallet.coins = 100;
  },
  calls: {
    buy({ item, count }, { room, connection }) {
      if (!Object.hasOwn(prices, item)) throw new CallRejected(`there's no ${item} for sale`);
      const wallet = room.private(connection);
      const cost = prices[item]! * count;
      if (wallet.coins < cost) throw new CallRejected("not enough coins");
      wallet.coins -= cost;
      return { coins: wallet.coins };
    },
    balance: (_args, { room, connection }) => room.private(connection).coins,
  },
});
```

The order differs from the room's hooks, which take the room first: a
hook is IRT calling the room, and a handler is the function a client
called.

### Handlers in their own files

`calls` stays one object on `defineRoom`, which is how TypeScript tells
that every declared call has a handler. To keep handlers apart, write
them with `implement`, which types them against the schema and returns
them as given, and spread them into `calls`:

```ts
// shop.ts
import { CallRejected, implement } from "@irtio/room";
import { prices, schema } from "./schema.js";

export const shop = implement(schema, {
  buy({ item, count }, { room, connection }) {
    const cost = (prices[item] ?? Infinity) * count;
    const wallet = room.private(connection);
    if (wallet.coins < cost) throw new CallRejected("not enough coins");
    wallet.coins -= cost;
    return { coins: wallet.coins };
  },
});
```

```ts
// split-room.ts
import { defineRoom } from "@irtio/room";
import { schema } from "./schema.js";
import { shop } from "./shop.js";

export default defineRoom({
  schema,
  calls: { ...shop, balance: (_args, { room, connection }) => room.private(connection).coins },
});
```

- What a handler throws becomes the client's error, with its message,
  and the room keeps running.
- Throw `CallRejected` for a rejection that's part of the game, such as
  "not enough coins" or "the stairs are sealed": the client gets its
  message and the room logs nothing. Any other error is logged at error
  level with the room, player, tick and stack, because it's taken for a
  bug. Args that fail their fields or `parse` reject the call without
  logging too.
- A handler may be async; the reply goes out when its promise settles.
- A handler sees what the caller [wrote](/docs/room/ownership) before
  calling: the client sends its unsent owner writes ahead of the call,
  and the room applies them, through `writes`, before the handler runs.
  Applying them changes room state, so such a call replies after the
  state update that saves them.
- Handlers run as calls arrive, between ticks. A call that changed room
  state (shared or private state, entities, ownership, bans) replies
  after the state update that carries the change has saved it: a reply
  means the change is saved outside the VM and a room host crash can't
  lose it, and the client already has it. In a room
  [without ticks](/docs/room/sdk#with-or-without-ticks) that
  update goes out as soon as the handler returns, so the reply comes
  one round trip after the call; in a room with ticks it waits for the
  next tick, up to `1000 / tickRate` ms later. A call that changed
  nothing replies at once, unless another change is waiting for the
  same update. Errors go out at once. What isn't room
  state, such as `room.data` or a stepper's own state, isn't covered.
- A call that changes room state just as the room hibernates fails
  rather than replies, as any call in flight when the connection drops
  does.

## On the client

```ts
// client.ts
import { connect, IrtError } from "@irtio/client";
import { schema } from "./schema.js";

const room = await connect("shop-1", { schema });

try {
  const { coins } = await room.calls.buy({ item: "sword", count: 1 });
  console.log("coins left", coins);
} catch (e) {
  if (e instanceof IrtError && e.name === "OperationError") console.log("couldn't buy:", e.reason);
  else throw e;
}

const balance: number = await room.calls.balance(undefined, { timeout: 2000 });
console.log(balance);
```

`room.calls` has a function for each declared call, taking its args,
or none for a call declared with `call()`, and resolving to the
declared reply. The second argument is `{ timeout, signal }`. A call
rejects with an `IrtError`: an `OperationError` when the room throws,
with the handler's message as its `reason`; a `TimeoutError` after a
timeout of 10 seconds by default; an `AbortError` when its `signal`
aborts; and a `NetworkError` when the connection drops or the room
restarts before the reply. In those last cases the call may or may not
have run, and the SDK doesn't retry it. A call aborted with its
`signal` may still run in the room: the signal only stops the client
waiting.

```ts
// abort.ts
import { connect } from "@irtio/client";
import { schema } from "./schema.js";

const room = await connect("shop-1", { schema });
const leaving = new AbortController();
addEventListener("pagehide", () => leaving.abort());
await room.calls.buy({ item: "shield", count: 1 }, { signal: leaving.signal });
```

A handoff that moves the caller to another room isn't one of those: the
client waits up to 3 seconds for its calls' replies before it leaves, so
a handler can hand off its own caller and reply; see
[Lobbies](/docs/room/lobbies#from-your-own-room-code).
The error's `code` is 422 when the room answered with an error, such as
a `CallRejected`, and 0 when no answer came; see
[Errors](/docs/client/errors#calls).

## Common mistakes

- **Rejecting with a plain `Error`.** It works, but every rejection is
  logged as an error with a stack, which buries real bugs in normal
  traffic. Use `CallRejected` for expected outcomes.
- **Declaring a signature without `parse`.** The declared type is a
  promise the client makes, not one the room can rely on. Declare the
  call with `call({ ... })` so the room checks its args, or give it a
  `parse`.
- **Taking checked args for valid ones.** Fields check types and
  ranges. A string that names an item or a number that indexes a list
  still needs checking against the room's state.
- **Retrying a call that changes state.** After a dropped connection the
  room may already have run it. Check with another call, such as
  `balance`, or make the call safe to repeat.
- **Waiting on a call for state everyone sees.** Change the entity in
  the handler and let every client get it from the state update; reply
  with what only the caller needs.
