nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
world_list.cc
Go to the documentation of this file.
2
3#include <iostream>
4#include <string>
5#include <string_view>
6#include <utility>
7#include <vector>
8
9#include "absl/status/status.h"
10#include "absl/strings/str_cat.h"
11#include "asio/post.hpp"
12
13namespace nanommo {
14
15WorldList::WorldList(asio::io_context& io, Fetch fetch)
16 : io_(io), fetch_(std::move(fetch)), timer_(io) {}
17
19 timer_.cancel();
20 thread_.join();
21}
22
24 Ask();
25 timer_.expires_after(std::chrono::seconds(1));
26 timer_.async_wait([this](std::error_code error) {
27 if (!error) {
28 Start();
29 }
30 });
31}
32
33void WorldList::Ask() {
34 // One question at a time: a slow Consul isn't asked again until it answers.
35 if (asking_) {
36 return;
37 }
38 asking_ = true;
39 asio::post(thread_, [this] {
40 absl::StatusOr<std::vector<ListedWorld>> worlds = fetch_();
41 asio::post(io_, [this, worlds = std::move(worlds)]() mutable {
42 asking_ = false;
43 Take(std::move(worlds), Clock::now());
44 });
45 });
46}
47
48void WorldList::Take(absl::StatusOr<std::vector<ListedWorld>> worlds,
49 Clock::time_point at) {
50 if (!worlds.ok()) {
51 std::cerr << "nanommo gateway: couldn't list the worlds: "
52 << worlds.status() << "\n";
53 return;
54 }
55 worlds_ = *std::move(worlds);
56 fetched_ = at;
57}
58
59absl::StatusOr<std::string> WorldList::Find(std::string_view public_host,
60 uint16_t port,
61 Clock::time_point now) const {
62 if (!fetched_ || now - *fetched_ > kStale) {
63 return absl::UnavailableError("the gateway has no recent list of worlds");
64 }
65 for (const ListedWorld& world : worlds_) {
66 if (world.public_host == public_host && world.port == port) {
67 return world.address;
68 }
69 }
70 return absl::NotFoundError(
71 absl::StrCat("no world at ", public_host, ":", port));
72}
73
74} // namespace nanommo
WorldList(asio::io_context &io, Fetch fetch)
Definition world_list.cc:15
absl::StatusOr< std::string > Find(std::string_view public_host, uint16_t port, Clock::time_point now) const
Definition world_list.cc:59
void Take(absl::StatusOr< std::vector< ListedWorld > > worlds, Clock::time_point at)
Definition world_list.cc:48
~WorldList()
Destroy it once the io_context has stopped.
Definition world_list.cc:18
std::function< absl::StatusOr< std::vector< ListedWorld > >()> Fetch
Definition world_list.h:35
void Start()
Asks for the list now, and every second after.
Definition world_list.cc:23
static constexpr std::chrono::seconds kStale
A list this old says nothing about now, so every world is refused.
Definition world_list.h:38
Definition chat.cc:9