Skip to main content

Live Play

Two players in a match, and a move arrives as it's made. A room of players, and each sees who's there. That's a wire: a place your game's players are on together, where what one sends, everyone on it gets at once, and where your game's function can speak as the server. It's the Arcadible SDK's wires, and the Function SDK's wires.

const wire = await arcadible.wires.join({ id });

wire.on("message", ({ data, from }) => draw(data, from));
wire.on("join", (member) => showOnline(member));
wire.on("leave", (member) => showAway(member));

await wire.send({ x: 3, y: 4 });

What a wire is, and isn't​

  • A wire relays, and keeps nothing. Everyone on it gets each message once, in one order. Whoever isn't on it at that moment never gets it.
  • So your game's state lives in values, and the wire says it changed. A player who joins, or comes back, reads the state, then listens.
  • Arcadible makes a wire's id, and your game hands it on as it came: in a link, in a value, in its function's answer.
  • Anyone with the id can join and send. A wire is as private as its id is kept.
  • Every message says who sent it, by Arcadible's word: server is true for your game's function, and from is the member who sent it otherwise. No player can send as another, or as the server.

Two ways to use one​

  • The function decides: for turns, parties, and anything with a result that matters. Players ask your game's function, which checks, stores, and announces on the wire. Games act only on the server's messages.
  • The players decide: for what's only seen, or a game that trusts its players: positions, cursors, emotes, ten or twenty times a second, with no server code. Each game decides what to believe from who sent it.

A game can use both on one wire: the function's messages for what's decided, players' for what's only seen, such as an emote or "thinking…".

Joining, and who's there​

wires.join(wire) puts the player on a wire someone made, anything with its id, and wires.open() on a new one. Each resolves with the wire once they're on it.

const wire = await arcadible.wires.join({ id });
for (const member of wire.members) showOnline(member);
wire.on("join", (member) => showOnline(member));
wire.on("leave", (member) => showAway(member));
  • wire.members is who's on now, this player included: each with their id in your game, their name, and whether they're a guest. The other player of two is wire.members.find((m) => m.id !== arcadible.players.primary?.id).
  • A member is a player, not a window. The same player on a phone and a laptop is one member.
  • Guests are members too, with no name: have a word of your own ready.
  • Show a name as text, never as HTML.

Sending​

wire.send(data) sends a message to everyone on the wire, this player included.

try {
await wire.send({ x, y });
} catch (err) {
// unavailable: off the wire for a moment. too_large: past the wire's size
}
  • data is anything JSON, up to 1 KB: a move, a position, an input. Not a whole world, which is a value.
  • Draw what comes back, not what you sent. Your own message arrives with everyone else's, in the wire's one order, so two players who press at once agree on who was first.
  • A player sends up to 20 messages a second. Past it, the SDK holds each message until the wire takes it, so a burst arrives late. For something that moves, send its latest state at a steady rate, and drop what's stale.
  • Check what a player sent before you use it. It's whatever their game sent, and a player can change their game.

When the connection drops​

A network drops, a phone sleeps. The SDK connects again by itself. Your game hears its own leave, then its own join:

const me = arcadible.players.primary;

wire.on("leave", (member) => {
if (member.id === me.id) status.textContent = "Reconnecting…";
else showAway(member);
});

wire.on("join", async (member) => {
if (member.id !== me.id) return showOnline(member);
// back on: what was sent meanwhile is gone, so read the state again
await refresh();
status.textContent = "";
});
  • Read your state again on your own join. A wire keeps nothing, so that's how your game catches up.
  • Who went and who came meanwhile come just before your own join, as a leave and a join each, so the same listeners hear every change in who's on.
  • Forgive a brief drop. Other players see this one leave and come back; wait a few seconds before treating a leave as gone for good. The same goes for a player who's just been seated: they come on a moment after your game hears they joined the match, so wait before showing them as away.
  • While Arcadible pauses your game, the wire stays on, and its listeners still run.

A turn-based match, on a function​

The function is the authority: it makes the match, seats players, checks each move, stores the board, and announces it. The wire carries only what both players may see. This builds on an invite to a match.

