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"
28#include "protocol/nanommo.pb.h"
41#include "tracy/Tracy.hpp"
48constexpr int kFullEvery = 20;
51constexpr int kChatBurst = 5;
52constexpr std::chrono::seconds kChatRefill{2};
56constexpr int kStoryBurst = 1;
57constexpr std::chrono::seconds kStoryRefill{10};
61constexpr int kItemBurst = 10;
62constexpr std::chrono::milliseconds kItemRefill{100};
66constexpr std::size_t kMostRemembered = 20;
70constexpr int kGuildBurst = 3;
71constexpr std::chrono::seconds kGuildRefill{1};
75constexpr int kDuelBurst = 3;
76constexpr std::chrono::seconds kDuelRefill{1};
80constexpr int kCraftBurst = 3;
81constexpr std::chrono::seconds kCraftRefill{1};
85constexpr std::chrono::seconds kRenewEvery{1};
89constexpr std::chrono::seconds kReadWarsEvery{5};
94 .experience = player.experience,
95 .health = player.health,
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};
112 if (
kLands[player.land].dungeon) {
115 progress.x = outside.x;
116 progress.z = outside.z;
117 progress.land = out.to;
125 asio::io_context& io, uint16_t
port, asio::ssl::context& tls,
126 std::chrono::nanoseconds interval, std::string name, uint32_t seed,
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);
139Server::Server(asio::io_context& io, asio::ssl::context& tls,
140 std::chrono::nanoseconds interval, std::string name,
149 name_(std::move(name)),
151 copies_(seed, content),
157 storyteller_(storyteller) {}
162 std::error_code ignored;
163 return acceptor_.local_endpoint(ignored).port();
166absl::Status Server::Start(uint16_t port) {
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()) {
180 std::error_code ignored;
181 udp_.set_option(asio::socket_base::send_buffer_size(4 * 1024 * 1024),
185 timer_.expires_after(interval_);
186 timer_.async_wait([
this](std::error_code) { Tick(); });
187 return absl::OkStatus();
190World* Server::WorldOf(uint32_t
id) {
191 Copy* copy = copies_.Of(
id);
192 return copy !=
nullptr ? ©->world :
nullptr;
195void Server::Accept() {
196 acceptor_.async_accept([
this](std::error_code error,
197 asio::ip::tcp::socket socket) {
199 auto id = std::make_shared<uint32_t>(0);
201 const auto on_message = [
this, id](Session& session,
202 const std::string& bytes) {
203 metrics_.AddMessageReceived();
205 *
id = HandleHello(session, bytes);
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();
214 inputs_.Take(*land, *
id, input);
215 if (input.respawn()) {
218 if (input.has_walk_to()) {
219 land->WalkTo(*
id, {input.walk_to().x(), input.walk_to().z()});
221 if (input.skill() != 0) {
222 land->UseSkill(*
id, input.skill());
224 if (!input.say().empty()) {
225 Say(*
id, input.say());
227 if (input.has_talk()) {
228 Talk(*
id, input.talk());
230 if (input.has_learn()) {
231 Learn(*
id, input.learn());
233 if (input.has_take()) {
234 TakeQuest(*
id, input.take());
236 if (input.has_turn_in()) {
237 TurnIn(*
id, input.turn_in());
239 if (input.give_up() != 0) {
240 GiveUp(*
id, input.give_up());
242 if (input.enlist() != 0) {
243 Enlist(*
id, input.enlist());
245 if (input.has_item()) {
246 Item(*
id, input.item());
248 if (input.has_guild()) {
249 Guild(*
id, input.guild());
251 if (input.has_trade()) {
252 Trade(*
id, input.trade());
254 if (input.has_duel()) {
255 Duel(*
id, input.duel());
257 if (input.has_craft()) {
258 Craft(*
id, input.craft());
262 const auto on_close = [
this, id] {
267 std::make_shared<Session>(std::move(socket), tls_, on_message, on_close)
274uint32_t Server::HandleHello(
Session& session,
const std::string& bytes) {
277 const absl::Time arrived = absl::Now();
278 protocol::Hello hello;
280 const absl::StatusOr<uint32_t>
id =
281 hello.ParseFromString(bytes) ? tokens_.Redeem(hello.token(), &issuer)
282 : absl::InvalidArgumentError(
"not a hello");
284 if (!
id.ok() || WorldOf(*
id) !=
nullptr) {
286 if (!
id.ok() && !absl::IsNotFound(
id.status()) &&
287 !absl::IsInvalidArgument(
id.status())) {
288 std::cerr <<
"couldn't redeem a token: " <<
id.status() <<
TraceField()
290 span.SetError(
id.status().ToString());
292 std::cout <<
"refused a client: unknown token, or already playing"
294 span.SetAttribute(
"nanommo.refused",
"unknown token, or already playing");
299 span.SetAttribute(
"nanommo.player", *
id);
302 const absl::StatusOr<std::string> lease =
303 players_.Lease(name_, *
id, instance_);
305 if (absl::IsFailedPrecondition(lease.status())) {
306 std::cout <<
"refused player " << *
id <<
": " << lease.status().message()
308 span.SetAttribute(
"nanommo.refused", lease.status().message());
310 std::cerr <<
"couldn't lease player " << *
id <<
": " << lease.status()
312 span.SetError(lease.status().ToString());
317 const absl::StatusOr<Player> player = players_.Load(name_, *
id);
319 std::cerr <<
"couldn't load player " << *
id <<
": " << player.status()
321 span.SetError(player.status().ToString());
322 players_.Release(name_, *
id, *lease).IgnoreError();
326 copies_.Join(*
id, *player);
329 const absl::StatusOr<Membership> membership = guilds_.Of(*
id);
330 if (membership.ok()) {
331 members_[*id] = *membership;
332 WorldOf(*id)->SetGuild(*
id, membership->guild);
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";
339 guild_news_.insert(*
id);
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 "
359void Server::Leave(uint32_t
id) {
360 std::cout << WorldOf(
id)->players().at(
id).name <<
" left" << std::endl;
364 if (!handing_over_) {
365 Save({
id}).IgnoreError();
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
374 leases_.erase(lease);
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);
388 if (
const auto member = members_.find(
id); member != members_.end()) {
389 const uint32_t guild = member->second.guild;
390 members_.erase(member);
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);
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."));
407 const std::optional<std::string> clean =
CleanChat(text);
409 metrics_.AddChatLine(
"refused");
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;
419void Server::Talk(uint32_t
id,
const protocol::Talk& talk) {
420 const World& land = *WorldOf(
id);
421 const Player& player = land.players().at(
id);
423 const auto found = land.npcs().find(talk.npc());
424 if (found == land.npcs().end() || !found->second.talks) {
425 metrics_.AddStory(
"refused");
428 const Npc& npc = found->second;
430 metrics_.AddStory(
"refused");
431 Notify(
id,
Msg(
"You're too far away to talk to the $0.",
Of(npc)));
434 const std::optional<std::string> words =
CleanChat(talk.words());
435 const std::optional<std::string> prompt =
437 if (!words || !prompt) {
438 metrics_.AddStory(
"refused");
441 const auto asked = std::chrono::steady_clock::now();
442 if (!story_limits_.at(
id).Take(asked)) {
443 metrics_.AddStory(
"refused");
445 Notify(
id,
Msg(
"The $0 needs a moment before the next story.",
Of(npc)));
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) {
454 protocol::World told;
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();
462 said->set_text(*clean);
466 metrics_.AddStory(
"failed");
467 std::cerr <<
"no story for player " << id <<
": " << story.status()
469 protocol::Chat* said = told.add_chat();
471 *said->mutable_message() =
472 Msg(
"I can't think of a story right now.").message;
475 const auto session = sessions_.find(
id);
476 if (session == sessions_.end()) {
479 if (!told.chat().empty()) {
480 session->second->Send(Frame(told));
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());
492 std::cout << land.players().at(
id).name <<
" learned skill " << learn.skill()
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());
503 std::cout << land.players().at(
id).name <<
" took quest " << quest.quest()
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());
514 std::cout << land.players().at(
id).name <<
" turned in quest "
515 << quest.quest() << std::endl;
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()) {
525 std::cout << land.players().at(
id).name <<
" gave up quest " << quest
529void Server::Enlist(uint32_t
id, uint32_t npc) {
530 World& land = *WorldOf(
id);
531 const absl::Status sworn = land.Enlist(
id, npc);
536 const Player& player = land.players().at(
id);
537 std::cout << player.name <<
" joined faction " << player.faction << std::endl;
540void Server::Item(uint32_t
id,
const protocol::ItemAction& action) {
546 if (!item_limits_.at(
id).Take(std::chrono::steady_clock::now())) {
547 Notify(
id,
Msg(
"You're moving things too fast."));
550 const absl::Status done =
DoItem(*WorldOf(
id),
id, action);
556void Server::Trade(uint32_t
id,
const protocol::TradeAction& action) {
563 if (!item_limits_.at(
id).Take(std::chrono::steady_clock::now())) {
564 Notify(
id,
Msg(
"You're moving things too fast."));
567 World& land = *WorldOf(
id);
569 switch (action.action_case()) {
570 case protocol::TradeAction::kAsk:
571 done = land.AskToTrade(
id, action.ask());
573 case protocol::TradeAction::kOffer:
574 done = land.OfferToTrade(
id, action.offer());
576 case protocol::TradeAction::kReady: {
577 const absl::Time asked = absl::Now();
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();
586 if (traded.value_or(0) == 0) {
591 Span span =
StartSpan(
"trade", SpanKind::kServer, SpanContext(), asked);
594 .player_gave = offers.yours(),
596 .partner_gave = offers.theirs()};
597 span.SetAttribute(
"nanommo.trade", record.id);
598 span.SetAttribute(
"nanommo.player",
id);
599 span.SetAttribute(
"nanommo.partner", *traded);
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());
614 const std::string name = land.players().at(
id).name;
615 const std::string partner = land.players().at(*traded).name;
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"));
624 case protocol::TradeAction::kCancel:
625 land.CancelTrade(
id);
627 case protocol::TradeAction::ACTION_NOT_SET:
635void Server::Duel(uint32_t
id,
const protocol::DuelAction& action) {
640 if (!duel_limits_.at(
id).Take(std::chrono::steady_clock::now())) {
641 Notify(
id,
Msg(
"You're asking for duels too fast."));
644 World& land = *WorldOf(
id);
646 switch (action.action_case()) {
647 case protocol::DuelAction::kAsk:
648 done = land.AskToDuel(
id, action.ask());
650 case protocol::DuelAction::kAccept:
651 done = land.AnswerDuel(
id,
true);
653 case protocol::DuelAction::kDecline:
654 done = land.AnswerDuel(
id,
false);
656 case protocol::DuelAction::kYield:
657 done = land.Yield(
id);
659 case protocol::DuelAction::ACTION_NOT_SET:
667void Server::Craft(uint32_t
id,
const protocol::CraftAction& action) {
673 if (!craft_limits_.at(
id).Take(std::chrono::steady_clock::now())) {
674 Notify(
id,
Msg(
"You're crafting too fast."));
677 const absl::Status done =
DoCraft(*WorldOf(
id),
id, action);
683void Server::Guild(uint32_t
id,
const protocol::GuildAction& action) {
689 if (action.has_say()) {
690 GuildSay(
id, action.say());
693 if (!guild_limits_.at(
id).Take(std::chrono::steady_clock::now())) {
694 Notify(
id,
Msg(
"You're doing that too fast."));
697 switch (action.action_case()) {
698 case protocol::GuildAction::kCreate:
699 Found(
id, action.create());
701 case protocol::GuildAction::kInvite:
702 Ask(
id, action.invite());
704 case protocol::GuildAction::kAccept:
707 case protocol::GuildAction::kDecline:
708 if (
const absl::Status declined = guilds_.Decline(
id); !declined.ok()) {
712 case protocol::GuildAction::kLeave:
715 case protocol::GuildAction::kPromote:
716 SetRank(
id, action.promote(), protocol::RANK_OFFICER);
718 case protocol::GuildAction::kDemote:
719 SetRank(
id, action.demote(), protocol::RANK_MEMBER);
721 case protocol::GuildAction::kKick:
722 Kick(
id, action.kick());
724 case protocol::GuildAction::kDisband:
727 case protocol::GuildAction::kWar:
728 AskToWar(
id, action.war());
730 case protocol::GuildAction::kSay:
731 case protocol::GuildAction::ACTION_NOT_SET:
736void Server::Found(uint32_t
id,
const std::string& name) {
737 const absl::StatusOr<Membership> founded = guilds_.Create(name_,
id, name);
739 Refuse(
id, founded.status());
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;
749void Server::Ask(uint32_t
id,
const std::string& name) {
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)) {
757 asked_name = player.name;
762 Notify(
id,
Msg(
"Nobody of that name is playing in $0 now.",
Name(name_)));
765 if (members_.contains(asked)) {
766 Notify(
id,
Msg(
"$0 is in a guild already.",
Name(asked_name)));
769 const absl::StatusOr<Membership> guild = guilds_.Invite(
id, asked);
771 Refuse(
id, guild.status());
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));
779 Msg(
"You asked $0 to join $1.",
Name(asked_name),
Name(guild->name)));
782void Server::Join(uint32_t
id) {
783 const absl::StatusOr<Membership> joined = guilds_.Accept(
id);
785 Refuse(
id, joined.status());
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)));
796void Server::QuitGuild(uint32_t
id) {
797 const absl::StatusOr<Left> left = guilds_.Leave(
id);
799 Refuse(
id, left.status());
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) {
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);
816 TellGuild(left->guild,
Msg(
"$0 left $1. $2 leads it now.", who, guild,
817 Name(left->successor_name)));
819 TellGuild(left->guild,
Msg(
"$0 left $1.", who, guild));
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));
826void Server::SetRank(uint32_t
id, uint32_t player, protocol::Rank rank) {
827 const absl::StatusOr<Changed> changed = guilds_.SetRank(
id, player, rank);
829 Refuse(
id, changed.status());
832 if (
const auto member = members_.find(player); member != members_.end()) {
833 member->second.rank = rank;
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));
842void Server::Kick(uint32_t
id, uint32_t player) {
843 const absl::StatusOr<Changed> kicked = guilds_.Kick(
id, player);
845 Refuse(
id, kicked.status());
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)));
854 RefreshGuild(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)));
861void Server::Disband(uint32_t
id) {
862 const absl::StatusOr<Membership> ended = guilds_.Disband(
id);
864 Refuse(
id, ended.status());
867 TellGuild(ended->guild,
868 Msg(
"$0 disbanded $1.",
Name(WorldOf(
id)->players().at(
id).name),
871 std::erase_if(members_, [&](
const auto& member) {
872 if (member.second.guild != ended->guild) {
875 WorldOf(member.first)->SetGuild(member.first, 0);
876 guild_news_.insert(member.first);
881void Server::AskToWar(uint32_t
id,
const std::string& name) {
882 const absl::StatusOr<War> war = guilds_.AskToWar(name_,
id, name);
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)));
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);
914void Server::ReadWars() {
915 const auto now = std::chrono::steady_clock::now();
916 if (now - wars_read_ < kReadWarsEvery) {
920 absl::StatusOr<std::vector<War>> read = guilds_.Wars(name_);
922 std::cerr <<
"couldn't read the wars: " << read.status() <<
"\n";
928 for (
const War& war : wars_) {
929 if (std::ranges::find(*read, war.id, &War::id) != read->end()) {
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);
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);
949 wars_ = *std::move(read);
950 copies_.SetWars(wars_);
953void Server::TellKills(
const std::vector<WarKill>& kills) {
954 for (
const WarKill& kill : kills) {
955 const Sentence news =
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);
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;
971 return war != wars_.end() ? &*war :
nullptr;
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."));
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."));
985 const std::optional<std::string> clean =
CleanChat(text);
987 metrics_.AddChatLine(
"refused");
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;
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, {});
1009void Server::RefreshGuild(uint32_t guild) {
1010 for (
const auto& [
id, membership] : members_) {
1011 if (membership.guild == guild) {
1012 guild_news_.insert(
id);
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);
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
1031 Notify(
id,
Msg(
"That didn't work. Try again."));
1037void Server::Notify(uint32_t
id,
const Sentence& said,
1038 protocol::Channel channel) {
1039 Notify(
id, said.message, channel);
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));
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;
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_;
1075 handing_over_ =
true;
1076 std::error_code ignored;
1077 acceptor_.close(ignored);
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) {
1093 const absl::StatusOr<std::set<uint32_t>> passed =
1094 players_.Pass(name_, leases_,
InstanceId({.name = name_, .port =
port}));
1096 std::cerr <<
"couldn't hand the leases over: " << passed.status() <<
"\n";
1097 span.
SetError(passed.status().ToString());
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";
1111 const absl::StatusOr<std::string> token = tokens_.Issue(
id);
1113 std::cerr <<
"couldn't hand player " <<
id <<
" over: " << token.status()
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));
1128void Server::Tick() {
1130 if (handing_over_) {
1133 const auto start = std::chrono::steady_clock::now();
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);
1142 std::vector<WarKill> kills = copies_.TakeWarKills();
1146 std::erase_if(kills, [
this, start](
const WarKill& kill) {
1147 return !scoring_.Scores(kill, start);
1151 for (WarKill& kill : kills) {
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];
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]);
1172 ShowEvents(happened);
1179 metrics_.ObserveTick(std::chrono::steady_clock::now() - start);
1180 TracyPlot(
"players",
static_cast<int64_t
>(players()));
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;
1192 timer_.expires_at(next);
1193 timer_.async_wait([
this](std::error_code) { Tick(); });
1196void Server::ApplyInputs() {
1197 inputs_.Apply([
this](uint32_t
id) {
return WorldOf(
id); });
1200void Server::SaveChanged(
const std::vector<WarKill>& kills) {
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);
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");
1218 std::erase_if(everyone,
1219 [&lost](uint32_t
id) {
return lost->contains(
id); });
1221 metrics_.ObserveSave(std::chrono::steady_clock::now() - start);
1224void Server::RenewLeases() {
1225 const auto now = std::chrono::steady_clock::now();
1226 if (now - renewed_ < kRenewEvery) {
1231 const absl::StatusOr<std::set<uint32_t>> lost =
1232 players_.Renew(name_, leases_);
1234 std::cerr <<
"couldn't renew " << leases_.size()
1235 <<
" leases: " << lost.status() <<
"\n";
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");
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) {
1255 const auto lease = leases_.find(
id);
1256 if (lease == leases_.end()) {
1259 const Player& player = WorldOf(
id)->players().at(
id);
1260 const Progress progress = ProgressOf(player);
1261 if (progress != saved_[
id]) {
1263 if (progress.items_revision != saved_[
id].items_revision) {
1264 bags[id] = player.inventory.items();
1266 changed[id] = progress;
1267 leases[id] = lease->second;
1270 const absl::StatusOr<std::set<uint32_t>> lost =
1271 players_.Save(name_, changed, bags, leases, traded, kills);
1273 std::cerr <<
"couldn't save " << changed.size()
1274 <<
" players: " << lost.status() <<
"\n";
1275 return lost.status();
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"
1282 if (lost->empty()) {
1283 for (
const auto& [
id, progress] : changed) {
1284 saved_[id] = progress;
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);
1296 if (
const auto lease = leases_.find(
id); lease != leases_.end()) {
1297 players_.Release(name_,
id, lease->second).IgnoreError();
1298 leases_.erase(lease);
1300 sessions_.at(
id)->Close();
1303void Server::RecordEvents(
const std::vector<Event>& happened) {
1305 if (happened.empty()) {
1308 const absl::Time now = absl::Now();
1309 std::vector<std::string> rows;
1310 rows.reserve(happened.size());
1311 for (
const Event& event : happened) {
1313 rows.push_back(
Row(event, copies_.content(), name_, now));
1320 const absl::Status added = events_.Add(rows);
1322 std::cerr <<
"couldn't record " << rows.size() <<
" events: " << added
1327void Server::ShowEvents(
const std::vector<Event>& happened) {
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()) {
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;
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));
1352void Server::Broadcast() {
1357 const bool full = broadcasts_ == 0;
1358 broadcasts_ = (broadcasts_ + 1) % kFullEvery;
1359 for (
const auto& [
id, copy] : copies_.all()) {
1360 BroadcastCopy(copy, full);
1364void Server::BroadcastCopy(
const Copy& copy,
bool full) {
1365 const World& land = copy.world;
1367 if (land.players().empty()) {
1372 std::map<uint32_t, std::string> players;
1373 std::map<uint32_t, std::string> monsters;
1374 std::map<uint32_t, std::string> npcs;
1376 ZoneScopedN(
"serialize");
1377 for (
const auto& [
id, player] : land.players()) {
1378 protocol::Player entry =
ToProtocol(
id, player);
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()) {
1389 entry.set_guild(member->second.name);
1391 players[id] =
Piece(entry);
1393 for (
const auto& [
id, monster] : land.monsters()) {
1394 protocol::Monster entry =
ToProtocol(
id, monster);
1397 entry.clear_level();
1398 entry.clear_max_health();
1400 monsters[id] =
Piece(entry);
1403 for (
const auto& [
id, npc] : land.npcs()) {
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()) {
1421 std::vector<std::string_view> pieces =
1422 Delta(
id, copy, view, players, monsters, sent, still);
1424 for (
const uint32_t npc : view.npcs) {
1425 pieces.push_back(npcs.at(npc));
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()) {
1436 for (std::string& part :
Split(pieces, sent)) {
1438 std::make_shared<const std::string>(std::move(part));
1439 metrics_.AddBytesSent(bytes->size() + own.size());
1440 SendTo(udp->second, bytes, own);
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);
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));
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];
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 == ©) {
1474 Sent& now = history[sent];
1476 std::vector<std::string_view> pieces;
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();
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 == © &&
1490 before != world->second.pieces.end() && before->second == hash;
1495 pieces.push_back(piece);
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);
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);
1510 if (unchanged.still_players_size() + unchanged.still_monsters_size() > 0) {
1511 still = unchanged.SerializeAsString();
1512 pieces.push_back(still);
1516 if (seen != seen_.end()) {
1517 history.erase(history.begin(), history.lower_bound(seen->second));
1519 while (history.size() > kMostRemembered) {
1520 history.erase(history.begin());
1525void Server::SendChat() {
1526 if (chat_.chat().empty()) {
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, {});
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);
1547 if (session == sessions_.end() || sent_bags_[
id] == revision) {
1551 metrics_.AddBytesSent(frame.size());
1552 session->second->Send(std::move(frame));
1553 sent_bags_[id] = revision;
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);
1565 if (session == sessions_.end() ||
1566 (sent != sent_quests_.end() &&
1567 sent->second == player.quests_revision)) {
1571 metrics_.AddBytesSent(frame.size());
1572 session->second->Send(std::move(frame));
1573 sent_quests_[id] = player.quests_revision;
1578void Server::SendGuilds() {
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()) {
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()) {
1595 rosters.emplace(member->second.guild, Roster(member->second.guild))
1598 guild->mutable_members()->Add(roster->second.begin(),
1599 roster->second.end());
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()));
1613 std::string frame =
Frame(news);
1614 metrics_.AddBytesSent(frame.size());
1615 session->second->Send(std::move(frame));
1617 guild_news_.clear();
1620void Server::SendTrades() {
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) {
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));
1637void Server::SendDuels() {
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) {
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));
1654std::vector<protocol::GuildMember> Server::Roster(uint32_t guild) {
1655 absl::StatusOr<std::vector<protocol::GuildMember>> roster =
1656 guilds_.Roster(guild);
1658 std::cerr <<
"couldn't read guild " << guild
1659 <<
"'s roster: " << roster.status() <<
"\n";
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
>(
1669 return *std::move(roster);
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)};
1677 udp_.async_send_to(buffers, client,
1678 [part = std::move(part), tail = std::move(tail)](
1679 std::error_code, std::size_t) {});
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)
int HandOver(const std::string &host, uint16_t port)
int players() const
In all its lands.
void SetAttribute(std::string_view key, std::string_view value)
void SetError(std::string_view message)
Marks it as failed, and why.
static constexpr float kTalkReach
Span StartSpan(std::string_view name, SpanKind kind)
std::optional< protocol::Event > ForPlayers(const Event &event)
absl::Status DoCraft(World &land, uint32_t id, const protocol::CraftAction &action)
Sentence MsgN(std::string_view one, std::string_view many, uint64_t count, Parts... parts)
const Gate & WayOut(int dungeon)
The dungeon's way out: its first gate.
int64_t UnixMs()
Now, by the wall clock, in milliseconds since 1970.
protocol::World YouIn(uint32_t id, const Player &player, uint32_t seed, int land, std::optional< uint32_t > acked)
std::string InstanceId(const WorldRegistration &world)
Sentence SentenceOf(const absl::Status &status)
absl::Status ListenAndBind(asio::ip::tcp::acceptor &acceptor, asio::ip::udp::socket &socket, std::span< const uint16_t > ports)
Level LevelFor(uint32_t experience)
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
Place Arrival(const Gate &gate, float yaw)
Cell CellOf(float x, float z)
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
constexpr std::array< Land, 3 > kLands
protocol::Sky SkyAt(int land, int64_t unix_ms)
bool Near(Cell from, Cell to)
absl::Status DoItem(World &land, uint32_t id, const protocol::ItemAction &action)
protocol::World BagOf(const Player &player)
Their bag, and their quests, each as it goes when it's changed.
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)
Sentence Msg(std::string_view text, Parts... parts)
std::vector< std::string > Split(const std::vector< std::string_view > &pieces, int64_t sent, std::size_t max_size)
std::string Piece(const protocol::Player &player)
protocol::World QuestsOf(const Player &player)
protocol::Motion ToProtocol(Motion motion)
Part Name(std::string_view name)
int MaxHealthOf(const Player &player)
std::optional< std::string > StoryPrompt(std::string_view words)
Part Of(const items::Item &item, uint32_t count)
uint32_t MainHandOf(const Player &player)
std::optional< std::string > CleanChat(std::string_view text)
bool ForAnalytics(Event::Kind kind)
std::map< Cell, View > Views(const std::map< uint32_t, Player > &players, const std::map< uint32_t, Monster > &monsters, const Cells &npcs)
std::string Row(const Event &event, const Content &content, std::string_view world, absl::Time time)
A ring of stones in a land, which takes players to another.
In metres from the middle of a land.
What we keep of a player from one session to the next.