ARCANUM
Guide ยท server

The server

A game server is one class derived from server::Game. This page teaches it one concept at a time, from the first callback to every option, and ends with a reference of every public member.

A game is a class

Everything a server needs (the table of entities, who sees what, reading what clients send, applying their controls, writing the tick message to each of them) is done by server::Game. You derive from it and override the callbacks you care about. All of them are optional.

Here is the whole meadow server, the game this guide builds on. It was introduced on the Start page; read it again now, because the rest of this page is a tour of its parts.

examples/meadow/World.h
#pragma once
#include <aether/server.h>

#include "meadow/Shared.h"

using namespace aether;
using meadow::Chat;
using meadow::Purse;
using meadow::Said;

class World : public server::Game {
public:
    explicit World(ecs::Store& store) : Game({.store = &store, .contract = meadow::contract}) {}

    void onStart() override {
        persist<Purse>().key(&Purse::owner);                 // saved, filed under its owner
        view<Walker>().spatial("x", "y");                    // seen by players nearby
        view<Purse>().ownerOnly();                           // seen by its owner only
        inputs().apply<Move>(step);                          // what a held Move does
        on<Chat>([this](Player& p, const Chat& c) {          // a message from a client
            broadcast(Said{String<16>(p.query("name", "anon")), c.text});
        });
    }

    void onJoin(Player& p) override {
        const std::string name = p.query("name", "anon");
        p.entity = spawn(Walker{0, 0, 60},
                         load<Purse>(name).value_or(Purse{String<16>(name), 0}));
    }

    void update(float) override {
        for (Player& p : players()) get<Purse>(p.entity).gold += 1;      // a coin a tick
    }
};

A server.cpp hands the class to an App, which owns the sockets and the threads and ticks the game 20 times a second here:

examples/meadow/server.cpp
#include <cstdio>
#include <cstdlib>

#include "meadow/World.h"

int main(int argc, char** argv) {
    ecs::FileStore store("meadow.db");
    World world(store);
    server::App app(world, {.tickRate = 20});
    const std::uint16_t port = argc > 1 ? std::atoi(argv[1]) : 9000;
    return app.listen(port, [](std::uint16_t p) { std::printf("meadow on %u\n", p); }) ? 0 : 1;
}

Notice that onStart is the only place that declares things (views, the held input, message handlers, what is saved). The other callbacks run again and again as players come and go and as ticks pass.

The callbacks

You writeIt is calledDefault
void onStart()Once, when the world starts (before the first tick). Declare views, the held input, message handlers and saved rows here. The views and the persist declarations take effect when it returns.nothing
void onJoin(Player&)A client has connected and (if you saved its rows) they have been read. Set p.entity. Throwing refuses that one client, see Refusing a client.nothing: the player has no entity
void onLeave(Player&)A client left. Its entity is still alive; the game destroys it after you return unless you set p.entity = ecs::kNoEntity.nothing
void update(float dt)Every tick, after the held inputs and moves were applied. dt is 1 / tickRate seconds.nothing
std::string playerKey(Player&)When a client connects, only if some saved row is declared ofPlayer(). See Saving.empty: nothing is fetched early
void receive(Player&), void sendState()Once per player per tick (reading what it sent), and once per tick (writing every client its tick message). Override to take a step by hand; see One tick, in order.the SDK's chain
Trap. update takes a float. void update(double dt) override does not compile, but void update(double dt) without override compiles and is never called. Always write override.

What the game does for you, so you do not write it: it reads what each client sent and hands it to the right piece; it tells Interest the tick rate; it always sends the welcome (so session.me(), tickRate() and inputRate() work on the client); it keeps the list of players; it destroys a player's entity when the player leaves; and it contains the failures of a single client so that the other players are not affected.

One tick, in order

Knowing the order answers most "why did that happen a tick late" questions. One tick of a Game is, exactly:

  1. Answers of slow reads. Saved rows that a store or a storage answered since the last tick are delivered (callbacks of load<Row>(key, fn), clients held for their rows now join).
  2. Players are synchronised (a player whose entity you reassigned is moved to the new one).
  3. Receive. receive(p) runs for every player: it reads up to Options::rate.perTick messages (16 by default) of that client. Plain messages are handled here, so an on<Chat> handler runs in this step. Held inputs and moves are only queued.
  4. Phase "input". Functions you gave to post() run first, then inputs().run() applies the queued held inputs and moves, in order, and sets each client's acknowledgement.
  5. Phase "simulate". Your update(dt). (Phases you add with schedule().phase("name") come after it, in the order you declared them.)
  6. Commit. The registry compares every row with the previous commit; this is what views read.
  7. Phase "send". Players are synchronised again, then sendState() writes every client its tick message.
  8. After the send. Messages you queued with send/broadcast are written (so they arrive after the state of the tick they were sent in), then changed rows are handed to the store.

Two consequences follow, and both are used later. A plain message is handled in step 3, before the controls that arrived in the same batch are applied in step 4, so order-sensitive actions belong in the move stream (below), not in plain messages. And a message you send in update or in a handler reaches the client after the tick message carrying the change it is about (view rows that you send only every k ticks may still show the change a few ticks after the message).

Trap. A handler for a message or a move that throws loses that one message and the tick goes on. update() is different: an exception that leaves a schedule system aborts the rest of that tick (no commit, no send, no saving this tick), is reported to Options::onError (stderr by default), and the world carries on with the next tick. Catch inside update what you can recover from.

You can add your own systems to the schedule (schedule().system("name", "simulate", fn)) when update grows too large; ecs.html documents the schedule.

What runs where

An App runs three threads: the server layer (accepts connections and reads what clients send), a network thread (the per-connection rate limiter, which runs before anything of yours, and writing bytes to sockets), and the world thread, which ticks your game. Every callback on this page (onStart, onJoin, onLeave, update, every handler, every storage callback) runs on the world thread, one at a time, so game code needs no locks.

Anything that must touch the game from another thread (a timer, an admin console, a test) hands the work to the world thread with post():

// any thread
void announce(server::Game& game, std::string text) {
    game.post([&game, text] {                       // runs on the world thread, at the start of the next tick
        game.broadcast(Said{String<16>("server"), String<80>(text)});
    });
}