The function is named in arcadible.toml's [function] table:

arcadible.toml
[function]
main = "function/index.ts"

It opens a wire with the match, and announces each move it has checked:

import { players, values, wires, isArcadibleError } from "@arcadible/function-sdk";

type Match = { seats: string[]; wire: string };

export default {
async fetch(request: Request): Promise<Response> {
const me = players.primary(request);
if (me === null) return Response.json({ code: "no_player" }, { status: 403 });
const path = new URL(request.url).pathname;
const body = request.method === "POST" ? await request.json().catch(() => ({})) : {};

if (path === "/create") {
const match = crypto.randomUUID();
const wire = await wires.open();
await values.write([
// the seats and the wire's id: only the function reads these
{ scope: "server", key: `match/${match}`, value: { seats: [me.id], wire: wire.id }, revision: 0 },
// the board: every player may read it
{ scope: "game", key: `board/${match}`, value: newBoard(), revision: 0 },
]);
return Response.json({ match, wire: wire.id });
}

if (typeof body.match !== "string" || !/^[0-9a-f-]{36}$/.test(body.match)) {
return Response.json({ code: "invalid" }, { status: 400 });
}
const [record] = await values.read([{ scope: "server", key: `match/${body.match}` }]);
if (!record) return Response.json({ code: "no_match" }, { status: 404 });
const { seats, wire } = record.value as Match;

if (path === "/join") {
// seat them as in the invite's recipe, then say where to listen
if (!seats.includes(me.id)) {
if (seats.length >= 2) return Response.json({ code: "full" }, { status: 409 });
try {
await values.write([{ scope: "server", key: `match/${body.match}`, value: { seats: [...seats, me.id], wire }, revision: record.revision }]);
} catch (err) {
if (isArcadibleError(err, "conflict")) return Response.json({ code: "full" }, { status: 409 });
throw err;
}
}
return Response.json({ match: body.match, wire });
}

if (path === "/move") {
// check who's asking, then the move, then store, then announce
if (!seats.includes(me.id)) return Response.json({ code: "not_seated" }, { status: 403 });
const [board] = await values.read([{ scope: "game", key: `board/${body.match}` }]);
if (!board) return Response.json({ code: "no_match" }, { status: 404 });
const next = play(board.value, seats.indexOf(me.id), body.move); // your rules: null for a move that isn't allowed
if (next === null) return Response.json({ code: "not_allowed" }, { status: 409 });
let written;
try {
[written] = await values.write([{ scope: "game", key: `board/${body.match}`, value: next, revision: board.revision }]);
} catch (err) {
if (isArcadibleError(err, "conflict")) return Response.json({ code: "try_again" }, { status: 409 });
throw err;
}
await wires.send({ id: wire }, { board: next, revision: written.revision });
return Response.json({ board: next, revision: written.revision });
}

return Response.json({ code: "not_found" }, { status: 404 });
},
};

The game joins the wire its function names, reads the board, then listens:

const { functions, values, wires } = arcadible;
let revision = 0;

async function enter(match, wireId) {
const wire = await wires.join({ id: wireId });
const show = (board, at) => {
// an announcement carries the board's revision: skip what's already drawn
if (at <= revision) return;
revision = at;
draw(board);
};
const refresh = async () => {
const [board] = await values.read([{ scope: "game", key: `board/${match}` }]);
if (board) show(board.value, board.revision);
};
wire.on("message", ({ data, server }) => {
if (server) show(data.board, data.revision); // only the server's word moves a piece
});
wire.on("join", (member) => {
if (member.id === arcadible.players.primary?.id) void refresh(); // back after a drop
});
await refresh(); // read first, then listen
return wire;
}

