Skip to main content

Server Code

Some of what a game does can't be left to the player's browser: a score that goes on a leaderboard, a move in a match, a call to an API with a key of yours. That's server code, and on Arcadible it runs in one of two places: your game's function, which Arcadible runs beside each build, or a server of your own. Either way, each request carries proof of which player sent it.

arcadible.toml
[function]
main = "function/index.ts"
function/index.ts
import { players } from "@arcadible/function-sdk";

export default {
async fetch(request: Request): Promise<Response> {
const me = players.primary(request); // who sent it, by Arcadible's word
return Response.json({ roll: 1 + Math.floor(Math.random() * 6), for: me?.id ?? null });
},
};
// in your game
const res = await arcadible.functions.fetch("/roll");
const { roll } = await res.json();

A function, or a server of your own​

Start with a function. It's the [function] table in arcadible.toml, which arc deploy bundles and ships with your build. Your game calls it with arcadible.functions, and it calls Arcadible with the Function SDK:

  • Nothing to run or set up: no host, no key, no address to configure.
  • Each request is checked before your code runs, so players.primary(request) is who sent it.
  • It's the same version as your build, since each build has its own function.
  • It reads and writes your game's values, reads players' names, and speaks on wires as the server.

Use a server of your own when you already run one, or need what a function doesn't give: more work than a request may do (Limits), or a database or service of your own. Your game lists it in [client] server_origins, sends it a ticket, and your server checks the ticket with the Server SDK (A server of your own).

A game can have both: the same values are reached from each, on the same channel.

Who sent a request​

A request to your server code carries a ticket: proof, signed by Arcadible, of the game, the build, and the player. Your game never reads it, and a player can't make one for someone else.

  • To your function, functions.fetch sends the ticket for you, and gets a new one when it runs out. Arcadible checks it before your function's code runs, and a request without a good one never reaches it.
  • To a server of your own, your game gets one with arcadible.tickets.get(server), and your server checks it with tickets.check.

Either way, the player is { id, guest }: the same id your game's own arcadible.players.primary has, and guest for someone playing logged out. A ticket carries no name: players.read gives one.

  • A guest has an id too, which proves the same device, and nothing more. Check guest before giving what should take an account, such as a place on a leaderboard.
  • The player can be null: a guest whose device has no id yet. Refuse what needs to know who's asking.
  • Check what a player sent before you use it. Who sent it is Arcadible's word; what they sent is whatever their game sent, and a player can change their game.

A score, checked by a function​

A puzzle game's leaderboard: the game sends the moves that solved the puzzle, the function replays them, and only then puts the score on the board. The board is a "game" value, which every player can read and only server code can write.

The function:

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

export default {
async fetch(request: Request): Promise<Response> {
if (request.method !== "POST" || new URL(request.url).pathname !== "/score") {
return new Response(null, { status: 404 });
}
const me = players.primary(request);
if (me === null || me.guest) return new Response("Log in to be on the board", { status: 403 });

const body = await request.json().catch(() => ({}));
const score = replay(body.moves); // your rules: the score these moves make, or null when they don't solve it
if (score === null) return new Response("Not a solution", { status: 422 });

// read, then write with the revision read, so two scores landing at once both count
for (let i = 0; i < 3; i++) {
const [board] = await values.read([{ scope: "game", key: "leaderboard" }]);
const next = rank(board?.value ?? [], { player: { id: me.id }, score }); // your rules: the top ten
try {
await values.write([{ scope: "game", key: "leaderboard", value: next, revision: board?.revision ?? 0 }]);
return Response.json({ leaderboard: next });
} catch (err) {
if (!isArcadibleError(err) || !err.conflicts) throw err; // conflicts: someone wrote first, so read again
}
}
return new Response("Try again", { status: 503 });
},
};

The game:

async function submit(moves) {
try {
const res = await arcadible.functions.fetch("/score", {
method: "POST",
body: JSON.stringify({ moves }),
});
if (!res.ok) return showRefused(await res.text()); // your function's own answer
showBoard((await res.json()).leaderboard);
} catch (err) {
// Arcadible's refusal: the request never reached your function
showUnavailable(err.retry !== "no"); // "yes" or "later": trying again may help
}
}
  • Your function's answers are yours: any status, any body, and functions.fetch resolves with them, a 404 or a 500 included.
  • functions.fetch rejects only when Arcadible refused the request, such as offline or with the function paused, with a code and a retry (Codes). Follow retry for a code you don't handle, and play on without the function where you can.
  • Paths are your function's, from its root: "/score". Route them as you like.
  • Keep what only your function should know in "server" values, such as a puzzle's answer: your game can't read them. What's in "game" values, any player can.
  • The players on the board are kept as { id }: players.read gives their names when you show them, since a name can change.

For a match between players, announced as each move is checked, see Live Play.

Secrets, and the hosts a function reaches​

A function reaches only Arcadible, through the Function SDK, until its table names more. To call another API with a key of yours, name the host in outbound_hosts, and the key as a secret:

