Skip to content

Latest commit

 

History

History
348 lines (297 loc) · 18.6 KB

PROTOCOL.md

File metadata and controls

348 lines (297 loc) · 18.6 KB

Polychat3 protocol, version 1

Each game server (the client) keeps one WebSocket open to the Polychat3 server (the hub). This file and the payload classes in core change in the same commit.

The protocol is strict: frames are strict JSON, every field is required at every depth and has exactly its listed type, unknown types and fields are errors, and both ends must use the same version.

Transport and framing

  • WebSocket (RFC 6455) over TCP: ws://host:port/. The hub listens on bind_address and server_port in the hub config, 127.0.0.1 and 5005 by default. The path is ignored.
  • The hub itself speaks no TLS. Over ws:// the handshake token travels in clear text, so only use it on one machine or on a private network the game servers share, never on the public internet.
  • To cross any other network, put a reverse proxy that terminates TLS in front of the hub. Clients then connect to the proxy with wss://host:port/ and must check its certificate and hostname. The frames are the same either way.
  • One text frame is one UTF-8 JSON object with a string type. No batching, no binary frames.
  • Field names are camelCase, the same as the Java fields. type is the class name in camelCase, without its C2S or S2C prefix: C2SPlayerJoin is playerJoin.
  • Protocol.MAX_FRAME_BYTES (1 048 576, 1 MiB) is the largest encoded frame, in both directions. Both ends pass it to Java-WebSocket's Draft_6455, which closes a connection that receives a bigger frame with 1009. The library only checks what it receives, so the sender keeps its own frames under the limit: the client cuts commandResult.output and sets truncated: true, and the hub logs an error and does not send a frame of its own that is too big.
  • One connection per game server for the life of its process. The client sends from one queue, so seq is monotonic on the wire.

Text

Every text field is plain text: no § colour codes, no Discord markup, no prefixes such as [A5]. The sender strips formatting and the receiver adds its own.

Server ids

A server id is 1 to 16 characters, each a lowercase letter, a digit, _ or - (regex ^[a-z0-9_-]{1,16}$). For example a5, gtnh or atm-9. A display prefix such as [A5] is the id in upper case.

Hub modules that send chat, such as Discord, claim a server id when they load. The hub loads every module before it accepts connections, and refuses a handshake that uses a claimed id with 4003. Nothing is hardcoded: with the Discord module turned off, discord is a normal id.

Code layout

Everything below is in core, package club.moddedminecraft.polychat3.core.

Class Purpose
Protocol VERSION, MAX_FRAME_BYTES, SERVER_ID and the close codes
payloads.PayloadCodec Encodes and decodes frames
payloads.Payload Base class of every frame
payloads.ProtocolError The protocolError frame, used in both directions
payloads.PlayerInfo, payloads.ServerState Shared by both directions
payloads.ProtocolException Thrown for an invalid frame
payloads.c2s.* Frames the client sends; events extend c2s.C2SEvent (adds seq). Every class name starts with C2S
payloads.s2c.* Frames the hub sends; relayed frames extend s2c.S2CRelayed (adds server, serverName). Every class name starts with S2C

Every payload class and getter has Javadoc.

Using the codec:

String frame = PayloadCodec.encode(payload);     // any payload
Payload in = PayloadCodec.C2S.decode(frame);      // hub side
Integer version = PayloadCodec.handshakeVersion(frame);  // hub side, first frame; null if none
Payload in = PayloadCodec.S2C.decode(frame);      // client side

decode throws ProtocolException for a frame that is not a strict JSON object (no comments, single quotes, unquoted names or trailing data), or has a missing or unknown type. It also throws for a field, at any depth, that is missing, unknown, null, of the wrong JSON type, or an unknown enum value. The receiver logs a warning and answers with protocolError; see below. encode throws IllegalArgumentException for a payload with a null field, since that frame would break the protocol.

Field types

seq, lastSeq, session, hubSession and lastRelayed are 64-bit integers. version, online and maxPlayers are integers. ok, truncated and muted are booleans (muted is an array in muteList). uuid is a dashed Minecraft UUID. Everything else is a string or an array.