Notice that post is the only Game member that is safe to call from another thread. Functions run in the order they were posted, as the first step of the "input" phase. Anything still posted when the server stops is discarded, not run.

Players

A Player is the server's record of one connected client. players() lists them; you can iterate it, ask its size, or look one up:

struct Seat { int chats = 0; };                       // anything default-constructible: yours, one type per game

class Lobby : public server::Game {
public:
    void onStart() override {
        view<Walker>().global();
        on<Chat>([this](Player& p, const Chat& c) {
            if (++p.user<Seat>().chats > 100) p.kick("too chatty");          // its onClose gets code 4001
            else broadcast(Said{String<16>(p.query("name", "anon")), c.text});
        });
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); }
    void update(float) override {
        for (Player& p : players())                          // every connected, joined player
            send(p, Said{String<16>("lobby"), String<80>("players: " + std::to_string(players().size()))});
    }
};

Notice three things. p.query("name", "anon") reads ?name=... from the URL the client connected with (over GNS the same text arrives in the hello message), so connection-time data such as a name or a class needs no extra message. p.user<Seat>() is your own per-player struct, made on first use; asking for a different type later throws. And send(p, msg) and broadcast(msg) do not write at once: they queue, and go out after this tick's state (step 8).

What a Player has

MemberMeaning
Client& clientThe connection. p.client.send(msg) writes immediately (not queued); p.client.disconnect(code, reason) closes it with your own code.
ecs::Entity entityThe player's own entity: what its client's me() is. Set it in onJoin. Default ecs::kNoEntity.
query(key, fallback = "")Value of ?key=value of the connect URL, or fallback.
user<T>()Your struct for this player.
send(msg)Queue a message to this player (same as Game::send(p, msg)).
show(e) / hide(e)This player alone sees entity e in every view, wherever it is, until hide(e). See Views.
focus(e) / unfocus(e)This player cares about e: it is sent entity by entity before the crowd under a budget. See Network.
link()A copy of the measured health of the connection (round trip, loss, capacity, backlog ...) for your rules.
crowdDelay() / focusDelay()How long the longest-waiting crowd cell / focused entity waited in the last send, in milliseconds.
kick(reason)End the connection after what is queued, telling the client why (close code 4001).
dropped()Counters of this client's messages that were dropped instead of handled.
Tip. p.show(e) and p.focus(e) called in onJoin, before the client is attached, are remembered and applied when it is attached. focus and show change nothing for other players.

A player is added to players() just before onJoin and removed after onLeave. A client that is still waiting for its saved rows (Saving) is not in the list yet.

Creating and changing entities

spawn makes an entity with the rows you give it, and returns its ecs::Entity. get<Row>(e) gives the row back as the struct itself, writable in place:

class Garden : public server::Game {
public:
    void onStart() override {
        view<Walker>().spatial("x", "y");
        view<Mine>().ownerOnly();
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}, Mine{0}); }
    void update(float dt) override {
        for (Player& p : players()) {
            Mine& m = get<Mine>(p.entity);                     // writable: change it in place, nothing to write back
            m.dashCd = std::max(0.0, m.dashCd - dt);
            const Walker& w = get<Walker>(p.entity, READONLY);   // only looking: a write does not compile
            if (w.x > 1000) set(p.entity, Walker{0, w.y, w.speed});   // assign a whole row
        }
    }
};

Notice that nothing says "I changed this row". The registry finds changes by comparing at the commit, so a row you only read is never sent and never saved. The reference you get from get is valid until an entity gains or loses that component or is destroyed, so do not keep it past the tick. get and set throw std::logic_error (in every build) if the entity is dead or has no such row.

What a struct is (a view row, a local component that stays on the server, a saved row) is explained on Data; who sees which rows on Views. Two things belong here because they are about the Game:

  • view<Row>() only in onStart. The builder is built when onStart returns. Calling it later (in onJoin, update or a handler) throws std::logic_error: "the views are built when onStart() returns, so a view cannot be added later ... Define every view in onStart()".
  • A discontinuity is a snap. A portal or a respawn that moves an entity far in one tick should not be interpolated across by clients: snap(e, row) (or set then snap(e)) marks the change, and clients that see e read it as view.snapped(e).

Held inputs

Most real-time games have controls that are held: the walker's direction, the steering of a car. The SDK treats that as state, not as a stream of events: the client samples its controls, cuts them into fixed steps of time, and sends them. The server applies each step with a function of yours and acknowledges the last one, which is what lets a client predict. The client half is on Client; this is the server half.

The function is registered once in onStart. In meadow it is the shared step, the same function the client runs when it predicts:

class Walkers : public server::Game {
public:
    void onStart() override {
        view<Walker>().spatial("x", "y");
        inputs().apply<Move>(step);                                         // void step(Walker&, const Move&, float dt)
        inputs().valid<Move>([](const Move& m) { return std::isfinite(m.dx) && std::isfinite(m.dy); });
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); }
};

Notice what the step receives: the walker's own row, the input, and dt. The server loads the player's Walker, calls step, and writes the row back. A step is skipped (nothing happens) if the player has no entity, the entity is dead, or it lacks the row.

The forms of a step

FormWhat it gets
void(Row&, const Input&) and void(Row&, const Input&, float dt)The player's row of that struct; written back.
void(Hero&, Mine&, const Input&[, float dt])Several rows of the entity (each a distinct struct). With one row it is always written back; with several, only the rows the function changed (so an owner-only row that did not change is not re-sent). The input is skipped if the entity lacks any of the rows.
void(ecs::Entity, const Input&[, float dt]) and void(Client&, ecs::Entity, const Input&[, float dt])The entity (and the client) for code that does its own lookups. The entity form is also called with a dead or kNoEntity id: check it.

dt is 1 / rate seconds, where rate is the input rate (default: the tick rate). A function that returns a value does not compile ("a handler returns nothing: send the result as a message: send(player, Result{...}) (or change a row the client reads)").

One held input per game. Registering a second input struct with apply throws std::logic_error: "server::Inputs: A and B are both the held input (kind 0), and a game has one. If B is an act, register it with action<B>(fn)". Registering the same struct again replaces its function. A one-shot move is not the held input: it is on<X>, below.

Validating

