nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
server.cc
Go to the documentation of this file.
1#include "server/server.h"
2
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <deque>
7#include <iostream>
8#include <map>
9#include <memory>
10#include <optional>
11#include <set>
12#include <string>
13#include <string_view>
14#include <utility>
15#include <vector>
16
17#include "absl/memory/memory.h"
18#include "absl/strings/match.h"
19#include "absl/strings/str_cat.h"
20#include "absl/time/clock.h"
21#include "absl/time/time.h"
22#include "asio/buffer.hpp"
23#include "asio/socket_base.hpp"
24#include "protocol/chat.h"
25#include "protocol/clock.h"
26#include "protocol/framing.h"
27#include "protocol/messages.h"
28#include "protocol/nanommo.pb.h"
29#include "protocol/parts.h"
30#include "server/consul.h"
31#include "server/inputs.h"
32#include "server/interest.h"
33#include "server/levels.h"
34#include "server/listen.h"
35#include "server/shown.h"
36#include "server/stories.h"
37#include "server/tick.h"
38#include "server/tracing.h"
39#include "server/weather.h"
40#include "terrain/lands.h"
41#include "tracy/Tracy.hpp"
42
43namespace nanommo {
44
45namespace {
46
47// A second's worth of ticks.
48constexpr int kFullEvery = 20;
49
50// A player can say five lines at once, and then one every two seconds.
51constexpr int kChatBurst = 5;
52constexpr std::chrono::seconds kChatRefill{2};
53
54// A story is a hundred tokens of the model's work, where a line of chat costs
55// nothing, so a player gets one story every ten seconds.
56constexpr int kStoryBurst = 1;
57constexpr std::chrono::seconds kStoryRefill{10};
58
59// A drag in the bag is a move, so a player can make a few at once, and then
60// ten a second.
61constexpr int kItemBurst = 10;
62constexpr std::chrono::milliseconds kItemRefill{100};
63
64// A second of the worlds each client was sent, to leave out of the next what
65// hasn't changed since the one it has.
66constexpr std::size_t kMostRemembered = 20;
67
68// Each guild action is a transaction in MySQL, which the tick waits for, so a
69// player gets three at once, and then one a second.
70constexpr int kGuildBurst = 3;
71constexpr std::chrono::seconds kGuildRefill{1};
72
73// An ask for a duel is a line in another player's chat, so a player can ask
74// or answer three times at once, and then once a second, as for a guild.
75constexpr int kDuelBurst = 3;
76constexpr std::chrono::seconds kDuelRefill{1};
77
78// Starting to make something checks the whole bag, so a player can start or
79// stop three times at once, and then once a second, as for a duel.
80constexpr int kCraftBurst = 3;
81constexpr std::chrono::seconds kCraftRefill{1};
82
83// A lease lasts ten seconds, so renewing each second keeps it through a few
84// renewals that fail.
85constexpr std::chrono::seconds kRenewEvery{1};
86
87// As often as the saver flushes the wars' scores, so that a war started on
88// the other instance during a handover, or whose time is up, takes effect.
89constexpr std::chrono::seconds kReadWarsEvery{5};
90
91Progress ProgressOf(const Player& player) {
92 Progress progress{.x = player.x,
93 .z = player.z,
94 .experience = player.experience,
95 .health = player.health,
96 .land = player.land,
97 .weapon = MainHandOf(player),
98 .skills = player.skills,
99 .items_revision = player.inventory.revision(),
100 .quests = player.quests,
101 .quests_done = player.quests_done,
102 .quests_revision = player.quests_revision,
103 .faction = player.faction};
104 // The dead come back in the middle, at full health, so that's what we keep.
105 if (player.motion == Motion::kDead) {
106 progress.x = 0.0f;
107 progress.z = 0.0f;
108 progress.health = MaxHealthOf(player);
109 }
110 // A dungeon's copy may be gone by the time they're back, and after a deploy
111 // it is, as it ran in the instance before, so we keep them outside it.
112 if (kLands[player.land].dungeon) {
113 const Gate& out = WayOut(player.land);
114 const Place outside = Arrival(out, 0.0f);
115 progress.x = outside.x;
116 progress.z = outside.z;
117 progress.land = out.to;
118 }
119 return progress;
120}
121
122} // namespace
123
124absl::StatusOr<std::unique_ptr<Server>> Server::Create(
125 asio::io_context& io, uint16_t port, asio::ssl::context& tls,
126 std::chrono::nanoseconds interval, std::string name, uint32_t seed,
127 const Content& content, Metrics& metrics, Tokens& tokens, Players& players,
128 Guilds& guilds, Events& events, Storyteller& storyteller) {
129 std::unique_ptr<Server> server = absl::WrapUnique(
130 new Server(io, tls, interval, std::move(name), seed, content, metrics,
131 tokens, players, guilds, events, storyteller));
132 const absl::Status started = server->Start(port);
133 if (!started.ok()) {
134 return started;
135 }
136 return server;
137}
138
139Server::Server(asio::io_context& io, asio::ssl::context& tls,
140 std::chrono::nanoseconds interval, std::string name,
141 uint32_t seed, const Content& content, Metrics& metrics,
142 Tokens& tokens, Players& players, Guilds& guilds, Events& events,
143 Storyteller& storyteller)
144 : acceptor_(io),
145 tls_(tls),
146 udp_(io),
147 timer_(io),
148 interval_(interval),
149 name_(std::move(name)),
150 seed_(seed),
151 copies_(seed, content),
152 metrics_(metrics),
153 tokens_(tokens),
154 players_(players),
155 guilds_(guilds),
156 events_(events),
157 storyteller_(storyteller) {}
158
159int Server::players() const { return copies_.players(); }
160
161uint16_t Server::port() const {
162 std::error_code ignored;
163 return acceptor_.local_endpoint(ignored).port();
164}
165
166absl::Status Server::Start(uint16_t port) {
167 // On port zero, the system gives TCP a free port, and UDP takes that number
168 // too, which can be one taken for UDP already: in Docker, its DNS holds one
169 // at random. So it asks the system again, a few times. A port we were given
170 // is tried once.
171 constexpr int kTries = 8;
172 const std::vector<uint16_t> ports(port == 0 ? kTries : 1, port);
173 const absl::Status listening = ListenAndBind(acceptor_, udp_, ports);
174 if (!listening.ok()) {
175 return listening;
176 }
177 instance_ = InstanceId({.name = name_, .port = this->port()});
178 // One socket sends all the datagrams, so it gets more room for those on
179 // their way out than the two hundred kilobytes Linux gives by default.
180 std::error_code ignored;
181 udp_.set_option(asio::socket_base::send_buffer_size(4 * 1024 * 1024),
182 ignored);
183 Accept();
184 Receive();
185 timer_.expires_after(interval_);
186 timer_.async_wait([this](std::error_code) { Tick(); });
187 return absl::OkStatus();
188}
189
190World* Server::WorldOf(uint32_t id) {
191 Copy* copy = copies_.Of(id);
192 return copy != nullptr ? &copy->world : nullptr;
193}
194
195void Server::Accept() {
196 acceptor_.async_accept([this](std::error_code error,
197 asio::ip::tcp::socket socket) {
198 if (!error) {
199 auto id = std::make_shared<uint32_t>(0);
200
201 const auto on_message = [this, id](Session& session,
202 const std::string& bytes) {
203 metrics_.AddMessageReceived();
204 if (*id == 0) {
205 *id = HandleHello(session, bytes);
206 return;
207 }
208 protocol::Input input;
209 World* land = WorldOf(*id);
210 if (land != nullptr && input.ParseFromString(bytes)) {
211 if (input.seen() > seen_[*id]) {
212 seen_[*id] = input.seen();
213 }
214 inputs_.Take(*land, *id, input);
215 if (input.respawn()) {
216 land->Respawn(*id);
217 }
218 if (input.has_walk_to()) {
219 land->WalkTo(*id, {input.walk_to().x(), input.walk_to().z()});
220 }
221 if (input.skill() != 0) {
222 land->UseSkill(*id, input.skill());
223 }
224 if (!input.say().empty()) {
225 Say(*id, input.say());
226 }
227 if (input.has_talk()) {
228 Talk(*id, input.talk());
229 }
230 if (input.has_learn()) {
231 Learn(*id, input.learn());
232 }
233 if (input.has_take()) {
234 TakeQuest(*id, input.take());
235 }
236 if (input.has_turn_in()) {
237 TurnIn(*id, input.turn_in());
238 }
239 if (input.give_up() != 0) {
240 GiveUp(*id, input.give_up());
241 }
242 if (input.enlist() != 0) {
243 Enlist(*id, input.enlist());
244 }
245 if (input.has_item()) {
246 Item(*id, input.item());
247 }
248 if (input.has_guild()) {
249 Guild(*id, input.guild());
250 }
251 if (input.has_trade()) {
252 Trade(*id, input.trade());
253 }
254 if (input.has_duel()) {
255 Duel(*id, input.duel());
256 }
257 if (input.has_craft()) {
258 Craft(*id, input.craft());
259 }
260 }
261 };
262 const auto on_close = [this, id] {
263 if (*id != 0) {
264 Leave(*id);
265 }
266 };
267 std::make_shared<Session>(std::move(socket), tls_, on_message, on_close)
268 ->Start();
269 }
270 Accept();
271 });
272}
273
274uint32_t Server::HandleHello(Session& session, const std::string& bytes) {
275 // The hello's span starts as it arrives, under the span that issued its
276 // token, which we know once Redis gives the token back.
277 const absl::Time arrived = absl::Now();
278 protocol::Hello hello;
279 SpanContext issuer;
280 const absl::StatusOr<uint32_t> id =
281 hello.ParseFromString(bytes) ? tokens_.Redeem(hello.token(), &issuer)
282 : absl::InvalidArgumentError("not a hello");
283 Span span = StartSpan("hello", SpanKind::kServer, issuer, arrived);
284 if (!id.ok() || WorldOf(*id) != nullptr) {
285 // Redis not answering is the server's failure, not the player's.
286 if (!id.ok() && !absl::IsNotFound(id.status()) &&
287 !absl::IsInvalidArgument(id.status())) {
288 std::cerr << "couldn't redeem a token: " << id.status() << TraceField()
289 << "\n";
290 span.SetError(id.status().ToString());
291 } else {
292 std::cout << "refused a client: unknown token, or already playing"
293 << TraceField() << std::endl;
294 span.SetAttribute("nanommo.refused", "unknown token, or already playing");
295 }
296 session.Close();
297 return 0;
298 }
299 span.SetAttribute("nanommo.player", *id);
300 // A character plays on one instance of its world at a time, which has their
301 // lease while they do, so that the others turn them away.
302 const absl::StatusOr<std::string> lease =
303 players_.Lease(name_, *id, instance_);
304 if (!lease.ok()) {
305 if (absl::IsFailedPrecondition(lease.status())) {
306 std::cout << "refused player " << *id << ": " << lease.status().message()
307 << TraceField() << std::endl;
308 span.SetAttribute("nanommo.refused", lease.status().message());
309 } else {
310 std::cerr << "couldn't lease player " << *id << ": " << lease.status()
311 << TraceField() << "\n";
312 span.SetError(lease.status().ToString());
313 }
314 session.Close();
315 return 0;
316 }
317 const absl::StatusOr<Player> player = players_.Load(name_, *id);
318 if (!player.ok()) {
319 std::cerr << "couldn't load player " << *id << ": " << player.status()
320 << TraceField() << "\n";
321 span.SetError(player.status().ToString());
322 players_.Release(name_, *id, *lease).IgnoreError();
323 session.Close();
324 return 0;
325 }
326 copies_.Join(*id, *player);
327 // Their guild is in MySQL, as others change it too, and they get it, or
328 // that they're in none, with the first guild news.
329 const absl::StatusOr<Membership> membership = guilds_.Of(*id);
330 if (membership.ok()) {
331 members_[*id] = *membership;
332 WorldOf(*id)->SetGuild(*id, membership->guild);
333 // The rest of the guild sees them online.
334 RefreshGuild(membership->guild);
335 } else if (!absl::IsNotFound(membership.status())) {
336 std::cerr << "couldn't load player " << *id
337 << "'s guild: " << membership.status() << TraceField() << "\n";
338 }
339 guild_news_.insert(*id);
340 // Names, kinds and NPCs go out once a second, so the next broadcast is a
341 // full one, and a player who's just joined, say from another instance,
342 // gets them in their first world.
343 broadcasts_ = 0;
344 saved_[*id] = ProgressOf(*player);
345 leases_[*id] = *lease;
346 sessions_[*id] = session.shared_from_this();
347 chat_limits_.emplace(*id, TokenBucket(kChatBurst, kChatRefill));
348 story_limits_.emplace(*id, TokenBucket(kStoryBurst, kStoryRefill));
349 item_limits_.emplace(*id, TokenBucket(kItemBurst, kItemRefill));
350 guild_limits_.emplace(*id, TokenBucket(kGuildBurst, kGuildRefill));
351 duel_limits_.emplace(*id, TokenBucket(kDuelBurst, kDuelRefill));
352 craft_limits_.emplace(*id, TokenBucket(kCraftBurst, kCraftRefill));
353 udp_tokens_[hello.token()] = *id;
354 std::cout << player->name << " joined, as player " << *id << ", with lease "
355 << *lease << TraceField() << std::endl;
356 return *id;
357}
358
359void Server::Leave(uint32_t id) {
360 std::cout << WorldOf(id)->players().at(id).name << " left" << std::endl;
361 // Nothing saves them once they're gone, so what's changed since the last
362 // tick goes now. The next instance has loaded them as they were saved when
363 // the handover began, which this mustn't write over.
364 if (!handing_over_) {
365 Save({id}).IgnoreError();
366 }
367 // So that another instance can take them at once, not once it runs out.
368 if (const auto lease = leases_.find(id); lease != leases_.end()) {
369 const absl::Status released = players_.Release(name_, id, lease->second);
370 if (!released.ok()) {
371 std::cerr << "couldn't release player " << id << "'s lease: " << released
372 << "\n";
373 }
374 leases_.erase(lease);
375 }
376 copies_.Leave(id);
377 saved_.erase(id);
378 sessions_.erase(id);
379 chat_limits_.erase(id);
380 story_limits_.erase(id);
381 item_limits_.erase(id);
382 guild_limits_.erase(id);
383 duel_limits_.erase(id);
384 craft_limits_.erase(id);
385 inputs_.Leave(id);
386 history_.erase(id);
387 seen_.erase(id);
388 if (const auto member = members_.find(id); member != members_.end()) {
389 const uint32_t guild = member->second.guild;
390 members_.erase(member);
391 RefreshGuild(guild);
392 }
393 guild_news_.erase(id);
394 sent_bags_.erase(id);
395 sent_quests_.erase(id);
396 std::erase_if(udp_tokens_,
397 [id](const auto& token) { return token.second == id; });
398 udp_clients_.erase(id);
399}
400
401void Server::Say(uint32_t id, const std::string& text) {
402 if (!chat_limits_.at(id).Take(std::chrono::steady_clock::now())) {
403 metrics_.AddChatLine("refused");
404 Notify(id, Msg("You're talking too fast, so nobody heard that."));
405 return;
406 }
407 const std::optional<std::string> clean = CleanChat(text);
408 if (!clean) {
409 metrics_.AddChatLine("refused");
410 return;
411 }
412 metrics_.AddChatLine("said");
413 protocol::Chat* line = chat_.add_chat();
414 line->set_name(WorldOf(id)->players().at(id).name);
415 line->set_text(*clean);
416 std::cout << line->name() << ": " << line->text() << std::endl;
417}
418
419void Server::Talk(uint32_t id, const protocol::Talk& talk) {
420 const World& land = *WorldOf(id);
421 const Player& player = land.players().at(id);
422 // Each land counts its NPCs from one, so we look in the player's land.
423 const auto found = land.npcs().find(talk.npc());
424 if (found == land.npcs().end() || !found->second.talks) {
425 metrics_.AddStory("refused");
426 return;
427 }
428 const Npc& npc = found->second;
429 if (std::hypot(npc.x - player.x, npc.z - player.z) > World::kTalkReach) {
430 metrics_.AddStory("refused");
431 Notify(id, Msg("You're too far away to talk to the $0.", Of(npc)));
432 return;
433 }
434 const std::optional<std::string> words = CleanChat(talk.words());
435 const std::optional<std::string> prompt =
436 words ? StoryPrompt(*words) : std::nullopt;
437 if (!words || !prompt) {
438 metrics_.AddStory("refused");
439 return;
440 }
441 const auto asked = std::chrono::steady_clock::now();
442 if (!story_limits_.at(id).Take(asked)) {
443 metrics_.AddStory("refused");
444 // Translators: $0 is an NPC who tells stories.
445 Notify(id, Msg("The $0 needs a moment before the next story.", Of(npc)));
446 return;
447 }
448 std::cout << player.name << " asked the " << npc.name
449 << " for a story: " << *words << std::endl;
450 storyteller_.Tell(*prompt, [this, id, asked, kind = npc.kind](
451 const absl::StatusOr<std::string>& story) {
452 // The NPC speaks, by its kind, which each client names in its own
453 // language. The story is the storyteller's, in English.
454 protocol::World told;
455 if (story.ok()) {
456 metrics_.AddStory("told");
457 metrics_.ObserveStory(std::chrono::steady_clock::now() - asked);
458 for (const std::string& line : StoryLines(*story)) {
459 if (const std::optional<std::string> clean = CleanChat(line)) {
460 protocol::Chat* said = told.add_chat();
461 said->set_npc(kind);
462 said->set_text(*clean);
463 }
464 }
465 } else {
466 metrics_.AddStory("failed");
467 std::cerr << "no story for player " << id << ": " << story.status()
468 << "\n";
469 protocol::Chat* said = told.add_chat();
470 said->set_npc(kind);
471 *said->mutable_message() =
472 Msg("I can't think of a story right now.").message;
473 }
474 // The player may have left while the model wrote.
475 const auto session = sessions_.find(id);
476 if (session == sessions_.end()) {
477 return;
478 }
479 if (!told.chat().empty()) {
480 session->second->Send(Frame(told));
481 }
482 });
483}
484
485void Server::Learn(uint32_t id, const protocol::Learn& learn) {
486 World& land = *WorldOf(id);
487 const absl::Status learned = land.Learn(id, learn.npc(), learn.skill());
488 if (!learned.ok()) {
489 Notify(id, SentenceOf(learned));
490 return;
491 }
492 std::cout << land.players().at(id).name << " learned skill " << learn.skill()
493 << std::endl;
494}
495
496void Server::TakeQuest(uint32_t id, const protocol::Quest& quest) {
497 World& land = *WorldOf(id);
498 const absl::Status taken = land.TakeQuest(id, quest.npc(), quest.quest());
499 if (!taken.ok()) {
500 Notify(id, SentenceOf(taken));
501 return;
502 }
503 std::cout << land.players().at(id).name << " took quest " << quest.quest()
504 << std::endl;
505}
506
507void Server::TurnIn(uint32_t id, const protocol::Quest& quest) {
508 World& land = *WorldOf(id);
509 const absl::Status turned = land.TurnIn(id, quest.npc(), quest.quest());
510 if (!turned.ok()) {
511 Notify(id, SentenceOf(turned));
512 return;
513 }
514 std::cout << land.players().at(id).name << " turned in quest "
515 << quest.quest() << std::endl;
516}
517
518void Server::GiveUp(uint32_t id, uint32_t quest) {
519 World& land = *WorldOf(id);
520 const absl::Status given_up = land.GiveUp(id, quest);
521 if (!given_up.ok()) {
522 Notify(id, SentenceOf(given_up));
523 return;
524 }
525 std::cout << land.players().at(id).name << " gave up quest " << quest
526 << std::endl;
527}
528
529void Server::Enlist(uint32_t id, uint32_t npc) {
530 World& land = *WorldOf(id);
531 const absl::Status sworn = land.Enlist(id, npc);
532 if (!sworn.ok()) {
533 Notify(id, SentenceOf(sworn));
534 return;
535 }
536 const Player& player = land.players().at(id);
537 std::cout << player.name << " joined faction " << player.faction << std::endl;
538}
539
540void Server::Item(uint32_t id, const protocol::ItemAction& action) {
541 // The next instance loads the bag as it was last saved, so nothing changes
542 // it here after that.
543 if (handing_over_) {
544 return;
545 }
546 if (!item_limits_.at(id).Take(std::chrono::steady_clock::now())) {
547 Notify(id, Msg("You're moving things too fast."));
548 return;
549 }
550 const absl::Status done = DoItem(*WorldOf(id), id, action);
551 if (!done.ok()) {
552 Notify(id, SentenceOf(done));
553 }
554}
555
556void Server::Trade(uint32_t id, const protocol::TradeAction& action) {
557 // A trade changes two bags, which the next instance loads as they were
558 // last saved, so nothing trades here after that.
559 if (handing_over_) {
560 return;
561 }
562 // It's moving things too, so it's on the bag's limit.
563 if (!item_limits_.at(id).Take(std::chrono::steady_clock::now())) {
564 Notify(id, Msg("You're moving things too fast."));
565 return;
566 }
567 World& land = *WorldOf(id);
568 absl::Status done;
569 switch (action.action_case()) {
570 case protocol::TradeAction::kAsk:
571 done = land.AskToTrade(id, action.ask());
572 break;
573 case protocol::TradeAction::kOffer:
574 done = land.OfferToTrade(id, action.offer());
575 break;
576 case protocol::TradeAction::kReady: {
577 const absl::Time asked = absl::Now();
578 // What each side offers, for the trade's record, should this complete it.
579 const protocol::Trade offers = land.TradeOf(id);
580 const absl::StatusOr<uint32_t> traded =
581 land.ReadyToTrade(id, action.ready(), action.revision());
582 done = traded.status();
583 // Both bags go into Redis together, as they trade, before either player
584 // hears of it, so that a crash or a leave can't keep one and lose the
585 // other.
586 if (traded.value_or(0) == 0) {
587 break;
588 }
589 // A trade that's done is a trace of its own, from the ready that did it
590 // to the saver putting it into MySQL.
591 Span span = StartSpan("trade", SpanKind::kServer, SpanContext(), asked);
592 const Traded record{.id = RandomHex(),
593 .player = id,
594 .player_gave = offers.yours(),
595 .partner = *traded,
596 .partner_gave = offers.theirs()};
597 span.SetAttribute("nanommo.trade", record.id);
598 span.SetAttribute("nanommo.player", id);
599 span.SetAttribute("nanommo.partner", *traded);
600 // A save that failed, as when Redis is down, read as one that went
601 // through, which left the trade to whoever stayed: one who left kept
602 // what they gave in Redis, and one who stayed had it too once Redis was
603 // back, an item twice. A trade is saved, or called off.
604 const absl::StatusOr<std::set<uint32_t>> lost =
605 Save({id, *traded}, record);
606 if (!lost.ok() || !lost->empty()) {
607 span.SetError(lost.ok()
608 ? "a side's lease isn't this instance's any more"
609 : lost.status().ToString());
610 // One of them isn't this instance's any more, and another can have
611 // them as they were before the trade, or Redis couldn't take it, so
612 // neither keeps it: both go, unsaved, and come back with what Redis
613 // has, which the trade's one script wrote both bags of, or neither.
614 const std::string name = land.players().at(id).name;
615 const std::string partner = land.players().at(*traded).name;
616 Drop(id, "trade",
617 absl::StrCat("their trade with ", partner, " couldn't be saved"));
618 Drop(*traded, "trade",
619 absl::StrCat("their trade with ", name, " couldn't be saved"));
620 return;
621 }
622 break;
623 }
624 case protocol::TradeAction::kCancel:
625 land.CancelTrade(id);
626 break;
627 case protocol::TradeAction::ACTION_NOT_SET:
628 return;
629 }
630 if (!done.ok()) {
631 Notify(id, SentenceOf(done));
632 }
633}
634
635void Server::Duel(uint32_t id, const protocol::DuelAction& action) {
636 // The next instance has none of this one's duels.
637 if (handing_over_) {
638 return;
639 }
640 if (!duel_limits_.at(id).Take(std::chrono::steady_clock::now())) {
641 Notify(id, Msg("You're asking for duels too fast."));
642 return;
643 }
644 World& land = *WorldOf(id);
645 absl::Status done;
646 switch (action.action_case()) {
647 case protocol::DuelAction::kAsk:
648 done = land.AskToDuel(id, action.ask());
649 break;
650 case protocol::DuelAction::kAccept:
651 done = land.AnswerDuel(id, true);
652 break;
653 case protocol::DuelAction::kDecline:
654 done = land.AnswerDuel(id, false);
655 break;
656 case protocol::DuelAction::kYield:
657 done = land.Yield(id);
658 break;
659 case protocol::DuelAction::ACTION_NOT_SET:
660 return;
661 }
662 if (!done.ok()) {
663 Notify(id, SentenceOf(done));
664 }
665}
666
667void Server::Craft(uint32_t id, const protocol::CraftAction& action) {
668 // What's made goes into the bag, which the next instance loads as it was
669 // last saved, so nothing starts here after that.
670 if (handing_over_) {
671 return;
672 }
673 if (!craft_limits_.at(id).Take(std::chrono::steady_clock::now())) {
674 Notify(id, Msg("You're crafting too fast."));
675 return;
676 }
677 const absl::Status done = DoCraft(*WorldOf(id), id, action);
678 if (!done.ok()) {
679 Notify(id, SentenceOf(done));
680 }
681}
682
683void Server::Guild(uint32_t id, const protocol::GuildAction& action) {
684 // Like the bag, so that the next instance reads the guild as it'll stay.
685 if (handing_over_) {
686 return;
687 }
688 // A line of chat has the chat's own limit, and doesn't touch MySQL.
689 if (action.has_say()) {
690 GuildSay(id, action.say());
691 return;
692 }
693 if (!guild_limits_.at(id).Take(std::chrono::steady_clock::now())) {
694 Notify(id, Msg("You're doing that too fast."));
695 return;
696 }
697 switch (action.action_case()) {
698 case protocol::GuildAction::kCreate:
699 Found(id, action.create());
700 break;
701 case protocol::GuildAction::kInvite:
702 Ask(id, action.invite());
703 break;
704 case protocol::GuildAction::kAccept:
705 Join(id);
706 break;
707 case protocol::GuildAction::kDecline:
708 if (const absl::Status declined = guilds_.Decline(id); !declined.ok()) {
709 Refuse(id, declined);
710 }
711 break;
712 case protocol::GuildAction::kLeave:
713 QuitGuild(id);
714 break;
715 case protocol::GuildAction::kPromote:
716 SetRank(id, action.promote(), protocol::RANK_OFFICER);
717 break;
718 case protocol::GuildAction::kDemote:
719 SetRank(id, action.demote(), protocol::RANK_MEMBER);
720 break;
721 case protocol::GuildAction::kKick:
722 Kick(id, action.kick());
723 break;
724 case protocol::GuildAction::kDisband:
725 Disband(id);
726 break;
727 case protocol::GuildAction::kWar:
728 AskToWar(id, action.war());
729 break;
730 case protocol::GuildAction::kSay:
731 case protocol::GuildAction::ACTION_NOT_SET:
732 break;
733 }
734}
735
736void Server::Found(uint32_t id, const std::string& name) {
737 const absl::StatusOr<Membership> founded = guilds_.Create(name_, id, name);
738 if (!founded.ok()) {
739 Refuse(id, founded.status());
740 return;
741 }
742 members_[id] = *founded;
743 WorldOf(id)->SetGuild(id, founded->guild);
744 guild_news_.insert(id);
745 std::cout << WorldOf(id)->players().at(id).name << " founded "
746 << founded->name << std::endl;
747}
748
749void Server::Ask(uint32_t id, const std::string& name) {
750 // They have to be playing here, to see the question.
751 uint32_t asked = 0;
752 std::string asked_name;
753 for (const auto& [copy_id, copy] : copies_.all()) {
754 for (const auto& [other, player] : copy.world.players()) {
755 if (absl::EqualsIgnoreCase(player.name, name)) {
756 asked = other;
757 asked_name = player.name;
758 }
759 }
760 }
761 if (asked == 0) {
762 Notify(id, Msg("Nobody of that name is playing in $0 now.", Name(name_)));
763 return;
764 }
765 if (members_.contains(asked)) {
766 Notify(id, Msg("$0 is in a guild already.", Name(asked_name)));
767 return;
768 }
769 const absl::StatusOr<Membership> guild = guilds_.Invite(id, asked);
770 if (!guild.ok()) {
771 Refuse(id, guild.status());
772 return;
773 }
774 protocol::World question;
775 question.mutable_invite()->set_guild(guild->name);
776 question.mutable_invite()->set_from(WorldOf(id)->players().at(id).name);
777 sessions_.at(asked)->Send(Frame(question));
778 Notify(id,
779 Msg("You asked $0 to join $1.", Name(asked_name), Name(guild->name)));
780}
781
782void Server::Join(uint32_t id) {
783 const absl::StatusOr<Membership> joined = guilds_.Accept(id);
784 if (!joined.ok()) {
785 Refuse(id, joined.status());
786 return;
787 }
788 members_[id] = *joined;
789 WorldOf(id)->SetGuild(id, joined->guild);
790 RefreshGuild(joined->guild);
791 TellGuild(joined->guild,
792 Msg("$0 joined $1.", Name(WorldOf(id)->players().at(id).name),
793 Name(joined->name)));
794}
795
796void Server::QuitGuild(uint32_t id) {
797 const absl::StatusOr<Left> left = guilds_.Leave(id);
798 if (!left.ok()) {
799 Refuse(id, left.status());
800 return;
801 }
802 members_.erase(id);
803 WorldOf(id)->SetGuild(id, 0);
804 guild_news_.insert(id);
805 RefreshGuild(left->guild);
806 const Part who = Name(WorldOf(id)->players().at(id).name);
807 const Part guild = Name(left->name);
808 if (left->successor != 0) {
809 // If they're playing here, they see it at once.
810 if (const auto next = members_.find(left->successor);
811 next != members_.end()) {
812 next->second.rank = protocol::RANK_LEADER;
813 guild_news_.insert(left->successor);
814 }
815 // Translators: $2 is who leads the guild after them.
816 TellGuild(left->guild, Msg("$0 left $1. $2 leads it now.", who, guild,
817 Name(left->successor_name)));
818 } else {
819 TellGuild(left->guild, Msg("$0 left $1.", who, guild));
820 }
821 Notify(id, left->ended
822 ? Msg("You were the last in $0, so it's no more.", guild)
823 : Msg("You left $0.", guild));
824}
825
826void Server::SetRank(uint32_t id, uint32_t player, protocol::Rank rank) {
827 const absl::StatusOr<Changed> changed = guilds_.SetRank(id, player, rank);
828 if (!changed.ok()) {
829 Refuse(id, changed.status());
830 return;
831 }
832 if (const auto member = members_.find(player); member != members_.end()) {
833 member->second.rank = rank;
834 }
835 RefreshGuild(changed->guild);
836 const Part who = Name(changed->player_name);
837 TellGuild(changed->guild, rank == protocol::RANK_OFFICER
838 ? Msg("$0 is an officer now.", who)
839 : Msg("$0 is a member now.", who));
840}
841
842void Server::Kick(uint32_t id, uint32_t player) {
843 const absl::StatusOr<Changed> kicked = guilds_.Kick(id, player);
844 if (!kicked.ok()) {
845 Refuse(id, kicked.status());
846 return;
847 }
848 // If they're playing here, they hear it, and lose the name over their head.
849 if (members_.erase(player) > 0) {
850 WorldOf(player)->SetGuild(player, 0);
851 guild_news_.insert(player);
852 Notify(player, Msg("You were removed from $0.", Name(kicked->guild_name)));
853 }
854 RefreshGuild(kicked->guild);
855 TellGuild(
856 kicked->guild,
857 Msg("$0 removed $1 from $2.", Name(WorldOf(id)->players().at(id).name),
858 Name(kicked->player_name), Name(kicked->guild_name)));
859}
860
861void Server::Disband(uint32_t id) {
862 const absl::StatusOr<Membership> ended = guilds_.Disband(id);
863 if (!ended.ok()) {
864 Refuse(id, ended.status());
865 return;
866 }
867 TellGuild(ended->guild,
868 Msg("$0 disbanded $1.", Name(WorldOf(id)->players().at(id).name),
869 Name(ended->name)));
870 // Everyone in it who's playing here is in no guild now.
871 std::erase_if(members_, [&](const auto& member) {
872 if (member.second.guild != ended->guild) {
873 return false;
874 }
875 WorldOf(member.first)->SetGuild(member.first, 0);
876 guild_news_.insert(member.first);
877 return true;
878 });
879}
880
881void Server::AskToWar(uint32_t id, const std::string& name) {
882 const absl::StatusOr<War> war = guilds_.AskToWar(name_, id, name);
883 if (!war.ok()) {
884 Refuse(id, war.status());
885 return;
886 }
887 // Asked: the other guild's players here hear it in their chat.
888 if (war->id == 0) {
889 // Translators: /war is the chat's command, which stays as it is, and $0
890 // the guild that asks.
891 TellGuild(war->challenged,
892 Msg("$0 asks $1 to war. Your leader types /war $0 to say yes.",
893 Name(war->challenger_name), Name(war->challenged_name)),
894 protocol::CHANNEL_GUILD);
895 Notify(id, Msg("You asked $0 to war.", Name(war->challenged_name)));
896 return;
897 }
898 // Started: each copy of each land has it at once, and both guilds hear.
899 std::cout << war->challenger_name << " and " << war->challenged_name
900 << " went to war" << std::endl;
901 wars_.push_back(*war);
902 copies_.SetWars(wars_);
903 const uint64_t minutes = Guilds::kWarLength.count();
904 const Sentence news =
905 MsgN("$0 and $1 are at war, for $2 minute.",
906 "$0 and $1 are at war, for $2 minutes.", minutes,
907 Name(war->challenger_name), Name(war->challenged_name), minutes);
908 for (const uint32_t guild : {war->challenger, war->challenged}) {
909 TellGuild(guild, news, protocol::CHANNEL_GUILD);
910 RefreshGuild(guild);
911 }
912}
913
914void Server::ReadWars() {
915 const auto now = std::chrono::steady_clock::now();
916 if (now - wars_read_ < kReadWarsEvery) {
917 return;
918 }
919 wars_read_ = now;
920 absl::StatusOr<std::vector<War>> read = guilds_.Wars(name_);
921 if (!read.ok()) {
922 std::cerr << "couldn't read the wars: " << read.status() << "\n";
923 return;
924 }
925 // A war that's gone is over, and both guilds hear so. One that's started
926 // since, as on another instance, or whose score has moved, goes to both
927 // with their next news.
928 for (const War& war : wars_) {
929 if (std::ranges::find(*read, war.id, &War::id) != read->end()) {
930 continue;
931 }
932 const Sentence news =
933 Msg("The war between $0 and $1 is over.", Name(war.challenger_name),
934 Name(war.challenged_name));
935 for (const uint32_t guild : {war.challenger, war.challenged}) {
936 TellGuild(guild, news, protocol::CHANNEL_GUILD);
937 RefreshGuild(guild);
938 }
939 }
940 for (const War& war : *read) {
941 const auto before = std::ranges::find(wars_, war.id, &War::id);
942 if (before == wars_.end() ||
943 before->challenger_kills != war.challenger_kills ||
944 before->challenged_kills != war.challenged_kills) {
945 RefreshGuild(war.challenger);
946 RefreshGuild(war.challenged);
947 }
948 }
949 wars_ = *std::move(read);
950 copies_.SetWars(wars_);
951}
952
953void Server::TellKills(const std::vector<WarKill>& kills) {
954 for (const WarKill& kill : kills) {
955 const Sentence news =
956 Msg("$0 killed $1.",
957 Name(WorldOf(kill.killer)->players().at(kill.killer).name),
958 Name(WorldOf(kill.victim)->players().at(kill.victim).name));
959 std::cout << news.english << std::endl;
960 TellGuild(kill.guild, news, protocol::CHANNEL_GUILD);
961 if (const War* war = WarOf(kill.guild); war != nullptr) {
962 TellGuild(war->Against(kill.guild), news, protocol::CHANNEL_GUILD);
963 }
964 }
965}
966
967const War* Server::WarOf(uint32_t guild) const {
968 const auto war = std::ranges::find_if(wars_, [guild](const War& war) {
969 return war.challenger == guild || war.challenged == guild;
970 });
971 return war != wars_.end() ? &*war : nullptr;
972}
973
974void Server::GuildSay(uint32_t id, const std::string& text) {
975 const auto member = members_.find(id);
976 if (member == members_.end()) {
977 Notify(id, Msg("You're in no guild."));
978 return;
979 }
980 if (!chat_limits_.at(id).Take(std::chrono::steady_clock::now())) {
981 metrics_.AddChatLine("refused");
982 Notify(id, Msg("You're talking too fast, so nobody heard that."));
983 return;
984 }
985 const std::optional<std::string> clean = CleanChat(text);
986 if (!clean) {
987 metrics_.AddChatLine("refused");
988 return;
989 }
990 metrics_.AddChatLine("said");
991 protocol::World said;
992 protocol::Chat* line = said.add_chat();
993 line->set_name(WorldOf(id)->players().at(id).name);
994 line->set_text(*clean);
995 line->set_channel(protocol::CHANNEL_GUILD);
996 std::cout << "[" << member->second.name << "] " << line->name() << ": "
997 << line->text() << std::endl;
998 // Serialized once, for all of them, like the world's chat.
999 const auto bytes =
1000 std::make_shared<const std::string>(said.SerializeAsString());
1001 for (const auto& [other, membership] : members_) {
1002 if (membership.guild == member->second.guild) {
1003 metrics_.AddBytesSent(kHeaderSize + bytes->size());
1004 sessions_.at(other)->Send(bytes, {});
1005 }
1006 }
1007}
1008
1009void Server::RefreshGuild(uint32_t guild) {
1010 for (const auto& [id, membership] : members_) {
1011 if (membership.guild == guild) {
1012 guild_news_.insert(id);
1013 }
1014 }
1015}
1016
1017void Server::TellGuild(uint32_t guild, const Sentence& news,
1018 protocol::Channel channel) {
1019 for (const auto& [id, membership] : members_) {
1020 if (membership.guild == guild) {
1021 Notify(id, news, channel);
1022 }
1023 }
1024}
1025
1026void Server::Refuse(uint32_t id, const absl::Status& why) {
1027 if (absl::IsUnavailable(why) || absl::IsInternal(why) ||
1028 absl::IsAborted(why)) {
1029 std::cerr << "a guild action of player " << id << " failed: " << why
1030 << "\n";
1031 Notify(id, Msg("That didn't work. Try again."));
1032 return;
1033 }
1034 Notify(id, SentenceOf(why));
1035}
1036
1037void Server::Notify(uint32_t id, const Sentence& said,
1038 protocol::Channel channel) {
1039 Notify(id, said.message, channel);
1040}
1041
1042void Server::Notify(uint32_t id, const protocol::Message& message,
1043 protocol::Channel channel) {
1044 protocol::World notice;
1045 protocol::Chat* line = notice.add_chat();
1046 *line->mutable_message() = message;
1047 line->set_channel(channel);
1048 sessions_.at(id)->Send(Frame(notice));
1049}
1050
1051void Server::Receive() {
1052 udp_.async_receive_from(
1053 asio::buffer(datagram_), sender_,
1054 [this](std::error_code error, std::size_t size) {
1055 protocol::Hello hello;
1056 if (!error &&
1057 hello.ParseFromArray(datagram_.data(), static_cast<int>(size))) {
1058 const auto token = udp_tokens_.find(hello.token());
1059 if (token != udp_tokens_.end()) {
1060 udp_clients_[token->second] = sender_;
1061 }
1062 }
1063 Receive();
1064 });
1065}
1066
1067int Server::HandOver(const std::string& host, uint16_t port) {
1068 // A trace of its own, which each player's hello on the next instance carries
1069 // on, from the token they're given.
1070 Span span = StartSpan("hand over", SpanKind::kInternal);
1071 span.SetAttribute("nanommo.next", absl::StrCat(host, ":", port));
1072 // The next instance loads each player from Redis, so they go in now, and
1073 // nothing changes them here afterwards. Those in a dungeon come out of it
1074 // there, as its copy stays here.
1075 handing_over_ = true;
1076 std::error_code ignored;
1077 acceptor_.close(ignored);
1078 SaveChanged();
1079 // The next instance has none of this one's duels, so each is off, and both
1080 // sides hear so before they're told to go.
1081 const Sentence off =
1082 Msg("The duel's off, as the world moves to its next instance.");
1083 for (const auto& [id, session] : sessions_) {
1084 if (const uint32_t other = WorldOf(id)->CallOffDuel(id); other != 0) {
1085 Notify(id, off);
1086 Notify(other, off);
1087 }
1088 }
1089 SendDuels();
1090 // The next instance turns away a player whose lease this one has, so their
1091 // leases go to it first, with newer fencing numbers. It's named as in
1092 // Consul, by its world and its port.
1093 const absl::StatusOr<std::set<uint32_t>> passed =
1094 players_.Pass(name_, leases_, InstanceId({.name = name_, .port = port}));
1095 if (!passed.ok()) {
1096 std::cerr << "couldn't hand the leases over: " << passed.status() << "\n";
1097 span.SetError(passed.status().ToString());
1098 return 0;
1099 }
1100 int told = 0;
1101 for (const auto& [id, session] : sessions_) {
1102 if (!passed->contains(id)) {
1103 std::cerr << "couldn't hand player " << id
1104 << " over: their lease isn't this instance's\n";
1105 continue;
1106 }
1107 // It's the next instance's now, which leaving here leaves alone.
1108 leases_.erase(id);
1109 // Tokens are one-time, and the player's own is used, so each move gets a
1110 // token of its own.
1111 const absl::StatusOr<std::string> token = tokens_.Issue(id);
1112 if (!token.ok()) {
1113 std::cerr << "couldn't hand player " << id << " over: " << token.status()
1114 << "\n";
1115 continue;
1116 }
1117 protocol::World move;
1118 move.mutable_move()->set_host(host);
1119 move.mutable_move()->set_port(port);
1120 move.mutable_move()->set_token(*token);
1121 session->Send(Frame(move));
1122 ++told;
1123 }
1124 span.SetAttribute("nanommo.players", told);
1125 return told;
1126}
1127
1128void Server::Tick() {
1129 ZoneScoped;
1130 if (handing_over_) {
1131 return;
1132 }
1133 const auto start = std::chrono::steady_clock::now();
1134 ApplyInputs();
1135 ReadWars();
1136 copies_.Step(interval_);
1137 for (const Notice& notice : copies_.TakeNotices()) {
1138 if (sessions_.contains(notice.player)) {
1139 Notify(notice.player, notice.message, notice.channel);
1140 }
1141 }
1142 std::vector<WarKill> kills = copies_.TakeWarKills();
1143 TellKills(kills);
1144 // A victim scores for a war once every five minutes at most: the kill
1145 // happened, and both guilds heard, but it goes no further.
1146 std::erase_if(kills, [this, start](const WarKill& kill) {
1147 return !scoring_.Scores(kill, start);
1148 });
1149 // Each has an id of its own, as a trade's record does, so that the saver
1150 // records it once, however many times it reads it.
1151 for (WarKill& kill : kills) {
1152 kill.id = RandomHex();
1153 }
1154 // Counted as they go to the saver, so that the wars' scores in MySQL can be
1155 // checked against what the worlds saw.
1156 metrics_.AddWarKills(kills.size());
1157 const std::vector<Event> happened = copies_.TakeEvents();
1158 RecordEvents(happened);
1159 std::array<std::size_t, kLands.size()> in_land{};
1160 std::array<std::size_t, kLands.size()> copies_of{};
1161 for (const auto& [id, copy] : copies_.all()) {
1162 in_land[copy.land] += copy.world.players().size();
1163 ++copies_of[copy.land];
1164 }
1165 for (std::size_t land = 0; land < kLands.size(); ++land) {
1166 metrics_.SetPlayers(kLands[land].name, in_land[land]);
1167 metrics_.SetCopies(kLands[land].name, copies_of[land]);
1168 }
1169 SaveChanged(kills);
1170 RenewLeases();
1171 Broadcast();
1172 ShowEvents(happened);
1173 SendChat();
1174 SendBags();
1175 SendQuests();
1176 SendGuilds();
1177 SendTrades();
1178 SendDuels();
1179 metrics_.ObserveTick(std::chrono::steady_clock::now() - start);
1180 TracyPlot("players", static_cast<int64_t>(players()));
1181 FrameMark;
1182 // From the last expiry, not from now, so that the ticks don't drift, unless
1183 // the world's so far behind that it lets the ticks it missed go.
1184 const auto now = std::chrono::steady_clock::now();
1185 const auto next = NextTick(timer_.expiry(), now, interval_);
1186 if (next != timer_.expiry() + interval_) {
1187 std::cout << "nanommo server: "
1188 << absl::FormatDuration(
1189 absl::FromChrono(now - timer_.expiry() - interval_))
1190 << " behind, so the ticks missed are let go" << std::endl;
1191 }
1192 timer_.expires_at(next);
1193 timer_.async_wait([this](std::error_code) { Tick(); });
1194}
1195
1196void Server::ApplyInputs() {
1197 inputs_.Apply([this](uint32_t id) { return WorldOf(id); });
1198}
1199
1200void Server::SaveChanged(const std::vector<WarKill>& kills) {
1201 ZoneScoped;
1202 const auto start = std::chrono::steady_clock::now();
1203 std::vector<uint32_t> everyone;
1204 for (const auto& [copy_id, copy] : copies_.all()) {
1205 for (const auto& [id, player] : copy.world.players()) {
1206 everyone.push_back(id);
1207 }
1208 }
1209 // Those whose leases aren't this instance's any more go, and the rest are
1210 // saved without them, with the kills.
1211 for (absl::StatusOr<std::set<uint32_t>> lost =
1212 Save(everyone, std::nullopt, kills);
1213 lost.ok() && !lost->empty();
1214 lost = Save(everyone, std::nullopt, kills)) {
1215 for (const uint32_t id : *lost) {
1216 Drop(id, "lease", "their lease isn't this instance's any more");
1217 }
1218 std::erase_if(everyone,
1219 [&lost](uint32_t id) { return lost->contains(id); });
1220 }
1221 metrics_.ObserveSave(std::chrono::steady_clock::now() - start);
1222}
1223
1224void Server::RenewLeases() {
1225 const auto now = std::chrono::steady_clock::now();
1226 if (now - renewed_ < kRenewEvery) {
1227 return;
1228 }
1229 renewed_ = now;
1230 // All of them in one round trip, as the tick waits for it.
1231 const absl::StatusOr<std::set<uint32_t>> lost =
1232 players_.Renew(name_, leases_);
1233 if (!lost.ok()) {
1234 std::cerr << "couldn't renew " << leases_.size()
1235 << " leases: " << lost.status() << "\n";
1236 return;
1237 }
1238 // Another instance can take them once their lease runs out, as it does if
1239 // this one stalls, and it's that one that saves them then.
1240 for (const uint32_t id : *lost) {
1241 std::cout << WorldOf(id)->players().at(id).name << "'s lease isn't "
1242 << leases_.at(id) << " any more" << std::endl;
1243 Drop(id, "lease", "their lease isn't this instance's any more");
1244 }
1245}
1246
1247absl::StatusOr<std::set<uint32_t>> Server::Save(
1248 const std::vector<uint32_t>& ids, const std::optional<Traded>& traded,
1249 const std::vector<WarKill>& kills) {
1250 std::map<uint32_t, Progress> changed;
1251 std::map<uint32_t, protocol::Inventory> bags;
1252 std::map<uint32_t, std::string> leases;
1253 for (const uint32_t id : ids) {
1254 // One whose lease is gone isn't this instance's to save.
1255 const auto lease = leases_.find(id);
1256 if (lease == leases_.end()) {
1257 continue;
1258 }
1259 const Player& player = WorldOf(id)->players().at(id);
1260 const Progress progress = ProgressOf(player);
1261 if (progress != saved_[id]) {
1262 // The bag goes too only when its revision has moved.
1263 if (progress.items_revision != saved_[id].items_revision) {
1264 bags[id] = player.inventory.items();
1265 }
1266 changed[id] = progress;
1267 leases[id] = lease->second;
1268 }
1269 }
1270 const absl::StatusOr<std::set<uint32_t>> lost =
1271 players_.Save(name_, changed, bags, leases, traded, kills);
1272 if (!lost.ok()) {
1273 std::cerr << "couldn't save " << changed.size()
1274 << " players: " << lost.status() << "\n";
1275 return lost.status();
1276 }
1277 for (const uint32_t id : *lost) {
1278 std::cout << "couldn't save " << WorldOf(id)->players().at(id).name
1279 << ", as their lease isn't " << leases.at(id) << " any more"
1280 << std::endl;
1281 }
1282 if (lost->empty()) {
1283 for (const auto& [id, progress] : changed) {
1284 saved_[id] = progress;
1285 }
1286 }
1287 return *lost;
1288}
1289
1290void Server::Drop(uint32_t id, const char* kind, std::string_view why) {
1291 std::cout << "dropped " << WorldOf(id)->players().at(id).name
1292 << " without saving them, as " << why << TraceField() << std::endl;
1293 metrics_.AddDropped(kind);
1294 // So that leaving doesn't save them. A lease that's still this instance's
1295 // goes, so that they can come back at once.
1296 if (const auto lease = leases_.find(id); lease != leases_.end()) {
1297 players_.Release(name_, id, lease->second).IgnoreError();
1298 leases_.erase(lease);
1299 }
1300 sessions_.at(id)->Close();
1301}
1302
1303void Server::RecordEvents(const std::vector<Event>& happened) {
1304 ZoneScoped;
1305 if (happened.empty()) {
1306 return;
1307 }
1308 const absl::Time now = absl::Now();
1309 std::vector<std::string> rows;
1310 rows.reserve(happened.size());
1311 for (const Event& event : happened) {
1312 if (ForAnalytics(event.kind)) {
1313 rows.push_back(Row(event, copies_.content(), name_, now));
1314 }
1315 }
1316 if (rows.empty()) {
1317 return;
1318 }
1319 // The game goes on without its analytics.
1320 const absl::Status added = events_.Add(rows);
1321 if (!added.ok()) {
1322 std::cerr << "couldn't record " << rows.size() << " events: " << added
1323 << "\n";
1324 }
1325}
1326
1327void Server::ShowEvents(const std::vector<Event>& happened) {
1328 ZoneScoped;
1329 // Each player's events go together, in a message a tick.
1330 std::map<uint32_t, protocol::World> shown;
1331 for (const Event& event : happened) {
1332 const std::optional<protocol::Event> for_players = ForPlayers(event);
1333 const auto copy = copies_.all().find(event.copy);
1334 if (!for_players || copy == copies_.all().end()) {
1335 continue;
1336 }
1337 const protocol::Event& seen = *for_players;
1338 const Cell cell = CellOf(event.x, event.z);
1339 for (const auto& [id, player] : copy->second.world.players()) {
1340 if (sessions_.contains(id) && Near(CellOf(player.x, player.z), cell)) {
1341 *shown[id].add_events() = seen;
1342 }
1343 }
1344 }
1345 for (const auto& [id, events] : shown) {
1346 std::string frame = Frame(events);
1347 metrics_.AddBytesSent(frame.size());
1348 sessions_.at(id)->Send(std::move(frame));
1349 }
1350}
1351
1352void Server::Broadcast() {
1353 ZoneScoped;
1354 // Names, kinds, levels, weapons and the most health a unit can have change
1355 // now and then, and looks and NPCs never do, so they go out once a second,
1356 // and the clients keep them in between.
1357 const bool full = broadcasts_ == 0;
1358 broadcasts_ = (broadcasts_ + 1) % kFullEvery;
1359 for (const auto& [id, copy] : copies_.all()) {
1360 BroadcastCopy(copy, full);
1361 }
1362}
1363
1364void Server::BroadcastCopy(const Copy& copy, bool full) {
1365 const World& land = copy.world;
1366 // A dungeon's copy waits for its player with nobody to send it to.
1367 if (land.players().empty()) {
1368 return;
1369 }
1370 // Each player and monster is serialized once a tick, and what each cell
1371 // gets is put together from those pieces.
1372 std::map<uint32_t, std::string> players;
1373 std::map<uint32_t, std::string> monsters;
1374 std::map<uint32_t, std::string> npcs;
1375 {
1376 ZoneScopedN("serialize");
1377 for (const auto& [id, player] : land.players()) {
1378 protocol::Player entry = ToProtocol(id, player);
1379 if (!full) {
1380 entry.clear_name();
1381 entry.clear_looks();
1382 entry.clear_level();
1383 entry.clear_max_health();
1384 entry.clear_weapon();
1385 entry.clear_faction();
1386 } else if (const auto member = members_.find(id);
1387 member != members_.end()) {
1388 // Their guild goes with their name, once a second.
1389 entry.set_guild(member->second.name);
1390 }
1391 players[id] = Piece(entry);
1392 }
1393 for (const auto& [id, monster] : land.monsters()) {
1394 protocol::Monster entry = ToProtocol(id, monster);
1395 if (!full) {
1396 entry.clear_kind();
1397 entry.clear_level();
1398 entry.clear_max_health();
1399 }
1400 monsters[id] = Piece(entry);
1401 }
1402 if (full) {
1403 for (const auto& [id, npc] : land.npcs()) {
1404 npcs[id] = Piece(ToProtocol(id, npc));
1405 }
1406 }
1407 }
1408 const int64_t sent = NowMicros();
1409 // The same for everyone in the land, from the wall clock.
1410 const protocol::Sky sky = SkyAt(copy.land, UnixMs());
1411 for (const auto& [cell, view] :
1412 Views(land.players(), land.monsters(), copy.npc_cells)) {
1413 for (const uint32_t id : view.here) {
1414 const auto session = sessions_.find(id);
1415 if (session == sessions_.end()) {
1416 continue;
1417 }
1418 // Each client's world is its own now, as each has a world of its own
1419 // whole, and what's changed since differs.
1420 std::string still;
1421 std::vector<std::string_view> pieces =
1422 Delta(id, copy, view, players, monsters, sent, still);
1423 if (full) {
1424 for (const uint32_t npc : view.npcs) {
1425 pieces.push_back(npcs.at(npc));
1426 }
1427 }
1428 protocol::World you =
1429 YouIn(id, land.players().at(id), seed_ + kLands[copy.land].seed,
1430 copy.land, inputs_.acked(id));
1431 *you.mutable_sky() = sky;
1432 std::string own = you.SerializeAsString();
1433 const auto udp = udp_clients_.find(id);
1434 if (udp != udp_clients_.end()) {
1435 // A datagram arrives whole or not at all, so it needs no size in front.
1436 for (std::string& part : Split(pieces, sent)) {
1437 const auto bytes =
1438 std::make_shared<const std::string>(std::move(part));
1439 metrics_.AddBytesSent(bytes->size() + own.size());
1440 SendTo(udp->second, bytes, own);
1441 }
1442 } else {
1443 protocol::World stamp;
1444 stamp.set_sent(sent);
1445 std::string bytes = stamp.SerializeAsString();
1446 for (const std::string_view piece : pieces) {
1447 bytes.append(piece);
1448 }
1449 const auto whole =
1450 std::make_shared<const std::string>(std::move(bytes));
1451 metrics_.AddBytesSent(kHeaderSize + whole->size() + own.size());
1452 session->second->Send(whole, std::move(own));
1453 }
1454 }
1455 }
1456}
1457
1458std::vector<std::string_view> Server::Delta(
1459 uint32_t id, const Copy& copy, const View& view,
1460 const std::map<uint32_t, std::string>& players,
1461 const std::map<uint32_t, std::string>& monsters, int64_t sent,
1462 std::string& still) {
1463 std::map<int64_t, Sent>& history = history_[id];
1464 // The world the client has whole, if we still have what we sent in it,
1465 // and it was in this copy of the land.
1466 const auto seen = seen_.find(id);
1467 auto baseline = history.end();
1468 if (seen != seen_.end()) {
1469 const auto found = history.find(seen->second);
1470 if (found != history.end() && found->second.copy == &copy) {
1471 baseline = found;
1472 }
1473 }
1474 Sent& now = history[sent];
1475 now.copy = &copy;
1476 std::vector<std::string_view> pieces;
1477 // Whether the piece has changed since the world the client has, which it
1478 // then needs. Either way, this world has it. Each world sent since has to
1479 // have had it the same too, as the client may have had those: one that
1480 // changed and changed back would leave it with the change.
1481 const auto changed = [&](uint64_t key, std::string_view piece) {
1482 const std::size_t hash = std::hash<std::string_view>{}(piece);
1483 now.pieces[key] = hash;
1484 bool same = baseline != history.end();
1485 // The end too, should the clock have stepped back past the client's.
1486 for (auto world = baseline;
1487 same && world != history.end() && world->first != sent; ++world) {
1488 const auto before = world->second.pieces.find(key);
1489 same = world->second.copy == &copy &&
1490 before != world->second.pieces.end() && before->second == hash;
1491 }
1492 if (same) {
1493 return false;
1494 }
1495 pieces.push_back(piece);
1496 return true;
1497 };
1498 protocol::World unchanged;
1499 for (const uint32_t player : view.players) {
1500 if (!changed(player, players.at(player))) {
1501 unchanged.add_still_players(player);
1502 }
1503 }
1504 // A monster's id goes above a player's, as the two count apart.
1505 for (const uint32_t monster : view.monsters) {
1506 if (!changed(uint64_t{1} << 32 | monster, monsters.at(monster))) {
1507 unchanged.add_still_monsters(monster);
1508 }
1509 }
1510 if (unchanged.still_players_size() + unchanged.still_monsters_size() > 0) {
1511 still = unchanged.SerializeAsString();
1512 pieces.push_back(still);
1513 }
1514 // The client never asks for one older than the world it has, and a second
1515 // of them is plenty.
1516 if (seen != seen_.end()) {
1517 history.erase(history.begin(), history.lower_bound(seen->second));
1518 }
1519 while (history.size() > kMostRemembered) {
1520 history.erase(history.begin());
1521 }
1522 return pieces;
1523}
1524
1525void Server::SendChat() {
1526 if (chat_.chat().empty()) {
1527 return;
1528 }
1529 // Each line has to arrive, so it goes over TCP, even to a client that gets
1530 // the world over UDP. Everyone in the world hears it, in all its lands.
1531 const auto bytes =
1532 std::make_shared<const std::string>(chat_.SerializeAsString());
1533 for (const auto& [id, session] : sessions_) {
1534 metrics_.AddBytesSent(kHeaderSize + bytes->size());
1535 session->Send(bytes, {});
1536 }
1537 chat_.Clear();
1538}
1539
1540void Server::SendBags() {
1541 for (const auto& [copy_id, copy] : copies_.all()) {
1542 for (const auto& [id, player] : copy.world.players()) {
1543 const uint32_t revision = player.inventory.revision();
1544 const auto session = sessions_.find(id);
1545 // A bag changes now and then, and has to arrive, so it goes on its own,
1546 // over TCP, only when it has.
1547 if (session == sessions_.end() || sent_bags_[id] == revision) {
1548 continue;
1549 }
1550 std::string frame = Frame(BagOf(player));
1551 metrics_.AddBytesSent(frame.size());
1552 session->second->Send(std::move(frame));
1553 sent_bags_[id] = revision;
1554 }
1555 }
1556}
1557
1558void Server::SendQuests() {
1559 for (const auto& [copy_id, copy] : copies_.all()) {
1560 for (const auto& [id, player] : copy.world.players()) {
1561 const auto session = sessions_.find(id);
1562 const auto sent = sent_quests_.find(id);
1563 // Like a bag, but each player gets theirs as they join, none included,
1564 // as a quest's revision starts again from zero with each login.
1565 if (session == sessions_.end() ||
1566 (sent != sent_quests_.end() &&
1567 sent->second == player.quests_revision)) {
1568 continue;
1569 }
1570 std::string frame = Frame(QuestsOf(player));
1571 metrics_.AddBytesSent(frame.size());
1572 session->second->Send(std::move(frame));
1573 sent_quests_[id] = player.quests_revision;
1574 }
1575 }
1576}
1577
1578void Server::SendGuilds() {
1579 // Each guild's roster is read once, for all its players who get news.
1580 std::map<uint32_t, std::vector<protocol::GuildMember>> rosters;
1581 for (const uint32_t id : guild_news_) {
1582 const auto session = sessions_.find(id);
1583 if (session == sessions_.end()) {
1584 continue;
1585 }
1586 // An empty guild, for none, still says so.
1587 protocol::World news;
1588 protocol::Guild* guild = news.mutable_guild();
1589 if (const auto member = members_.find(id); member != members_.end()) {
1590 guild->set_name(member->second.name);
1591 guild->set_rank(member->second.rank);
1592 auto roster = rosters.find(member->second.guild);
1593 if (roster == rosters.end()) {
1594 roster =
1595 rosters.emplace(member->second.guild, Roster(member->second.guild))
1596 .first;
1597 }
1598 guild->mutable_members()->Add(roster->second.begin(),
1599 roster->second.end());
1600 // Each side's kills, from theirs.
1601 if (const War* war = WarOf(member->second.guild); war != nullptr) {
1602 const bool challenger = war->challenger == member->second.guild;
1603 protocol::GuildWar* shown = guild->mutable_war();
1604 shown->set_enemy(challenger ? war->challenged_name
1605 : war->challenger_name);
1606 shown->set_kills(challenger ? war->challenger_kills
1607 : war->challenged_kills);
1608 shown->set_enemy_kills(challenger ? war->challenged_kills
1609 : war->challenger_kills);
1610 shown->set_left(static_cast<uint32_t>(war->left.count()));
1611 }
1612 }
1613 std::string frame = Frame(news);
1614 metrics_.AddBytesSent(frame.size());
1615 session->second->Send(std::move(frame));
1616 }
1617 guild_news_.clear();
1618}
1619
1620void Server::SendTrades() {
1621 // A trade has to arrive, as a bag does, so it goes on its own, over TCP, to
1622 // each side, and with nobody in it once it's over.
1623 for (const uint32_t id : copies_.TakeTradeNews()) {
1624 const auto session = sessions_.find(id);
1625 const World* land = WorldOf(id);
1626 if (session == sessions_.end() || land == nullptr) {
1627 continue;
1628 }
1629 protocol::World news;
1630 *news.mutable_trade() = land->TradeOf(id);
1631 std::string frame = Frame(news);
1632 metrics_.AddBytesSent(frame.size());
1633 session->second->Send(std::move(frame));
1634 }
1635}
1636
1637void Server::SendDuels() {
1638 // Like a trade, on its own, over TCP, to each side, and with nobody in it
1639 // once it's over.
1640 for (const uint32_t id : copies_.TakeDuelNews()) {
1641 const auto session = sessions_.find(id);
1642 const World* land = WorldOf(id);
1643 if (session == sessions_.end() || land == nullptr) {
1644 continue;
1645 }
1646 protocol::World news;
1647 *news.mutable_duel() = land->DuelOf(id);
1648 std::string frame = Frame(news);
1649 metrics_.AddBytesSent(frame.size());
1650 session->second->Send(std::move(frame));
1651 }
1652}
1653
1654std::vector<protocol::GuildMember> Server::Roster(uint32_t guild) {
1655 absl::StatusOr<std::vector<protocol::GuildMember>> roster =
1656 guilds_.Roster(guild);
1657 if (!roster.ok()) {
1658 std::cerr << "couldn't read guild " << guild
1659 << "'s roster: " << roster.status() << "\n";
1660 return {};
1661 }
1662 for (protocol::GuildMember& member : *roster) {
1663 if (World* land = WorldOf(member.id()); land != nullptr) {
1664 member.set_online(true);
1665 member.set_level(static_cast<uint32_t>(
1666 LevelFor(land->players().at(member.id()).experience).number));
1667 }
1668 }
1669 return *std::move(roster);
1670}
1671
1672void Server::SendTo(const asio::ip::udp::endpoint& client,
1673 std::shared_ptr<const std::string> part, std::string own) {
1674 auto tail = std::make_shared<const std::string>(std::move(own));
1675 const std::array buffers{asio::buffer(*part), asio::buffer(*tail)};
1676 // The handler keeps the bytes alive until the datagram has gone.
1677 udp_.async_send_to(buffers, client,
1678 [part = std::move(part), tail = std::move(tail)](
1679 std::error_code, std::size_t) {});
1680}
1681
1682} // namespace nanommo
static absl::StatusOr< std::unique_ptr< Server > > Create(asio::io_context &io, uint16_t port, asio::ssl::context &tls, std::chrono::nanoseconds interval, std::string name, uint32_t seed, const Content &content, Metrics &metrics, Tokens &tokens, Players &players, Guilds &guilds, Events &events, Storyteller &storyteller)
Definition server.cc:124
int HandOver(const std::string &host, uint16_t port)
Definition server.cc:1067
int players() const
In all its lands.
Definition server.cc:159
uint16_t port() const
Definition server.cc:161
void SetAttribute(std::string_view key, std::string_view value)
Definition tracing.cc:314
void SetError(std::string_view message)
Marks it as failed, and why.
Definition tracing.cc:326
static constexpr float kTalkReach
Definition world.h:341
SkillTable Kick()
Definition chat.cc:9
Span StartSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:389
std::optional< protocol::Event > ForPlayers(const Event &event)
Definition shown.cc:151
absl::Status DoCraft(World &land, uint32_t id, const protocol::CraftAction &action)
Definition inputs.cc:101
Sentence MsgN(std::string_view one, std::string_view many, uint64_t count, Parts... parts)
Definition messages.h:100
const Gate & WayOut(int dungeon)
The dungeon's way out: its first gate.
Definition lands.cc:39
int64_t UnixMs()
Now, by the wall clock, in milliseconds since 1970.
Definition weather.cc:130
protocol::World YouIn(uint32_t id, const Player &player, uint32_t seed, int land, std::optional< uint32_t > acked)
Definition shown.cc:94
std::string InstanceId(const WorldRegistration &world)
Definition consul.cc:76
Sentence SentenceOf(const absl::Status &status)
Definition messages.cc:224
std::string RandomHex()
Definition tokens.cc:24
absl::Status ListenAndBind(asio::ip::tcp::acceptor &acceptor, asio::ip::udp::socket &socket, std::span< const uint16_t > ports)
Definition listen.cc:47
Level LevelFor(uint32_t experience)
Definition levels.cc:5
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
Definition websocket.cc:139
Place Arrival(const Gate &gate, float yaw)
Definition lands.cc:43
Cell CellOf(float x, float z)
Definition interest.cc:20
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14
constexpr std::array< Land, 3 > kLands
Definition lands.h:31
protocol::Sky SkyAt(int land, int64_t unix_ms)
Definition weather.cc:87
bool Near(Cell from, Cell to)
Definition interest.cc:25
absl::Status DoItem(World &land, uint32_t id, const protocol::ItemAction &action)
Definition inputs.cc:85
protocol::World BagOf(const Player &player)
Their bag, and their quests, each as it goes when it's changed.
Definition shown.cc:136
std::chrono::steady_clock::time_point NextTick(std::chrono::steady_clock::time_point due, std::chrono::steady_clock::time_point now, std::chrono::nanoseconds interval)
Definition tick.cc:16
std::string TraceField()
Definition tracing.cc:398
Sentence Msg(std::string_view text, Parts... parts)
Definition messages.h:92
std::vector< std::string > Split(const std::vector< std::string_view > &pieces, int64_t sent, std::size_t max_size)
Definition parts.cc:76
std::string Piece(const protocol::Player &player)
Definition parts.cc:58
protocol::World QuestsOf(const Player &player)
Definition shown.cc:142
protocol::Motion ToProtocol(Motion motion)
Definition shown.cc:11
Part Name(std::string_view name)
Definition messages.cc:113
int MaxHealthOf(const Player &player)
Definition world.cc:148
std::optional< std::string > StoryPrompt(std::string_view words)
Definition stories.cc:44
Part Of(const items::Item &item, uint32_t count)
Definition messages.cc:139
uint32_t MainHandOf(const Player &player)
Definition world.cc:189
int64_t NowMicros()
Definition clock.h:11
std::optional< std::string > CleanChat(std::string_view text)
Definition chat.cc:11
bool ForAnalytics(Event::Kind kind)
Definition events.cc:101
std::map< Cell, View > Views(const std::map< uint32_t, Player > &players, const std::map< uint32_t, Monster > &monsters, const Cells &npcs)
Definition interest.cc:30
std::string Row(const Event &event, const Content &content, std::string_view world, absl::Time time)
Definition events.cc:77
A ring of stones in a land, which takes players to another.
Definition lands.h:38
In metres from the middle of a land.
Definition lands.h:13
What we keep of a player from one session to the next.
Definition players.h:23