A frame holds no other kind of number, and an integer is written as digits only, with - in front when it is negative: 1.0, 1e0 and -0 are refused like a value of the wrong type.

state is one of starting, started, stopping, stopped, crashed, offline, unresponsive. A client only sends the first five. The hub refuses a handshake with either of the last two (4000), and logs, acknowledges and otherwise ignores a serverStatus with one.

Messages, client to hub (c2s)

Type Fields
handshake version, server, name, token, session, state, colour, address, maxPlayers, hubSession, lastRelayed
heartbeat none
chatMessage seq, player, senderId, message
playerJoin seq, player, uuid, online
playerLeave seq, player, uuid, online
playerList seq, players (array of {name, uuid})
serverStatus seq, state
commandResult seq, id, ok, output, truncated
mute seq, target, muted, by
protocolError code, message
  • handshake:
    • session is the process start time in ms, set once when the mod loads. A new value tells the hub the server restarted; the same value means a reconnect.
    • state is the last state the client sent, starting before the first.
    • colour is one of the 16 Minecraft colour names.
    • address and maxPlayers are shown by /online.
    • hubSession and lastRelayed ask the hub to replay what this server missed; see "Replay to the client". Both are 0 on the first connection of a session.
  • heartbeat: sent from the game's server tick every 15 s. No seq, never buffered or replayed.
  • chatMessage: senderId is the player's Minecraft UUID.
  • playerJoin and playerLeave: online is the player count afterwards.
  • playerList: the full list, sent after every handshakeAccepted and every 5 minutes.
  • commandResult: id is the id of the runCommand it answers.
  • mute: a staff member on this server muted (muted: true) or unmuted the player with Minecraft UUID target. by is the staff member's UUID, or console when the server console (or RCON) did it. See "Mutes".

Messages, hub to client (s2c)

Type Fields
handshakeAccepted version, session, lastSeq, servers (array of S2CServerEntry)
acknowledgement seq
chatMessage server, serverName, seq, player, senderId, message
playerJoin server, serverName, seq, player, uuid, online
playerLeave server, serverName, seq, player, uuid, online
playerList server, serverName, seq, players
serverStatus server, serverName, seq, state, colour, address, maxPlayers, players
runCommand id, name, default, args
systemMessage message, kind
muteList muted (array of UUIDs)
mute target, muted, by
protocolError code, message
  • handshakeAccepted: session is the hub's process start time in ms. lastSeq is the highest seq accepted from this server and session, 0 if none. An S2CServerEntry has id, name, colour, address, maxPlayers, state and players.
  • acknowledgement: every event up to and including seq is accepted.
  • chatMessage, playerJoin, playerLeave, playerList, serverStatus: relayed from another server or a module, with server and serverName naming where it came from. seq is the hub's relay number; see "Replay to the client".
    • chatMessage.senderId is a Minecraft UUID for game chat, and the Discord user id for Discord chat.
    • serverStatus is the origin's S2CServerEntry flattened onto the frame.
  • runCommand: the client joins args with single spaces and substitutes the result for $args once, in its own override for name if it has one, else in default (defaultCommand in Java), and trims spaces from both ends, so empty args leave no trailing space. It runs that console command and answers with commandResult.
  • systemMessage: kind is broadcast, restart or info. The hub sends it to every connected game server, or to one server only when it is about that server alone, such as the countdown before its restart.
  • muteList: every muted player's Minecraft UUID, sent right after handshakeAccepted. It replaces the client's copy of the list.
  • mute: one player was muted or unmuted, sent to every server. by is a Minecraft UUID for an in-game mute, console for one from a server console, or the Discord user id for a Discord one. Not relayed with seq and never replayed: the next muteList carries it.

Mutes

  • The hub owns the mute list, keyed by Minecraft UUID, and keeps it across restarts. Staff change it in game (c2s mute) or through a hub module such as Discord.
  • On every change the hub sends mute to every connected server, including the one the change came from. A mute that changes nothing (muting a player who is already muted) sends nothing. muteList and s2c mute carry UUIDs in lowercase.
  • The hub ignores a mute whose target is not a dashed UUID. It still acknowledges it and logs it.
  • The client keeps its copy from muteList and mute, and stops a muted player's chat on its own server.
  • The hub also drops a chatMessage whose senderId is muted, in case a client's copy is behind. It acknowledges it, logs it and does not relay it.