arcadible.toml
[function]
main = "function/index.ts"
outbound_hosts = ["api.example.com"]
secrets = ["EXAMPLE_KEY"]
export default {
async fetch(request: Request, env: { EXAMPLE_KEY?: string }): Promise<Response> {
return fetch("https://api.example.com/rate", {
headers: { Authorization: `Bearer ${env.EXAMPLE_KEY}` },
});
},
};
  • The manifest names a secret; its value is set in Studio, on the game's Function tab, for production and staging apart. A value is set, replaced, or removed there, and never shown again.
  • Your function reads it from env, the second argument of fetch, by its name.
  • A value changes with no release, and reaches your function within a minute. arc deploy warns of a secret with no value on the channel it deploys to, and your function reads nothing for it until it's set.
  • A fetch to a host outbound_hosts doesn't name isn't sent, and answers 403 (the Function SDK).
  • Only arc deploy changes outbound_hosts, since it's where your secrets may go: a release from GitHub must keep it as it is.
  • Keep your function's code outside deploy_dir, where anyone can download what's there. Its bundle is never served.

Studio's Function tab​

Your game's Function tab in Arcadible Studio shows it on production or staging:

  • The version that's live, and the hosts it may reach.
  • Pause and Resume: a paused function answers no requests on that channel until you resume it. Your game's requests are refused meanwhile, with a retry that says to wait.
  • Secrets, as above.
  • Its requests this month (Limits).
  • Logs, which follow live: each request your function was given, with what it logged and threw.

A server of your own​

List it in arcadible.toml, by its origin:

arcadible.toml
[client]
server_origins = ["https://api.example.com"]

Your game gets a ticket for it, and sends it as it connects:

const ticket = await arcadible.tickets.get("https://api.example.com");
const res = await fetch("https://api.example.com/score", {
method: "POST",
headers: { Authorization: `Bearer ${ticket}` },
body: JSON.stringify({ moves }),
});

Your server checks it with the Server SDK, @arcadible/server-sdk:

import { tickets, isArcadibleError } from "@arcadible/server-sdk";

async function who(request: Request) {
const bearer = request.headers.get("Authorization")?.replace(/^Bearer /, "") ?? "";
try {
return await tickets.check(bearer, {
server: "https://api.example.com",
game: "8f36cdfb-adad-4f37-b543-63cf1b401455", // your game's id
channel: "production",
});
} catch (err) {
if (isArcadibleError(err) && err.retry !== "yes") return null; // not good: answer 401, and the game gets another
throw err; // Arcadible's keys couldn't be read: try again
}
}
  • Call tickets.get each time you need one. It gives the same ticket while it's good, and a new one once it isn't. Send it in an Authorization header or a WebSocket's first message, never in a URL.
  • A ticket lasts 10 minutes. Check it as your game connects, then keep a session of your own.
  • channel is required, so a production server never takes a staging build's tickets by leaving it out. Run one server for each, or name both.
  • Checking a ticket needs no key. Reading players' names, and your game's values, takes one: make it on the game's Server tab in Studio, where it's shown once, and give it to your server as ARCADIBLE_KEY (Including it). A key is for one channel. Keep it on your server.
  • Your server sends CORS headers for any origin ending in .arcadible.io, since every build has its own.
  • One server answers every build, so it hears from older versions too: the ticket's build says which.
  • Only arc deploy changes server_origins, as for outbound_hosts.
  • Read players.deleted on a schedule, and delete what your server keeps for each player who deleted their account: nothing else tells your server.

Channels and versions​

  • Production and staging are apart: each has its own values, secrets, keys, and pause. A prerelease's function reaches staging's values, so trying it on staging leaves players' alone.
  • Each build has its own function, so a game and its function are always the same version. When a newer build takes the channel, the older one's function answers for a day more, for players still on it, then refuses: have the player reload.

Limits​

The full list is in Limits. The ones you'll design around:

  • A request's body: 1 MB. Keep what's larger in values.
  • A request's work: 50 ms of CPU, and 20 requests of its own, calls through the Function SDK included.
  • A function's requests: about 600 a minute for a game on each channel, 200,000 a day for a game, and 1 million a month for every game of your account together. Past the day's or the month's, the function is paused until it turns: have your game go on without it.
  • A bundle: 1 MB, as arc build makes it.
  • Calls to Arcadible: 600 a minute for a game on each channel, its keys and its function together.

A request refused before your code runs isn't counted.

Trying it​

arc serve runs your function beside your game, as Arcadible would, with its own tickets and values:

EXAMPLE_KEY=… arc serve --player Sam
  • Your function answers at the address it prints under Function, and functions.fetch reaches it the same way (its reference).
  • A secret's value is the one in arc serve's own environment.
  • Another player is a second window at the address under As another player, such as http://localhost:4100/?player=Kim.
  • A server of your own on your machine gets tickets without being listed: start it with the address under For your server, ARCADIBLE_SERVE=http://localhost:4100 node server.js, and it takes arc serve's tickets, with no key (the Server SDK under arc serve).
  • What isn't counted locally isn't refused there: the limits on how often your code is called, and a request's CPU. Try those on staging.

Checklist​

  • Uses a function unless it needs a server of its own
  • Asks who sent a request (players.primary(request), or tickets.check) before it acts, and refuses null
  • Checks guest before giving what should take an account
  • Checks what a player sent, and keeps what's decided in values only server code writes
  • Writes a value two requests may change with the revision it read
  • Says so, and plays on, when its server code is refused, following retry
  • Keeps keys and secrets out of the build: secrets set in Studio, a key on the server
  • Sets each secret, and makes each key, on both channels it deploys to

Next steps​