inputs().valid<Move>(fn) drops any input for which fn returns false, before it is queued; it is counted in inputs().dropped(client). It may be called before or after the struct is registered with apply/on. A valid<X> whose X is never registered makes the game fail to start with std::logic_error: "valid<X>(): X is not registered as the held input or an act, so nothing would be checked".

Validate fields the shared function cannot make safe (NaN, an index that must be in range). The shared function itself should enforce the rules of the game (speed, collisions): the server never accepts a position, only intent for a slice of time.

When inputs arrive faster or slower than ticks: InputPolicy

Clients sample at their frame rate, ticks come at the tick rate, and the network adds jitter, so the number of held inputs that arrive for one tick varies. InputPolicy decides what the server does about it. Every field is optional; set them as Game({.inputs = {.rate = 60}}) (designated initialisers must follow declaration order).

FieldType, defaultMeaning
rateint, 0Input steps per second; each step is applied with dt = 1 / rate. 0 means the tick rate. Announced to clients in the welcome (session.inputRate()). Must be >= 0.
maxPerTickint, 0Held inputs applied per client per tick. 0 means ceil(rate / tickRate) + 1: one more than the expected number, so two frames landing in one tick cost nothing. Must be >= 0.
excessExcess, WaitWhat to do with held inputs over maxPerTick. Wait: they stay queued for the next ticks (the queue keeps the newest queue; when it is full the oldest is dropped and counted). Drop: they are consumed and acknowledged without being applied.
queueint, 0Held inputs kept per client. 0 means 2 * maxPerTick. Must be >= 0.
starvedStarved, SkipWhat to do in a tick where the client (which has sent at least one held input) has none to apply. Skip: nothing, the entity does not move. Repeat: apply the last held input again for repeatTicks ticks, then a neutral (all-zero) one: for things with momentum. Neutral: apply a neutral one at once. A starved tick applies max(1, round(rate / tickRate)) steps. The acknowledgement never moves for these steps.
repeatTicksint, 6How many starved ticks Repeat repeats the last input. Must be >= 0.
maxActionsint, 16One-shot moves (acts) applied per client per tick; the rest wait. Moves are never dropped by the time budget. Must be >= 1.
typestd::uint8_t, kInputType (8)The message type byte that input batches arrive under; Inputs::handle ignores other types. Leave it: 8 is what client::Session sends.

In numbers: at tick rate 20 and input rate 20, maxPerTick is 2 and queue is 4; at input rate 60 they are 4 and 8. A value below zero (or maxActions below 1) makes the Game constructor throw std::invalid_argument: "server::Inputs: rate, maxPerTick, queue, repeatTicks must be >= 0 and maxActions >= 1".

How the stream is ordered. Held inputs and moves share one sequence per connection and are applied in that order; a held input that has to wait holds back the moves behind it. A message whose sequence is not newer than the last received (compared with wrap-around) is ignored and counted. An unknown kind, or a batch cut short, drops the rest of that batch.

You can watch a client's queue: inputs().applied(client) (the acknowledged sequence), queued(client), dropped(client). A handler that throws loses that one input, the others and the tick carry on, and the error goes to inputs().onError(fn) or to stderr as "aether: an input handler (client N) threw: ...".

Messages and moves: one verb, on<X>

A client talks to the server in two other ways besides held inputs. It can send a message (session.send(Chat{..})): handled when it arrives, any size up to the connection limit, no promise about ordering with inputs. Or it can perform a move (me.act(Dash{..})): a one-shot action that travels in the input stream, in order with the held inputs, and that the client may predict. You write one handler for both:

class Arena : public server::Game {
public:
    void onStart() override {
        view<Walker>().spatial("x", "y");
        inputs().apply<Move>(step);
        on<Chat>([this](Player& p, const Chat& c) {                // (Player&, const X&)
            broadcast(Said{String<16>(p.query("name", "anon")), c.text});
        }).limit(2, 1s);                                                // at most 2 a second per client
        on<Jump>([this](ecs::Entity e, const Jump&, float dt) {      // ([Client&,] Entity, const X&[, float])
            get<Walker>(e).y += 1;                                     // dt is 0: a one-shot move is not a step
        });
        on<Dash>([](Walker& w, const Dash& d) {                   // (Row&..., const X&[, float]): the rows of the player's entity
            w.x += d.dx * 5; w.y += d.dy * 5;
        });
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); }
};

Notice that the handler does not say which way the struct arrived. on<X> registers the struct as a message and, if it packs to at most 255 bytes, also as a move. A bigger struct can only be a message; me.act of it throws on the client.

Handler formCalled with
(Player& p, const X&)The player. No dt. Message path: only for a player that has joined.
(Row&, ..., const X&[, float dt])The rows of the player's entity, written back (as for held inputs). Skipped for a dead entity.
([Client&,] ecs::Entity, const X&[, float dt])The player's entity (can be dead or kNoEntity: check it).

dt is always 0 here. The handler returns nothing: a value is a compile error ("a handler returns nothing: send the result as a message: send(player, Result{...}) ..."). The result of a command is a message the server chooses to send, or a change in a row the client reads; there is no request and response. on<X> also refuses a struct that is not plain ("X is not a plain struct (public members, no constructors)").

Limiting a message

on<X>(fn) returns a MessageHandle, and .limit(count, per) on it caps how many of that message one client may send: a bucket of count that refills over per. count must be at least 1 and per at least 1 ms, otherwise it throws std::invalid_argument "server::Messages::limit<M>(count, per): both must be positive". What is over the limit is dropped and counted in p.dropped().perType, and the connection is warned and finally closed:

  1. the first message over the limit in a run is dropped and the client is sent a warning (its session.onWarning gets "too many Chat messages: the limit is 2 per 1000 ms; what is over it is dropped");
  2. the second inside 2 seconds is dropped silently;
  3. the third closes the connection with code 4290 and the reason "closed for sending too many Chat messages".

A message that passes ends the run. The limit applies to the message form of X. A move of the same struct travels in the input stream and is limited by maxActions instead.

When something goes wrong