Errors

protocolError has code (machine-readable, for example unsupported_version) and message (human-readable).

When a frame fails to decode, the receiver logs a warning and sends protocolError; the connection stays open. Three invalid frames in a row close it with 4005. Before any protocol close, the hub sends protocolError so the client's log says why.

A protocolError for a refused handshake never quotes the frame, and the hub never writes that frame to its log: it holds the token.

Handshake

  1. The client opens the socket and sends handshake at once, then nothing until handshakeAccepted.
  2. A first frame that is not a valid handshake, or no handshake within 5 s, closes the connection with 4000.
  3. The hub checks, in this order, and closes on the first failure:
    1. the version equals Protocol.VERSION (4002). The hub reads type and version before it decodes the frame, so a handshake of another version is closed with 4002 and not 4000, whatever its other fields are;
    2. the id is valid and not claimed by a module (4003);
    3. the token matches the hub's server_token, which every server shares (4001).
  4. If a live connection already has that id, the hub closes the old one with 4004.
  5. The hub relays the server's serverStatus to every other server, so a server they saw offline or unresponsive, or never saw, shows its handshake state again. It answers handshakeAccepted, then replays what the client missed; see "Replay to the client".
  6. The client resends its buffered events with seq above lastSeq, oldest first, then sends a fresh playerList.

Versioning

version is one integer, Protocol.VERSION. Both ends must use exactly the same version.

It stays 1 until the first release. From then on, any change to the protocol, including a new type, bumps it by one in the next release.

Sequence numbers, acknowledgements and replay

  • Events are chatMessage, playerJoin, playerLeave, playerList, serverStatus, commandResult and mute. Each carries seq: 1 for the first event a client process sends, plus one for every event after it.
  • seq belongs to the session. After a restart the client has a new session and starts again at 1, and the hub starts counting again from 0.
  • The hub sends acknowledgement after it has processed an event. One acknowledgement may cover several events.
  • The client buffers every chatMessage, playerJoin, playerLeave, serverStatus and mute until an acknowledgement covers it, up to 200 events, dropping the oldest when full. playerList and commandResult are not buffered.
  • An event with seq at or below the hub's last accepted seq for that session is a duplicate. The hub acknowledges it again and does not process it.
  • Delivery is at-least-once.

Replay to the client

  • The hub numbers every relayed event with one seq for the whole hub: 1 for the first event it relays after it starts, plus one for every event after that. An event has the same seq on every server it goes to, so a client sees gaps, which are normal.
  • The hub keeps the last 200 relayed chatMessage, playerJoin and playerLeave frames. playerList and serverStatus are not kept, since handshakeAccepted.servers already carries the current state.
  • The client keeps, in memory, the hub session from its last handshakeAccepted and the highest relayed seq it has received since.
  • When it reconnects in the same session, the client sends them as hubSession and lastRelayed. If hubSession equals the hub's session, the hub sends every kept frame with seq above lastRelayed that came from another server, oldest first, right after handshakeAccepted.
  • On the first connection of a session, after a restart, the client sends 0 for both and gets no replay: no players were online to miss anything. A hub that restarted has a new session, so it replays nothing either.
  • Frames older than the last 200 are lost.

Shutting down

  • On a stop, the client sends serverStatus stopped; on a crash, crashed, from a JVM shutdown hook (it runs on a normal exit, Ctrl+C and SIGTERM).
  • The client then holds the JVM's shutdown until an acknowledgement covers that serverStatus, for at most 3 s, and closes the connection with 1000 either way. If the hub is unreachable, the JVM exits after 3 s and the hub sees a dropped connection, marking the server offline.
  • When a connection closes, for any reason, the hub marks the server offline and relays that serverStatus, unless the server last reported stopped or crashed: that state stays, and the other servers already have it. A connection replaced by a newer one (4004) changes nothing.
  • A server that is stopped, crashed or offline has no players: the hub empties its player list when it takes that state, since a game that shuts down may send no playerLeave for the players it kicks. The relayed serverStatus already carries the empty list.
  • The hub keeps a server's last seq after any close. The restarted server's new session resets it to 0, so both ends start again from the beginning.
  • A process killed without shutdown hooks (kill -9, the OOM killer, power loss) sends nothing and looks like a dropped connection. The new session in its next handshake is what tells the hub it restarted.

