R-Type
Networked shoot'em up built on Aegis2D
Loading...
Searching...
No Matches
server_network.hpp
Go to the documentation of this file.
1
3#pragma once
4#include <aegis2d/ecs/components.hpp>
5#include <aegis2d/net/binary.hpp>
6#include <aegis2d/net/context.hpp>
7#include <aegis2d/net/endpoint.hpp>
8#include <aegis2d/net/packet.hpp>
9#include <aegis2d/net/reliability.hpp>
10#include <aegis2d/net/rtt.hpp>
11#include <aegis2d/net/tcp_connection.hpp>
12#include <aegis2d/net/traffic.hpp>
13#include <aegis2d/net/udp_socket.hpp>
14
15#include <rtype/ban_list.hpp>
16#include <rtype/chat.hpp>
17#include <rtype/events.hpp>
18#include <rtype/login.hpp>
19#include <rtype/rate_limit.hpp>
20#include <rtype/scoreboard.hpp>
21#include <rtype/sessions.hpp>
22#include <rtype/snapshot.hpp>
24
25#include <chrono>
26#include <cstddef>
27#include <cstdint>
28#include <functional>
29#include <memory>
30#include <optional>
31#include <span>
32#include <string>
33#include <string_view>
34#include <unordered_map>
35#include <variant>
36#include <vector>
37
38namespace rtype {
39
82public:
84 using Clock = std::chrono::steady_clock;
85
87 using PlayerHandler = std::function<void(const Session& session)>;
88
92 using LeaveHandler = std::function<void(const Session& session, LeaveReason reason)>;
93
96 using InputHandler = std::function<void(const Session& session, aegis2d::ecs::PlayerInput input,
97 std::uint16_t sequence)>;
98
100 static constexpr std::chrono::seconds login_timeout{5};
101
104 static constexpr std::chrono::seconds udp_timeout{5};
105
108 static constexpr std::chrono::seconds traffic_report_period{10};
109
117 ServerNetwork(aegis2d::net::NetworkContext& context, std::uint16_t tcp_port,
118 std::uint16_t udp_port, SessionTable sessions = SessionTable{});
119
120 ServerNetwork(const ServerNetwork&) = delete;
124 ~ServerNetwork() = default;
125
133
142
148 void set_compression(std::optional<std::size_t> threshold) noexcept;
149
154 std::variant<std::size_t, ChatRejection> say(std::string_view text);
155
160 std::size_t close_room(std::uint32_t room);
161
169 std::optional<aegis2d::net::Endpoint> remove_player(std::string_view name, LogoutReason reason);
170
174 void set_bans(BanList* bans) noexcept;
175
178 [[nodiscard]] BanList* bans() const noexcept;
179
183 void set_scoreboard(const Scoreboard* board) noexcept;
184
187 void set_waves(std::vector<std::string> names);
188
191 [[nodiscard]] std::optional<std::size_t> compression() const noexcept;
192
200 void send_snapshot(std::span<const std::vector<std::byte>> payloads, std::uint32_t room,
201 const std::shared_ptr<const Snapshot>& snapshot = nullptr);
202
211 void send_snapshot(const std::shared_ptr<const Snapshot>& snapshot, std::uint32_t room);
212
215 [[nodiscard]] std::uint64_t snapshots_sent() const noexcept;
216
228 void send_events(std::span<const std::vector<std::byte>> events, std::uint32_t room,
229 std::optional<std::uint32_t> token = std::nullopt);
230
238 void send_events_to_others(std::span<const std::vector<std::byte>> events, std::uint32_t room,
239 std::uint32_t token);
240
243 [[nodiscard]] std::uint64_t event_datagrams_sent() const noexcept;
244
250 void update(Clock::time_point now);
251
257 void set_limits(RateLimits limits);
258
264 void shutdown();
265
268 [[nodiscard]] bool idle() const noexcept;
269
272 [[nodiscard]] aegis2d::net::Endpoint tcp_endpoint() const;
273
276 [[nodiscard]] aegis2d::net::Endpoint udp_endpoint() const;
277
280 [[nodiscard]] const SessionTable& sessions() const noexcept;
281
284 [[nodiscard]] std::uint64_t connections() const noexcept;
285
288 [[nodiscard]] std::size_t open_connections() const noexcept;
289
292 [[nodiscard]] std::uint64_t datagrams() const noexcept;
293
296 [[nodiscard]] std::uint64_t rate_limited() const noexcept;
297
300 [[nodiscard]] std::uint64_t refused_connections() const noexcept;
301
304 [[nodiscard]] std::uint64_t dropped_datagrams() const noexcept;
305
308 [[nodiscard]] std::uint64_t game_datagrams() const noexcept;
309
312 [[nodiscard]] std::uint64_t timeouts() const noexcept;
313
316 [[nodiscard]] std::uint64_t errors() const noexcept;
317
324 [[nodiscard]] const aegis2d::net::TrafficCounters* traffic(std::uint32_t token) const;
325
333 [[nodiscard]] const aegis2d::net::RttEstimator* rtt(std::uint32_t token) const;
334
340 [[nodiscard]] const SnapshotHistory* snapshots(std::uint32_t token) const;
341
342private:
343 struct Client {
344 aegis2d::net::TcpConnection connection;
345 Clock::time_point accepted;
346 std::optional<std::uint32_t> token;
347 std::uint64_t sent = 0;
348 bool close_when_sent = false;
349 bool closed = false;
350 // Whether it sent a message of the rooms, and so gets RoomPlayers and GameStart.
351 bool rooms = false;
352 ChatRate chat;
353 };
354
355 void on_accept(aegis2d::net::TcpConnection connection);
356 void on_message(std::uint64_t id, std::span<const std::byte> message);
357 void on_login(Client& client, std::span<const std::byte> message);
358 bool on_room_message(Client& client, std::span<const std::byte> message);
359 bool on_chat(Client& client, std::span<const std::byte> message);
360 void on_join(Client& client, std::uint8_t room);
361 void announce_room(std::uint32_t room);
362 void on_close(std::uint64_t id, aegis2d::net::TcpCloseReason reason);
363 void on_datagram(const aegis2d::net::Endpoint& from, std::span<const std::byte> datagram);
364 void on_connect(const aegis2d::net::Endpoint& from, std::span<const std::byte> datagram,
365 const aegis2d::net::PacketHeader& header,
366 const aegis2d::net::BinaryReader& payload);
367 void drop(const aegis2d::net::Endpoint& from, std::span<const std::byte> datagram,
368 std::string_view reason);
369 void on_game_datagram(const Session& session, const aegis2d::net::Endpoint& from,
370 std::span<const std::byte> datagram,
371 const aegis2d::net::PacketHeader& header,
372 aegis2d::net::BinaryReader& payload);
373 void disconnect(std::uint32_t token, LeaveReason reason);
374 void end_session(std::uint32_t token, LeaveReason reason);
375 void queue_events(std::span<const std::vector<std::byte>> events,
376 const std::function<bool(const Session& session)>& receives);
377 void send(Client& client, std::span<const std::byte> message);
378 void close(Client& client, std::string_view reason);
379 void flush_events(Clock::time_point now);
380 void time_out(std::uint32_t token);
381 void kick(std::uint32_t token);
382 void kick_client(std::uint64_t id);
383 void end_with_logout(std::uint32_t token, LogoutReason logout, LeaveReason leave);
384 void report_traffic(Clock::time_point now);
385 // Sends the payloads encode() gives for the history of each bound player of the room.
386 void send_snapshot(
387 const std::function<std::vector<std::vector<std::byte>>(const SnapshotHistory&)>& encode,
388 std::uint32_t room, const std::shared_ptr<const Snapshot>& snapshot);
389
390 aegis2d::net::TcpListener listener_;
391 aegis2d::net::UdpSocket socket_;
392 SessionTable sessions_;
393 std::unordered_map<std::uint64_t, Client> clients_;
394 // What the server keeps of each bound session's datagrams, by token.
395 struct Peer {
396 aegis2d::net::ReliableChannel channel;
397 // Sequence of the last Input passed on (InputRecord::sequence).
398 std::optional<std::uint16_t> last_input;
399 // When its last valid datagram arrived, for the UDP timeout.
400 Clock::time_point heard = Clock::now();
401 aegis2d::net::TrafficCounters traffic;
402 SnapshotHistory snapshots;
403 };
404 std::unordered_map<std::uint32_t, Peer> peers_;
405 PlayerHandler joined_;
406 LeaveHandler left_;
407 InputHandler input_;
408 std::uint64_t connections_ = 0;
409 std::uint64_t dropped_ = 0;
410 std::uint64_t game_datagrams_ = 0;
411 std::uint64_t snapshots_sent_ = 0;
412 std::uint64_t event_datagrams_sent_ = 0;
413 std::uint64_t timeouts_ = 0;
414 std::uint64_t errors_ = 0;
415 RateLimits limits_;
416 RateLimiter limiter_{limits_.datagrams_per_second};
417 const Scoreboard* scores_ = nullptr;
418 BanList* bans_ = nullptr;
419 DropReport drops_;
420 std::uint64_t rate_limited_ = 0;
421 std::uint64_t refused_connections_ = 0;
422 std::optional<std::size_t> compression_;
423 std::optional<Clock::time_point> next_traffic_report_;
424};
425
426} // namespace rtype
The addresses banned by the administrator, kept in a JSON file across restarts.
TCP messages of the chat (RFC section 3.8): encoding, decoding and text rules.
The IP addresses that cannot log in, kept in a JSON file.
Definition ban_list.hpp:20
The chat rate of one session (RFC section 3.8): a token bucket.
Definition rate_limit.hpp:76
The max_entries best scores, best first, kept in a JSON file.
Definition scoreboard.hpp:34
The two ports the server listens on, and the TCP side of the sessions.
Definition server_network.hpp:81
void send_snapshot(std::span< const std::vector< std::byte > > payloads, std::uint32_t room, const std::shared_ptr< const Snapshot > &snapshot=nullptr)
Sends a snapshot to every player of a room whose endpoint is bound.
std::uint64_t refused_connections() const noexcept
Number of TCP connections closed at once, their address having too many open.
ServerNetwork & operator=(ServerNetwork &&)=delete
aegis2d::net::Endpoint tcp_endpoint() const
Local TCP address and port, with the port the system picked if 0 was asked.
std::uint64_t datagrams() const noexcept
Number of UDP datagrams received, oversized ones excluded.
std::function< void(const Session &session)> PlayerHandler
Called with a session that joins the game.
Definition server_network.hpp:87
void set_compression(std::optional< std::size_t > threshold) noexcept
Sets from which size the payloads of snapshots and events are compressed.
std::optional< aegis2d::net::Endpoint > remove_player(std::string_view name, LogoutReason reason)
Removes a player for the administrator: it gets Logout with reason, every other session a message of ...
std::uint64_t timeouts() const noexcept
Number of sessions ended because their player sent nothing for udp_timeout.
const SessionTable & sessions() const noexcept
Sessions open.
std::uint64_t event_datagrams_sent() const noexcept
Number of Event datagrams sent, first sends and resends, all players together.
std::function< void(const Session &session, LeaveReason reason)> LeaveHandler
Called with a session that leaves the game, and why: Left for a Logout, a Disconnect or a closed TCP ...
Definition server_network.hpp:92
static constexpr std::chrono::seconds udp_timeout
Time a bound player may send no valid datagram before its session is lost (RFC section 5....
Definition server_network.hpp:104
void shutdown()
Starts a clean stop of the server (RFC section 3.2).
std::uint64_t errors() const noexcept
Number of datagrams and TCP messages whose handling threw.
void set_bans(BanList *bans) noexcept
Sets the bans checked at each login: a banned address gets LoginRejected with Banned.
bool idle() const noexcept
Tells whether every connection is closed and forgotten, after shutdown().
std::uint64_t snapshots_sent() const noexcept
Number of Snapshot datagrams sent, all players together.
void send_events(std::span< const std::vector< std::byte > > events, std::uint32_t room, std::optional< std::uint32_t > token=std::nullopt)
Sends gameplay events, reliably, to the players of a room whose endpoint is bound.
ServerNetwork(aegis2d::net::NetworkContext &context, std::uint16_t tcp_port, std::uint16_t udp_port, SessionTable sessions=SessionTable{})
Listens on both ports, on every IPv4 interface.
std::function< void(const Session &session, aegis2d::ecs::PlayerInput input, std::uint16_t sequence)> InputHandler
Called with the actions a player holds and the sequence of the Input they come from,...
Definition server_network.hpp:97
ServerNetwork(ServerNetwork &&)=delete
std::uint64_t connections() const noexcept
Number of TCP connections accepted.
std::size_t open_connections() const noexcept
Number of TCP connections not removed yet by update(), logged in or not.
const aegis2d::net::TrafficCounters * traffic(std::uint32_t token) const
Datagrams exchanged with a bound player, by direction and packet type.
std::uint64_t game_datagrams() const noexcept
Number of valid datagrams from bound endpoints, other than Connect.
ServerNetwork(const ServerNetwork &)=delete
ServerNetwork & operator=(const ServerNetwork &)=delete
std::chrono::steady_clock Clock
Clock of the login and UDP timeouts.
Definition server_network.hpp:84
const SnapshotHistory * snapshots(std::uint32_t token) const
The last snapshots sent to a player and the ones it acknowledged.
void update(Clock::time_point now)
Ends the sessions of the bound players silent for udp_timeout, closes the connections that did not lo...
aegis2d::net::Endpoint udp_endpoint() const
Local UDP address and port, with the port the system picked if 0 was asked.
void send_events_to_others(std::span< const std::vector< std::byte > > events, std::uint32_t room, std::uint32_t token)
Sends gameplay events, reliably, to every bound player of a room but one, as send_events().
std::variant< std::size_t, ChatRejection > say(std::string_view text)
Sends a message of the server to every session logged in (ChatMessage with server_player and server_n...
~ServerNetwork()=default
static constexpr std::chrono::seconds traffic_report_period
Time between two lines of traffic and round trip time of each bound player in the log.
Definition server_network.hpp:108
BanList * bans() const noexcept
The bans checked at each login.
void set_scoreboard(const Scoreboard *board) noexcept
Sets the board a ListScores reads (RFC section 3.9).
void on_input(InputHandler input)
Sets what to do with the inputs of the players.
void set_limits(RateLimits limits)
Sets the limits on the traffic of one address (RFC section 6.6).
void on_players(PlayerHandler joined, LeaveHandler left)
Sets what to do when a player joins or leaves the game.
const aegis2d::net::RttEstimator * rtt(std::uint32_t token) const
Round trip time to a bound player, with its jitter.
std::size_t close_room(std::uint32_t room)
Closes a room: each of its sessions gets Logout with RoomClosed and ends; the others of the game are ...
static constexpr std::chrono::seconds login_timeout
Time a new connection has to send its LoginRequest.
Definition server_network.hpp:100
std::uint64_t dropped_datagrams() const noexcept
Number of UDP datagrams dropped for their header, direction or source.
void set_waves(std::vector< std::string > names)
Sets the waves files a room may be created with (SessionTable::set_waves()).
std::uint64_t rate_limited() const noexcept
Number of UDP datagrams dropped because their address sent too many.
std::optional< std::size_t > compression() const noexcept
From which size payloads are compressed.
The sessions of the server and the rooms they are in.
Definition sessions.hpp:65
The last snapshots sent to one client, and the ones it acknowledged.
Definition snapshot_history.hpp:21
Gameplay events sent to the clients (RFC section 4.4): spawns, destructions, deaths,...
TCP messages of the session (RFC section 3.2): encoding, decoding and name rules; those of the rooms ...
R-Type game code, built on the Aegis2D engine.
Definition enemy_scripts.hpp:16
LeaveReason
Why a player left the game, in PlayerLeft.
Definition events.hpp:49
LogoutReason
Why a session ends, the reason of Logout.
Definition login.hpp:86
Limits on what one address may send, and the summary of what was dropped (RFC 6.6,...
The best scores of the server, kept in a JSON file across restarts.
Sessions of the server: who is logged in, under which token and player number.
Snapshots of the world sent to the clients (RFC section 4.3).
The snapshots sent to one client and which of them it acknowledged: the baselines of delta snapshots.
Limits on the traffic of one IP address.
Definition rate_limit.hpp:18
A logged-in player (RFC section 3).
Definition sessions.hpp:24
The state of the world at one tick.
Definition snapshot.hpp:94