SituationWhat happens
A handler throwsThat one message is lost, the tick carries on. stderr: "aether: the handler of message type N (client C) threw: ..." (for a move: "aether: an input handler (client C) threw: ..."). messages().onError(fn) / inputs().onError(fn) replace the stderr line; failed() counts them.
The body has the wrong size for its structDropped and counted in messages().dropped().
A type the server has no handler forSilently ignored by the receive chain. (On the client, session.send of such a struct throws once the id table has arrived.)
Two structs with the same unqualified name (in two namespaces)on<> throws std::logic_error naming both. Rename one.
A message type below 16Those belong to Aether: std::logic_error "message types below 16 are aether's".
A message larger than Options::maxMessageBytes (4096)The connection is closed (server layer; see Network).

Sending

send(player, msg) and broadcast(msg) are queued and written after the state of the tick (step 8), in the order you called them; a queued message to a client that has left is dropped. If a client stops reading and its output buffer is full, its messages wait for the next flush, in order, up to one buffer's worth per client; beyond that they are dropped. A message that is too big for the buffer is dropped. All of these are counted in players().dropped() (a total for the game, not the per-client inbound counters).

A move the server may refuse

A handler returns nothing, so how does a move get refused? By changing nothing. The rule is a function of the rows, written once in the shared header and used by both sides: the client predicts it with its own rows, the server runs the same function. If both refuse (the cooldown is not over), neither changes anything and no correction happens.

examples/meadow/Shared.h (addition)
inline constexpr double kDashCooldown = 2.0;

// The rule of the dash: checks, then the change. Refused = returns without changing anything.
inline void dash(Walker& w, Mine& m, const meadow::Dash& d) {
    if (m.dashCd > 0) return;
    m.dashCd = kDashCooldown;
    w.x += d.dx * 5;
    w.y += d.dy * 5;
}
// The held-input step also counts the cooldown down, on both sides.
inline void walk(Walker& w, Mine& m, const Move& in, float dt) {
    m.dashCd = std::max(0.0, m.dashCd - dt);
    step(w, in, dt);
}

The server registers the shared function directly, and may wrap it when it needs more:

class Dashers : public server::Game {
public:
    void onStart() override {
        view<Walker>().spatial("x", "y");
        view<Mine>().ownerOnly();
        inputs().apply<Move>(walk);
        on<meadow::Dash>(dash);                          // the same verb takes a message or a move
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}, Mine{0}); }
};

// When the server needs more than the shared rule (a reason only the server knows, a side effect), wrap it so the
// rule still comes from the one function, and tell the player why with an ordinary message:
class Dashers2 : public Dashers {
public:
    void onStart() override {
        Dashers::onStart();
        on<meadow::Dash>([this](Player& p, const meadow::Dash& d) {   // replaces the handler for Dash
            Mine& m = get<Mine>(p.entity);
            if (m.dashCd > 0) { send(p, Said{String<16>("server"), String<80>("dash is cooling down")}); return; }
            dash(get<Walker>(p.entity), m, d);
        });
    }
};

If the client predicted a move the server refused for a reason the client could not see, the client's next tick shows the server's row without the change: me.correction().serial goes up once and the client's state returns to the server's. You undo nothing by hand and the server sends no reply; the rows are the answer. How the client eases that is on Client.

Trap. If the client marks a held input idle (me.idle<Move>(..)) it sends nothing, so the server does not step either, and anything the step counts down (the cooldown above) freezes on the server. Count such timers in update or use time() if idle must not stop them.

Refusing a client

To refuse a client, throw from onJoin. The exception's message is sent as the close reason, the client's session.onClose(fn) gets code 4000 and that reason, whatever onJoin already spawned is removed (and not saved), one line goes to stderr, and nothing else is affected: the server and the other players carry on.

class Gate : public server::Game {
public:
    void onStart() override { view<Walker>().global(); }
    void onJoin(Player& p) override {
        const std::string name = p.query("name");
        if (name.empty()) throw std::invalid_argument("a name is needed");
        if (players().size() > 64) throw std::runtime_error("the server is full");
        if (online_.contains(name)) throw std::runtime_error("the name '" + name + "' is already online");
        online_.insert(name);
        p.entity = spawn(Walker{0, 0, 60});
    }
    void onLeave(Player& p) override { online_.erase(p.query("name")); }
private:
    std::set<std::string> online_;
};

The reason is cut at 123 bytes. The same refusal, with code 4000, is used by the SDK when:

  • the client's contract does not match the game's (GameOptions::contract, see Options);
  • a saved row cannot be loaded for the client, or takes longer than loadTimeout (see Saving);
  • playerKey throws, or returns a key too long for the row's key member;
  • the player's entity cannot be attached: "server::Game: a client could not join: ... (define a view in onStart(): view<YourRow>(), a plain struct)".

To end a connection after it joined, use p.kick(reason): it waits for what is already queued to be written and gives the client code 4001. For a code of your own call p.client.disconnect(code, reason); codes 3000 to 4999 are for the game (4000 means "rejected"). Only the first call's reason counts.

Tip. A rule such as "disconnect players on a hopeless link" belongs in update: for (Player& p : players()) if (p.link().queueMs > 5000) p.kick("connection too slow");. The SDK itself only closes a connection whose output was blocked for Options::stalledSeconds (300 by default; code 4291).

Close codes at a glance: 4000 refused, 4001 your kick, 4290 sent too much (limiter), 4291 stalled. All of them arrive in the client's onClose(code, reason).

Respawn and players without an entity

p.entity is not fixed for life. Assign it again whenever the player gets a new entity: the game notices before the next send, moves the client onto it (its me() changes, its inputs drive the new entity, its owner-only rows come from it) and stops showing the old one by right. Destroying the old entity is yours to do. It also works inside a handler: that player's later inputs in the same tick already drive the new entity. Assign ecs::kNoEntity for a player with no character for a while (dead, waiting, spectating).

struct Slot { double respawnAt = 0; };

class Brawl : public server::Game {
public:
    void onStart() override {
        view<Walker>().spatial("x", "y");
        inputs().apply<Move>(step);
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); }
    void update(float) override {
        for (Player& p : players()) {
            if (ecs::isSet(p.entity) && get<Walker>(p.entity, READONLY).x > 500) {   // "died"
                registry().destroy(p.entity);                      // the old entity is yours to destroy
                p.entity = ecs::kNoEntity;                         // no character for a while
                p.user<Slot>().respawnAt = time() + 3;
            } else if (!ecs::isSet(p.entity) && time() >= p.user<Slot>().respawnAt) {
                p.entity = spawn(Walker{0, 0, 60});                // a new character
            }
        }
    }
};