Keepalive

  • Socket. Both ends ping every 30 s. No pong within 45 s closes the connection locally with 1006.
  • Game thread. The client sends heartbeat every 15 s from a game-thread timer, so it stops when the game thread hangs. If the hub sees no heartbeat or event for 45 s, it marks the server unresponsive and relays that serverStatus. The socket stays open. Only a started or stopping server is marked: one in starting sends no heartbeat while it loads, which for a modded server can take minutes. The next heartbeat or event restores the last state the client reported.

Close codes

Code Constant Meaning Client does
1000 CLOSE_NORMAL Client shutting down, after serverStatus stopped or crashed Nothing
1001 CLOSE_GOING_AWAY Hub shutting down or restarting Reconnect with backoff
1006 No pong in time; local only Reconnect with backoff
1009 CLOSE_TOO_BIG Frame larger than MAX_FRAME_BYTES Log at error, reconnect
4000 CLOSE_BAD_HANDSHAKE First frame not a valid handshake, or none in time Reconnect with backoff
4001 CLOSE_BAD_TOKEN Wrong token Log at error, retry every 60 s
4002 CLOSE_BAD_VERSION Version differs from the hub's Log at error, retry every 60 s
4003 CLOSE_BAD_SERVER_ID Invalid server id, or one a module claimed Log at error, stop
4004 CLOSE_REPLACED Replaced by a newer connection with the same id Log at error, stop
4005 CLOSE_PROTOCOL_ERROR Binary frame, or three invalid frames in a row Reconnect with backoff

Backoff is 1, 2, 4, 8, 16, then 30 s, with 20 % jitter.

Example frames

> is client to hub, < is hub to client.

> {"type":"handshake","version":1,"server":"a5","name":"All the Mods 5","token":"...","session":1793130000000,"state":"started","colour":"yellow","address":"a5.example.net","maxPlayers":40,"hubSession":0,"lastRelayed":0}
< {"type":"handshakeAccepted","version":1,"session":1793120000000,"lastSeq":0,"servers":[{"id":"gtnh","name":"GTNH","colour":"gold","address":"gtnh.example.net","maxPlayers":30,"state":"started","players":[{"name":"Steve","uuid":"069a79f4-..."}]}]}
< {"type":"muteList","muted":["1f2a3b4c-..."]}
> {"type":"playerList","players":[{"name":"Alex","uuid":"ec561538-..."}],"seq":1}
< {"type":"acknowledgement","seq":1}
> {"type":"chatMessage","player":"Alex","senderId":"ec561538-...","message":"hello!","seq":2}
< {"type":"acknowledgement","seq":2}
> {"type":"mute","target":"ec561538-...","muted":true,"by":"069a79f4-...","seq":3}
< {"type":"mute","target":"ec561538-...","muted":true,"by":"069a79f4-..."}
< {"type":"acknowledgement","seq":3}
> {"type":"heartbeat"}
> {"type":"serverStatus","state":"stopping","seq":4}
< {"type":"runCommand","id":"c-7","name":"tps","default":"forge tps","args":[]}
> {"type":"commandResult","id":"c-7","ok":true,"output":"Overall: Mean TPS: 20.0","truncated":false,"seq":5}
< {"type":"systemMessage","message":"Server restarting in 60 s","kind":"restart"}
< {"type":"chatMessage","player":"Alex","senderId":"ec561538-...","message":"hello!","server":"a5","serverName":"All the Mods 5","seq":41}
< {"type":"chatMessage","player":"Heather","senderId":"123456789012345678","message":"hi from Discord","server":"discord","serverName":"Discord","seq":42}
< {"type":"protocolError","code":"unknown_type","message":"unknown type pong"}