async function move(match, cell) {
const res = await functions.fetch("/move", { method: "POST", body: JSON.stringify({ match, move: cell }) });
if (!res.ok) showRefused((await res.json()).code);
}
  • Players send nothing on the wire that changes the game. They ask the function, and act only on its messages, server: true.
  • The function checks the asker before it announces, always: who they are, that they sit in this match, and that the move is theirs to make. Every game on the wire believes the server.
  • The wire's id is kept in "server" values, and handed to a player only in the answer to /create or /join. Never in "game" values, which anyone can list.
  • The announcement carries the board's revision, so a game that read the board and then heard about the same move draws it once.
  • Send the whole state only when it's small. A message is 1 KB at most (Limits): announce the revision alone when the state is larger, and have each game read it, as it does on joining.
  • Secrets stay off the wire. A dealt hand or a hidden word stays in the function and "server" values; a player gets their own in the answer to their own request, and the wire can say "your hand changed".
  • A move is two trips: the game to its function, and the function to the wire. That's fine for turns and parties, and it replaces reading the board over and over to see if it changed.

A real-time room, with no function​

Players send to each other directly: positions, cursors, emotes. There's no server code, so there's no authority: each game decides what to believe from who sent it.

const { wires } = arcadible;
const me = arcadible.players.primary;
const others = new Map(); // by member id

async function enter(id) {
// the first player opens the room, and shares its id; the rest join it
const wire = id ? await wires.join({ id }) : await wires.open();

wire.on("message", ({ data, from, server }) => {
if (server || from === null || from.id === me.id) return; // not a player's, or my own
if (!isPosition(data)) return; // check it: it's whatever their game sent
others.set(from.id, { name: from.name, x: data.x, y: data.y });
});
wire.on("leave", (member) => {
if (member.id === me.id)
others.clear(); // dropped: start over when back
else others.delete(member.id);
});

// send where this player is, ten times a second, and only when it moved
let last = "";
setInterval(() => {
const now = JSON.stringify(position());
if (now === last) return;
last = now;
wire.send(position()).catch(() => undefined); // off for a moment: the next one will do
}, 100);
return wire;
}

const isPosition = (data) => Number.isFinite(data?.x) && Number.isFinite(data?.y);
  • from is the one thing a player can't fake. Key what you keep by from.id, so a player only ever moves themselves.
  • Send state, not steps: each message stands alone, so a dropped one costs nothing, and the last for each sender wins.
  • Stay within 20 messages a second for a player, and a wire's 200 a second together: ten players at full rate. For more, split players across wires.
  • A room's id can be public, such as in a link anyone may open: a lobby, cursors, an audience. Anyone there can send, so ignore what a sender isn't entitled to say.
  • Don't carry typed text between players over a wire: send fixed phrases, emoji, and your game's own data.
  • What must be true at the end, such as a result or a prize, still goes through a function. Players can't be trusted to agree on it.

What wires aren't for​

  • Fast action that needs less than a few hundredths of a second: a wire goes through Arcadible, which adds 30 to 80 ms.
  • Large state, which is a value's: a message is 1 KB.
  • Anything that must be kept, since a wire keeps nothing.
  • Voice and video.

Without the SDK, and off Arcadible​

  • Off Arcadible, open() and join() fail with unsupported. Offer your game's local play there.
  • Offline, open() fails with unavailable, join() waits and tries again until it's on, and a wire that was on drops, and comes back when the network does.
  • A wire that's over for this player says so with its end event: take them back to your lobby.

Trying it​

arc serve runs wires itself, with the same rules as Arcadible. Open your game in a second window as another player, http://localhost:4100/?player=Alex: two windows on one wire are two players, and your function's messages arrive in both. Try it under arc serve alone, not with --url, where a game with no function has no wires. To see what your game does when a connection drops, start it with --wires-drop 5, which cuts each connection five seconds after it comes on (its reference).

Checklist​

  • Keeps the game's state in values, and uses the wire to say it changed
  • Reads the state on joining, and again on its own join after a drop
  • Acts only on the server's messages (server: true) for what's decided
  • Checks a player's message before using it, and keys it by from.id
  • Keeps a wire's id where only those meant to join can find it, and no secret on the wire
  • Sends at a steady rate, within 20 messages a second, each up to 1 KB
  • Says so, and plays on, when a wire can't be reached

Next steps​