Notice that a player with kNoEntity is still connected: its messages are still handled, onLeave still runs, and entity-form handlers get kNoEntity. In onLeave, if the entity is already gone, check ecs::isSet(p.entity) before using it. A spectator is the same thing from the start: leave entity unset in onJoin and use p.show(e) to give it something to watch.

A player's entity is also what is destroyed when it leaves; to keep it (a corpse, a world object), set p.entity = ecs::kNoEntity in onLeave.

What a client may send: the rate limiter

Every connection is limited before anything of yours runs: on the network thread, a token bucket of messages and a token bucket of bytes. Set it in server::Options::rate of the App (Network has the full table); the game sees its effects. The defaults:

RateLimit fieldDefaultMeaning
perSecond30Messages a second sustained. 0 turns the whole limiter off, byte limit and violation rules included.
burst60Size of the message bucket; 0 means perSecond.
bytesPerSecond16384Bytes a second of counted messages; 0: no byte limit.
burstBytes32768Size of the byte bucket; 0 means bytesPerSecond.
violationWindowMs2000The 2nd and 3rd violation count only inside this window of the 1st.
perTick16The game reads at most this many messages of one client per tick; the rest waits in its ring. 0 reads all.

A message that finds an empty bucket is a violation. The first of a run is dropped and the client is told (session.onWarning: "too many messages: the limit is 30 messages a second (burst 60), 16384 bytes a second; what is over it is dropped"); the second inside the window is dropped silently; the third closes the connection with code 4290 and the reason "closed for sending too much: the limit is ...". A message that passes ends the run. A message that passes the bucket but finds the world's input ring full also counts as a violation. The ping echo and the held-input message are not counted: held inputs have their own budget, InputPolicy.

What the game can see of this:

  • p.dropped() returns {rate, ringFull, perType} (and total()): messages of this client dropped over the connection limit, because the world's ring was full (the world is behind), or over a per-type .limit. Read it to act before the connection is closed.
  • stats() totals them over every player, those who left included, and counts closedForRate (connections closed for sending too much) and closedStalled.
Trap in tests. The limiter is on by default, so a test that sends faster than 30 a second is warned and then closed. Give the test server test::Config{.rate = {.perSecond = 0}} (see Testing).

GameOptions, one field at a time

Options go into the constructor of your class: World() : Game({.inputs = {.rate = 60}, .radius = 200}) {}. Designated initialisers must be written in declaration order, which is the order of this section. Everything is optional; a game that sets nothing here sends every spatial row within 64 world units and applies no byte budget.

The first group is about how much a player sees and how many bytes it may be sent. The depth (what a budget is, how cells and focus split it, why a link is measured) is on Network; here is what each field is.

FieldType, defaultMeaning
interestecs::InterestPolicy, {}The low-level interest policy (cell size, subscription cap, worker threads ...). The welcome and the owner-row rule are always switched on. The fields below are the game-level versions of some of its fields; .interest = {.budget = ..} still works and stays bytes per send.
inputsInputPolicy, {}See Held inputs.
radiusRule<float, const Player&>, unset (64)How far a player sees spatial rows, in world units: a number, or a function of the player. What it answers is used; the SDK clamps nothing. NaN or negative is a bug: a debug build stops, a release build uses 0 and counts stats().badRadius. Spatial rows beyond the radius are not sent.
budgetRule<std::size_t, const Player&>, unset (no limit)Bytes a second of rows for one player. The game sends once a tick, so each send gets budget / tickRate bytes and what does not divide is carried to the player's next send. The player's own predicted row is outside the budget.
weightstd::function<float(const Player&, ecs::Entity other, float distance)>, unsetHow much other matters to a player when the budget cannot take everything; higher goes first. Default 1 / (1 + distance). Orders the entries sent entity by entity (what the player focuses or is shown), not the crowd's cells. With .interest = {.workers = N}, N > 1, it is called from N threads at once: read-only access to game data only.
focusstd::optional<float>, unset (0.5)Under a budget, the share (0 to 1) taken first by the entries sent entity by entity (own row, focused, shown); what they do not use goes to the crowd. 0: they take only what the crowd leaves. 1: they may take everything. Outside 0..1 counts as the nearest end. A share of bytes: it has nothing to do with which entity p.focus(e) names.
cellWeightstd::function<float(const Player&, const ecs::Cell&)>, unsetUnder a budget, how much one cell of the crowd matters (default nearer first, 1 / (1 + distance)). Urgency = view priority x this x (sends waited + 1). 0 goes only when the budget has room left. Called once per cell the budget has to choose among. Same thread rule as weight. ecs::Cell has x, y, distance, entities, bytes, waited, isNew, mine.
nearReserveecs::NearReserve, {.after = 30, .within = 1.5f, .share = 0.25f}The cells around a player are never left waiting long: a cell within within cells that has waited after sends is paid first, out of share of the budget. {.share = 0} switches the reserve off.
crowdEveryRule<std::uint32_t, const Player&>, unset (every send)The crowd's cells go to a player at most every this many sends; the cells take turns (half in each send at 2). What changed in between is in the block when it goes. A cell the player has none of yet is sent at once.
cutstd::function<ecs::Cut(const Player&, const ecs::Cell&)>, unset (Cut::Low)When a block of changes does not fit, how far it may be cut by field tier. Cut::Low may leave Low fields out; LowAndNormal the Normal ones too; Never cuts nothing (the whole block goes when it fits, else it waits). What was left out goes later: nothing is lost.

A Rule is "a number, or a function of a Player": the same field takes either, and the function is asked once per player per send. For radius and budget the function is where you read the link:

class Tuned : public server::Game {
public:
    Tuned() : Game({.inputs = {.rate = 60, .starved = server::Starved::Repeat},
                    .radius = [](const Player& p) { return p.link().congested() ? 150.f : 400.f; },
                    .budget = [](const Player& p) { return p.link().congested() ? 16'000 : 80'000; },
                    .focus = 0.3f,
                    .crowdEvery = 2}) {}
    void onStart() override { view<Walker>().spatial("x", "y"); inputs().apply<Move>(step); }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); }
};
Trap. A budget is an average of the bytes of entries per send. The player's own row, headers, unsubscribes and cell drops are on top of it, and a block larger than the budget is sent now and then from room saved by earlier sends (at most one block). Give .budget = p.link().headroom() some margin if the link is tight.

The second group is about the connection and about saving:

FieldType, defaultMeaning
idleHeaderTicksstd::uint32_t, 0A client that has nothing new (no changed row, same input acknowledgement) is sent no tick message for this many ticks in a row, then a keep-alive. 0 means the game's tick rate (about one a second). 1 sends a message every tick; the stamp then skips ticks, so use session.serverTime() for time.
storeecs::Store*, nullptrWhere persisted rows are kept. Needed for persist<Row>() unless every row has its own storage. It must outlive the Game and is used by one Game at a time (a second Game on the same store is "the server after a restart"). See Saving.
contractContract, noneThe ns::contract of the game's .aether file. A client built from another version is refused ("client and server were built from different versions of pond.aether", code 4000), and so is a client that sends none ("this server requires the contract pond.aether; the client sent none ..."). A server with none refuses a client that has one ("the client was built from pond.aether but this server has no contract (give the Game `.contract = <namespace>::contract`)"). See Data.
loadTimeoutstd::chrono::milliseconds, 10 sHow long a client may wait, not yet joined, for the rows persist<Row>().ofPlayer() fetches. Past it the client is refused (code 4000) and the server goes on: "loading the saved rows of 'KEY' took more than N ms: the store did not answer (Game({.loadTimeout = ..}) sets the wait)".

None of these is validated by the constructor except inputs (see above): a bad radius shows up when it is asked, as described.

Counters for the operator

stats() returns the counters of the server's own defences since the game started, over every player (those who left too):

FieldMeaning
dropped (rate, ringFull, perType, total())Messages dropped instead of handled: over the connection limit, the world's ring was full, over a per-type limit.
closedForRateConnections the server closed for sending too much (code 4290).
closedStalledConnections the server closed because they would not take what was sent (Options::stalledSeconds, code 4291).
badRadiusRadius rules that answered NaN or a negative number.

Next: Saving keeps rows across restarts, Views decides who sees what, and Network explains budgets and links.

Reference

Every public member of server::Game, server::Player, server::Players and every option, with all parameters. The pieces behind them (Inputs, Messages) are listed where a game reaches them through inputs() and messages(). Saving (persist, load) is in the reference of Saving.

Game: construction and callbacks

explicit Game(GameOptions options = {});
virtual void onStart();
virtual void onJoin(Player&);
virtual void onLeave(Player&);
virtual std::string playerKey(Player&);
virtual void update(float dt);
virtual void receive(Player& p);
virtual void sendState();
ItemParametersReturns, throws, notes
Game(GameOptions)options: see GameOptions.Throws std::invalid_argument for a negative inputs value or maxActions < 1. Not copyable (the base class is not).
onStart()noneOnce per run, on the world thread, before the first tick. If it throws the world never ticks, the cause goes to Options::onError (stderr by default), and App::listen returns false. After it returns: the persist declarations are made, validators are checked (std::logic_error for an unregistered valid<X>), views are built.
onJoin(Player&)p: the new player; set p.entity.A throw refuses that client (code 4000, message as reason), removes the entities this call spawned, and logs "aether: a client was refused: ...".
onLeave(Player&)p: the leaving player, its entity still alive.Afterwards: the rows of its entity are saved, then the entity is destroyed, unless p.entity is kNoEntity or no longer alive.
playerKey(Player&)p: good only for p.query(..) and p.client; do not keep it.Return the key of the player's saved rows, or empty for no early fetch. See Saving.
update(float dt)dt: 1 / tickRate seconds.Throwing aborts the rest of that tick (see One tick).
receive(Player&)pDefault: server::receive(p.client, now, rate().perTick, interest, inputs, messages): interest first (subscribe, ignore), then inputs (queue only), then message handlers. Override to add your own handler to the chain.
sendState()noneDefault: interest().send(), the tail of the tick that writes every client its tick message.

Game: pieces and clocks

ecs::Registry& registry();   ecs::Schedule& schedule();   ecs::Interest& interest();
Inputs& inputs();            Messages& messages();         Players& players();
float dt() const;   int tickRate() const;   double time() const;   std::int64_t stamp() const;
void post(std::function<void()> fn);
std::size_t rememberedLoads() const;
Stats stats() const;
ItemMeaning
registry()The entity registry (queries, hooks, groups; ECS). Everything spawn/get do goes through it.
schedule()The schedule: phase(name), system(name, phase, fn). The game's own systems are named "inputs" (phase "input"), "update" (phase "simulate") and "interest" (phase "send").
interest()The interest manager (who is sent what).
inputs()The held-input and move queue; see below.
messages()The message table: limit<M>(count, per), onError(fn), failed(), dropped().
players()The players; see below.
dt()Seconds per tick, 1 / tickRate.
tickRate()Ticks a second: the App's Options::tickRate. Valid once the game started.
time()Seconds on the game clock, tick / tickRate; what clients read as session.serverTime(). It restarts at 0 when the server restarts: never save it (Saving).
stamp()The number of the tick being run; what clients read as session.tick().stamp.
post(fn)Run fn on the world thread at the start of the next tick (first step of the input phase). Any thread. Discarded at shutdown.
rememberedLoads()For tests: how many loaded values the game still remembers for a spawn (one per key that a load answered and no row was spawned for yet). An entry goes when its row is spawned or saved, and after a minute of the game's clock.
stats()The Stats struct described in Counters.

Game: entities and rows

