Skip to main content

Saving data from the server

A deck's multiplayer server keeps its state in memory, and that memory goes when the session ends. session.storage is what outlives it. It is the same store the deck's clients see through Store, with the same JSON values and the same limits:

const match = { over: false }; // this session's game, kept by the server

export default {
async onPlayerJoin(session, player) {
const key = `wins:${player.userId}`;
const { [key]: wins = 0 } = await session.storage.deck.get([key]);
session.send(player.playerId, { type: "wins", wins });
},

async onMessage(session, player, data) {
if (!data || typeof data !== "object" || data.type !== "move") return;
if (match.over) return;
// Your rules apply the move to the server's own state and return the
// winner only on the move that ends the match.
const winner = applyMove(match, player, data);
if (!winner) return;
match.over = true; // count this match once
const wins = await session.storage.deck.increment(`wins:${winner.userId}`);
session.broadcast({ type: "won", userId: winner.userId, wins });
},

async onShutdown(session) {
await session.storage.deck.set({ lastGame: { endedAt: Date.now() } });
},
};
  • session.storage.deck is shared by everyone playing.
  • session.storage.user(userId) is one player's public data, the same keys that player reads and writes as Store.me.
  • session.storage.board(name) is a leaderboard.

Each scope has get(keys), set(values), remove(keys), increment(key, delta?) and list({ prefix, limit, cursor }), which work as they do on Store, and the root and its buckets also support the atomic save API. A board has submit(userId, score), top(limit?) and get(userId).

Three differences follow from a session server not being a player:

  • It owns deck scope. Once a deck has a published server, clients read that data but no longer write it, which is what lets you keep authoritative state players cannot forge. Saving the deck again without a server entry hands it back, but only when save-deck runs from the project that published the server (its .castle/published-server-bundle.json records that publish); otherwise the old server stays published.
  • It has no self. There is no storage.me, and a user scope or a board submission must name the player: session.storage.user(player.userId), session.storage.board("high").submit(player.userId, score). Castle does not check that the id belongs to a real player, so use only the userId of a player Castle gave your callbacks, never one a client sends.
  • It never sees private. Store.private is the player's alone, and session.storage has no way to reach it.

A server's writes are not batched the way a client's are: each set or remove is sent at once and resolves when the platform has it. Each request commits as a unit, but a set with more than 32 keys, or more than 316 KB once encoded, goes out as several requests, so it can land partly. A value is encoded twice on the way, so one full of quotes or backslashes can be refused even under the 256 KB value limit. remove splits by key count only. A session has its own rate limit, 30 calls and 2 MB a second, shared by every player in it.

Check a message's shape before reading its fields: a client can send anything, and a handler that throws on null.type ends the session.

Don't await storage in onStart: the session is not ready for it yet, so a call there can fail or stall. Read on the first join or message instead. A reconnect (with the same playerId) usually runs onPlayerJoin again, so a counter bumped on join counts reconnects too; one that replaces a socket still attached may not, so don't rely on it either way.

onShutdown is awaited, so a write you await there gets its chance to land, but it can still be refused (by a rate limit, for one), and onShutdown runs only on a clean stop. An out-of-memory kill or a host failing sends no shutdown at all, so save as things change and treat onShutdown as the last chance, not the plan.

Limits​

Everything in the Store limits applies: keys up to 128 bytes, values up to 256 KB of JSON, 32 keys in one get, and the per-player and deck allowances. A session server's rate is its own, 30 calls and 2 MB a second per session, separate from a client's 20 calls and 512 KB, and both count toward the deck's shared 500 calls and 8 MB a second. A list page holds 100 entries unless you pass a limit, and at most 1,000 or 1 MB; top returns 10 scores unless you pass a limit, and at most 100. A board name is at most 128 bytes.

Atomic saves from the server​

The atomic save API works from the server too, with two rules: a target in user scope must name its player, and private targets are refused. While keys written with set exist under a prefix, it is refused with CAULDRON_STORAGE_LEGACY_DATA_PRESENT; moving those keys over takes a transaction whose change replaces the prefix's whole contents.

Testing with castle-web serve​

During castle-web serve, ordinary storage calls go to the real deck's storage, so they need a published deck: an unpublished project gets CAULDRON_STORAGE_UNAVAILABLE. Atomic saves are different: they live in the serve's memory, are lost when serve exits, and are kept apart from ordinary keys, so a get never sees a key a transaction wrote, and the other way round.

A leaderboard players can't fake​

On a deck with a published server, only the server submits scores; a client submit is refused with CAULDRON_STORAGE_FORBIDDEN. Work the score out on the server and submit it for the player. Clients show the board with Store.board("high").top(10) and Store.board("high").get().

const runs = new Map(); // playerId -> the server's record of a run in progress

export default {
async onMessage(session, player, data) {
if (!data || typeof data !== "object") return;
if (data.type === "start") {
runs.set(player.playerId, startRun());
return;
}
const run = runs.get(player.playerId);
if (!run) return;
stepRun(run, data); // your rules apply the input to the server's state
if (!run.finished) return;
runs.delete(player.playerId); // this run counts once
const board = session.storage.board("high");
const best = await board.get(player.userId);
if (!best || run.score > best.score) await board.submit(player.userId, run.score);
},
};

submit replaces the player's score rather than keeping the higher one, and this read-then-submit is not atomic: if one player finishes in two sessions at the same moment, the lower score can land last. That is rare enough to accept for most games.

Moving a game that used client submits over to a server keeps the scores already on the board, forged ones included. Use a new board name for the server's scores.

Per-player records​

Anything the server must be able to trust about a player, such as a coin balance, a rating or an unlock, goes in deck scope under a key named after them. Every player can read deck scope, so nothing secret goes there. A player can write their own user(userId) keys from a client, so those are only for things they are allowed to set, such as a display name or an outfit.

// The deck's coins: fixed ids, so every room has the same ones.
const COINS = new Map([["c1", { x: 4, y: 2 }], ["c2", { x: 9, y: 7 }]]);

export default {
async onMessage(session, player, data) {
if (!data || typeof data !== "object" || data.type !== "collect") return;
const coin = COINS.get(data.coinId);
// The player must be standing on it, by the server's own record of
// where they are.
if (!coin || !isTouching(positionOf(player), coin)) return;
// Each coin pays each player once, ever: whatever room they are in,
// only their first claim gets 1.
const claims = await session.storage.deck.increment(
`coin:${player.userId}:${data.coinId}`
);
if (claims !== 1) return;
const total = await session.storage.deck.increment(`coins:${player.userId}`, 5);
session.send(player.playerId, { type: "coins", coins: total });
},
};

The claim key, one per player and coin, is what stops a coin paying out twice, in another room or after a restart. A reward that should repeat needs an id from progress the server tracks and a player cannot reset, such as a level they reached. If the credit fails after the claim, the coin is lost rather than paid twice. Each claim is a deck-scope key, so this suits a handful of rewards per player, not one a second.

Deck-scope keys count against the deck's shared allowance (500 MB and 1,000,000 keys, see the Store limits), not the player's, so keep one key or a few per player rather than one per event.