template <class... Rows> ecs::Entity spawn(Rows&&... rows);
template <class Row, Flag... Fs> auto get(ecs::Entity e, Flags<Fs...> flags = {});   // Row&, or const Row& with READONLY
template <class Row> void set(ecs::Entity e, const Row& row);
template <class Row> ecs::ViewBuilder& view(std::string_view name = {});
template <class T> ecs::Local<T> local();
template <class Row> ecs::Component componentOf();
void snap(ecs::Entity e);   template <class Row> void snap(ecs::Entity e, const Row& row);
static constexpr auto READONLY;
ItemParametersReturns, throws
spawn(rows...)Any number of rows. A flat struct becomes a component (registered here or by view); any other type (std::string, std::vector, a class with a constructor) becomes a local component that stays on the server. A persisted row (persist<Row>()) is added with its key.The new entity. For a persisted row, an empty, zero, too-long or already-used key throws std::invalid_argument / std::logic_error naming the row, and no entity is left behind. Inside onJoin the entity is recorded so a refusal removes it.
get<Row>(e)e: an entity; optional READONLY.A reference to the struct: writable in place (Row&), or const Row& with READONLY. Valid until the entity gains or loses that component or dies. Looking costs nothing: an unchanged row is not sent or saved (found by comparing). std::logic_error (every build) if e is dead or has no such row ("... has no Row row (spawn it with the row, or check what the entity was given)" / "... is dead or was never created (it may have been destroyed; do not keep its id)").
set(e, row)e; row: the new value.Assigns a whole row. Same errors as get. For a non-flat local row the type must be copy assignable.
view<Row>(name = "")name: the view's name; empty means the struct's name (the client says the same: session.view<Walker>("walkers")).A ViewBuilder& (.spatial("x", "y"), .global(), .ownerOnly(), .every(k).history(k); see Views). Built when onStart returns. std::logic_error if called later.
local<T>()T: any C++ type with a noexcept move constructor and destructor (compile error otherwise).A handle to a server-only component, never sent or saved: auto portals = local<Portals>(); then registry().get(zone, portals). A function view (view<Row>().from(portals, fn)) shows part of it.
componentOf<Row>()noneThe registry component of Row (registered if needed); for hand-written registry calls.
snap(e), snap(e, row)e; optional row to set first.Marks this tick's change of e as a discontinuity: clients that see e get the whole row marked and read it as view.snapped(e). Call it in the tick that changes the row.
READONLY-Game::READONLY: needs no using and no namespace.

Game: messages

template <class X, class Fn> MessageHandle<X> on(Fn fn);
template <class M> void send(Player& p, const M& message);
template <class M> void broadcast(const M& message);
// MessageHandle<X>
MessageHandle& limit(int count, std::chrono::milliseconds per);
ItemParametersReturns, throws
on<X>(fn)X: a plain struct (public members, no constructors) that is not the held input. fn: one of the forms in Messages and moves; returns nothing.A MessageHandle<X>. Registers X as a message (any size within Options::maxMessageBytes) and, if it packs to at most 255 bytes, as a move. std::logic_error for two structs with the same unqualified name; the same X registered twice replaces the handler.
send(p, msg)p: the player; msg: a plain struct.Queued, written after the tick's state, in call order. Dropped if the player left or the message is too big (counted in players().dropped()).
broadcast(msg)msgsend to every player in players().
handle.limit(count, per)count >= 1: bucket size and messages per per; per >= 1 ms.The handle (chainable). std::invalid_argument otherwise. See Limiting a message for what happens over the limit.

messages() (the table on registers into) also offers, for a hand-written chain: on<M>(fn) with fn(Client&, const M&), limit<M>(count, per), handle(client, type, body) (true if the type was registered), onError(fn(Client&, std::string_view what)), failed() (handlers that threw) and dropped() (wrong-size bodies).

Game: inputs()

template <class Input, class Fn> Inputs& apply(Fn&& fn);                                  // the held input
template <class Input, class Row, class Step> Inputs& apply(const ecs::Typed<Row>& component, Step step);
template <class Input, class Fn> Inputs& action(Fn&& fn);                                 // a move only
template <class Input> Inputs& valid(std::function<bool(const Input&)> fn);
void onError(std::function<void(Client&, std::string_view what)> fn);
std::size_t failed() const;
std::uint32_t applied(const Client& c) const;   int queued(const Client& c) const;   std::uint64_t dropped(const Client& c) const;
float stepSeconds() const;   int rate() const;   int maxPerTick() const;   int queueLimit() const;
ItemMeaning
apply<Input>(fn)Registers the held input. fn forms: see The forms of a step. std::logic_error if another struct is already the held input. A game has one.
apply<Input>(component, step)The same for a Typed<Row> handle: step(Row&, const Input&, float dt) steps the row of the client's entity in component; skipped if the entity is dead or lacks the row.
action<Input>(fn)Registers a move only, not a message. In a Game, on<X> is what you write: it is made of this plus the message handler. Move ids are handed out by the server (up to 255). std::logic_error for two structs with the same name.
valid<Input>(fn)Drops an input for which fn returns false (counted in dropped). Before or after registration.
onError(fn), failed()Replace the stderr line for a throwing handler; count of handlers that threw.
applied(c), queued(c), dropped(c)For one client: the acknowledged sequence (0 if not attached), entries waiting, entries dropped (stale, invalid, over the queue, or over the budget with Excess::Drop).
stepSeconds(), rate(), maxPerTick(), queueLimit()The values in use after defaults: 1 / rate, rate (the tick rate if 0), maxPerTick, queue.

Players (the list) and Player (one)

std::size_t size() const;   bool empty() const;   begin() / end()                 // iterate Player&
Player* find(const Client& client) const;   Player* find(ecs::Entity e);
template <class M> void send(Player& p, const M& message);   template <class M> void broadcast(const M& message);
std::size_t dropped() const;
// Player
Client& client;   ecs::Entity entity = ecs::kNoEntity;
std::string query(std::string_view key, std::string fallback = {}) const;
template <class T> T& user();   Link link() const;
std::chrono::milliseconds crowdDelay() const;   std::chrono::milliseconds focusDelay() const;
void kick(std::string_view reason);   Dropped dropped() const;
template <class M> void send(const M& message);
void show(ecs::Entity e);   void hide(ecs::Entity e);   void focus(ecs::Entity e);   void unfocus(ecs::Entity e);
ItemParametersReturns, throws
players().size(), empty()-Number of joined players (clients held for their saved rows are not counted).
iteration-for (Player& p : players()). Do not add or remove players while iterating (joins and leaves are handled by the game between ticks' steps, not inside your loop).
players().find(client)client: a Client&.The player or nullptr.
players().find(entity)e: the player's entity.The player whose entity == e, or nullptr (a linear search).
players().send, broadcastas Game::sendQueued. A message that is too big is dropped; one that finds the client's output buffer full waits for the next flush, in order, up to one buffer's worth of bytes per client, then is dropped.
players().dropped()-How many queued messages were dropped (too big, or beyond the buffer), over all players.
p.client-The connection: send(msg) immediate, disconnect(code, reason), link(), dropped(), query().
p.entityassignSee Respawn. The game applies a new value before the next send.
p.query(key, fallback)key: name; fallback: returned when absent (default empty).The text after key= in the connect query. No decoding is done here; the first match wins.
p.user<T>()T: default-constructible.A reference to the per-player struct, made on first use. std::logic_error ("this player's user struct was made as another type; use one type per game") for another T.
p.link()-A Link copy: rttMs, jitterMs, loss, capacity, sending, receiving, backlog (socket plus the world's output ring), queueMs, left, interpMs, limit; helpers congested() (queueMs > 100 || left > 0) and headroom() (capacity - 4 x backlog, bytes a second, 0 if unknown). See Network.
p.crowdDelay(), p.focusDelay()-Milliseconds the longest-waiting cell (or focused entity) waited in the last send; 0 before the first send, with no crowd or none focused, or when not attached.
p.kick(reason)reason: text, at most 123 bytes (cut).Closes after what is queued; the client's onClose gets 4001 and the reason.
p.dropped()-Dropped{rate, ringFull, perType} since the client connected; total() sums them.
p.send(msg)-Same as Game::send(p, msg).
p.show(e), p.hide(e)e: an entity.This player alone sees e in every view until hidden. Before the client is attached (in onJoin) the request is remembered and applied when it is. std::logic_error if the player has no interest manager (not the case in a Game).
p.focus(e), p.unfocus(e)ee is sent to this player entity by entity in every send, wherever it is, and under a budget before the crowd. A focused entity that dies is let go for you. Remembered before attach.

GameOptions

struct GameOptions {
    ecs::InterestPolicy interest = {};
    InputPolicy inputs = {};
    Rule<float, const Player&> radius = {};
    Rule<std::size_t, const Player&> budget = {};
    std::function<float(const Player&, ecs::Entity other, float distance)> weight = {};
    std::optional<float> focus = std::nullopt;
    std::function<float(const Player&, const ecs::Cell&)> cellWeight = {};
    ecs::NearReserve nearReserve = {};
    Rule<std::uint32_t, const Player&> crowdEvery = {};
    std::function<ecs::Cut(const Player&, const ecs::Cell&)> cut = {};
    std::uint32_t idleHeaderTicks = 0;
    ecs::Store* store = nullptr;
    Contract contract = {};
    std::chrono::milliseconds loadTimeout = std::chrono::seconds(10);
};

struct InputPolicy { int rate = 0; int maxPerTick = 0; Excess excess = Excess::Wait; int queue = 0;
                     Starved starved = Starved::Skip; int repeatTicks = 6; int maxActions = 16;
                     std::uint8_t type = kInputType; };
enum class Excess : std::uint8_t { Wait, Drop };
enum class Starved : std::uint8_t { Skip, Repeat, Neutral };

Every field is explained in GameOptions, one field at a time and InputPolicy. The Rule type: Rule(T value) or Rule(F fn) where fn is callable as T(Args...); members set() (a number or function was given), value() (the number; T{} for a function or unset), isFunction(), and operator()(args...) (the number, or the function's answer; check set() first).

The rate-limiter struct server::RateLimit (perSecond, burst, bytesPerSecond, burstBytes, violationWindowMs, perTick) belongs to server::Options::rate on the App; defaults are in What a client may send.

Counters

struct Stats { Dropped dropped; std::uint64_t closedForRate = 0, closedStalled = 0, badRadius = 0; };
struct Dropped { std::uint64_t rate = 0, ringFull = 0, perType = 0; std::uint64_t total() const; };

A complete example of the reference members

examples/meadow/Admin.h
class Admin : public server::Game {
public:
    Admin() : Game({.inputs = {.rate = 40, .maxPerTick = 3, .excess = server::Excess::Drop, .queue = 6,
                               .starved = server::Starved::Neutral, .repeatTicks = 4, .maxActions = 8},
                    .radius = 300, .budget = 40'000, .focus = 0.4f, .idleHeaderTicks = 5}) {}

    void onStart() override {
        view<Walker>().spatial("x", "y");
        inputs().apply<Move>(step);
        inputs().valid<Move>([](const Move& m) { return std::abs(m.dx) <= 1 && std::abs(m.dy) <= 1; });
        on<Chat>([this](Player& p, const Chat& c) {
            broadcast(Said{String<16>(p.query("name", "anon")), c.text});
        }).limit(2, 1s);
        messages().onError([](server::Client&, std::string_view what) { std::fprintf(stderr, "chat: %.*s\n", int(what.size()), what.data()); });
    }
    void onJoin(Player& p) override { p.entity = spawn(Walker{0, 0, 60}); p.focus(p.entity); }

    void report() {                                    // call it through post() from any thread
        const Stats s = stats();
        std::printf("tick %lld at %.1f s, %d Hz, dt %.3f; dropped %llu, closed %llu/%llu, bad radius %llu\n",
                    static_cast<long long>(stamp()), time(), tickRate(), dt(),
                    static_cast<unsigned long long>(s.dropped.total()), static_cast<unsigned long long>(s.closedForRate),
                    static_cast<unsigned long long>(s.closedStalled), static_cast<unsigned long long>(s.badRadius));
        for (Player& p : players()) {
            const server::Link l = p.link();
            std::printf("%s rtt %u ms, backlog %u, inputs queued %d, crowd delay %lld ms, dropped %llu\n", p.query("name").c_str(),
                        unsigned(l.rttMs), unsigned(l.backlog), inputs().queued(p.client),
                        static_cast<long long>(p.crowdDelay().count()), static_cast<unsigned long long>(p.dropped().total()));
            if (l.queueMs > 5000) p.kick("connection too slow");
        }
    }
};

See also: Saving for persist and load, Views, Client, Network, Testing (test::Server runs a Game in-process).