-
Notifications
You must be signed in to change notification settings - Fork 1
/
MetaServer.hpp
461 lines (425 loc) · 14.4 KB
/
MetaServer.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#pragma once
#include "Debug.hpp"
#include "Logger.hpp"
#include "Optimizations.hpp"
#include "Timer.hpp"
#include "Network.hpp"
#include "Lobby.hpp"
#include <cstdint>
#include <cstring>
#include <thread>
#include <mutex>
#include <set>
#include <unordered_set>
#include <vector>
#include <string>
namespace pkg {
struct metaserver_query_struct {
MSAction action;
net::Addr addr;
} ATTRIB_PACKED;
struct metaserver_query_response_struct {
net::Addr addr;
int8_t active;
} ATTRIB_PACKED;
struct metaserver_host_response_struct {
MSAction action;
net::Addr host;
char name[30] = "";
void set_name(std::string &s) {
strncpy(name, s.c_str(), std::min<int>(s.length() + 1, 30));
name[29] = '\0';
}
} ATTRIB_PACKED;
}
struct GameList {
std::map<net::Addr, std::string> games;
void add_game(net::Addr host, std::string name) {
games[host] = name;
}
void delete_game(net::Addr host) {
games.erase(host);
}
bool find(net::Addr host) {
return games.find(host) != std::end(games);
}
};
struct MetaServer {
GameList gamelist;
net::Socket<net::SocketType::UDP> socket;
Timer timer;
std::set<net::Addr> users;
Timer user_timer;
MetaServer(net::port_t port=5678):
gamelist(),
socket(port)
{}
void run() {
constexpr Timer::key_t EVENT_CHECK_STATUSES = 1;
timer.set_timeout(EVENT_CHECK_STATUSES, Timer::time_t(3.));
Logger::Info("mserver: started at port %hu\n", socket.port());
socket.listen(
[&]() mutable {
timer.set_time(Timer::system_time());
// clean up inactive users
timer.periodic(EVENT_CHECK_STATUSES, [&]() mutable {
Logger::Info("mserver: cleaning up inactive users\n");
user_timer.set_time(Timer::system_time());
std::string s = "";
// workaround because it fails when the iterated set changes
std::set<net::Addr> exusers;
for(auto &u : users) {
if(user_timer.timed_out(Timer::key_t(u.ip))) {
Logger::Info("mserver: removing user %s\n", u.to_str().c_str());
exusers.insert(u);
} else {
s += u.to_str() + " ";
}
}
for(auto &u : exusers) {
if(gamelist.find(u)) {
unregister_host(u);
}
users.erase(u);
user_timer.erase(Timer::key_t(u.ip));
}
Logger::Info("mserver: users [ %s]\n", s.c_str());
});
return !feof(stdin);
},
[&](const net::Blob &blob) mutable {
Logger::Info("mserver: received package from %s\n", blob.addr.to_str().c_str());
// find out if the user already exists
bool found = users.find(blob.addr) != std::end(users);
user_timer.set_time(Timer::system_time());
if(found) {
user_timer.set_event(Timer::key_t(blob.addr.ip));
}
static_assert(net::Typecheck::all_distinct<
pkg::metaserver_hello_struct,
pkg::metaserver_query_struct,
pkg::metaserver_host_struct
>);
// received hello package
blob.try_visit_as<pkg::metaserver_hello_struct>([&](const auto hello) mutable {
Logger::Info("mserver: recognized as hello package, found=%d\n", found);
if(!found) {
// add user
Logger::Info("mserver: added user %s\n", blob.addr.to_str().c_str());
user_timer.set_event(Timer::key_t(blob.addr.ip));
user_timer.set_timeout(Timer::key_t(blob.addr.ip), Timer::time_t(3.));
users.insert(blob.addr);
} else if(hello.action == pkg::MSAction::QUERY) {
// send random game information
if(!gamelist.games.empty()) {
int i = 0; int j = rand() % gamelist.games.size();
for(auto &it : gamelist.games) {
if(i == j) {
pkg::metaserver_host_response_struct gameinfo = {
.action = pkg::MSAction::HOST,
.host = it.first,
};
gameinfo.set_name(it.second);
socket.send(net::make_package(blob.addr, gameinfo));
Logger::Info("mserver: randomly sending host info on %s\n", blob.addr.to_str().c_str());
break;
}
++i;
}
}
}
});
// respond whether the address is active or not
blob.try_visit_as<pkg::metaserver_query_struct>([&](const auto query) mutable {
Logger::Info("mserver: recognized as query package\n");
if(!found) {
return;
}
ASSERT(query.action == pkg::MSAction::QUERY);
socket.send(net::make_package(blob.addr, (pkg::metaserver_query_response_struct){
.addr = query.addr,
.active = gamelist.find(query.addr)
}));
});
// received hosting action
blob.try_visit_as<pkg::metaserver_host_struct>([&](auto host) mutable {
Logger::Info("mserver: recognized as hosting struct\n");
switch(host.action) {
case pkg::MSAction::HELLO:break;
case pkg::MSAction::QUERY:break;
case pkg::MSAction::HOST:
if(found) {
host.name[29] = '\0';
Logger::Info("mserver: hosting game name='%s'\n", host.name);
register_host(blob.addr, host.name);
pkg::metaserver_host_response_struct response = {
.action = pkg::MSAction::HOST,
.host = blob.addr
};
std::string name = host.name;
response.set_name(name);
Logger::Info("mserver: sending action host host=%s name=%s\n", blob.addr.to_str().c_str(), name.c_str());
for(auto &u : users) {
socket.send(net::make_package(u, response));
}
}
break;
case pkg::MSAction::UNHOST:
if(found) {
host.name[29] = '\0';
Logger::Info("mserver: unhosting game\n");
unregister_host(blob.addr);
Logger::Info("mserver: sending action unhost host=%s\n", blob.addr.to_str().c_str());
for(auto &u : users) {
socket.send(net::make_package(u, (pkg::metaserver_host_response_struct){
.action = pkg::MSAction::UNHOST,
.host = blob.addr
}));
}
}
break;
}
});
return !feof(stdin);
});
Logger::Info("mserver: finisned\n");
}
// parent lock
void register_host(net::Addr host, std::string name) {
ASSERT(name.length() < 30);
if(!gamelist.find(host) || gamelist.games.at(host) != name) {
gamelist.add_game(host, name);
}
}
// parent lock
void unregister_host(net::Addr host) {
if(gamelist.find(host)) {
gamelist.delete_game(host);
}
}
};
struct MetaServerClient {
std::set<net::Addr> metaservers;
std::map<net::Addr, GameList> gamelists;
net::Socket<net::SocketType::UDP> socket;
struct LobbyMaker {
enum class type : int8_t { SERVER, CLIENT };
type ltype = type::SERVER;
net::Addr host;
} lobbyMaker;
std::thread user_thread;
std::recursive_mutex mservers_mtx;
std::recursive_mutex lmaker_mtx;
std::recursive_mutex finalize_mtx;
MetaServerClient(std::set<net::Addr> metaservers, net::port_t port=5679):
socket(port),
metaservers(metaservers)
{
set_timer();
}
Timer timer;
static constexpr Timer::key_t EVENT_SEND_HELLO = 1;
static constexpr Timer::key_t EVENT_SEND_QUERY = 2;
void set_timer() {
timer.set_timeout(EVENT_SEND_HELLO, Timer::time_t(1.));
timer.set_timeout(EVENT_SEND_QUERY, Timer::time_t(2.));
}
static void run(MetaServerClient *client) {
client->socket.listen(
[&]() mutable {
if(client->has_quit() || client->has_hosted()) {
return !client->should_stop();
}
/* usleep(1e6 / 24.); */
client->timer.set_time(Timer::system_time());
// send hello to the metaserver every second
client->timer.periodic(EVENT_SEND_HELLO, [&]() mutable {
if(rand() % 3) {
Logger::Info("mclient: sending hello\n");
client->send_action((pkg::metaserver_hello_struct){
.action = pkg::MSAction::HELLO
});
} else {
Logger::Info("mclient: sending query\n");
client->send_action((pkg::metaserver_hello_struct){
.action = pkg::MSAction::QUERY
});
}
});
// send query for random host
client->timer.periodic(EVENT_SEND_QUERY, [&]() mutable {
std::lock_guard<std::recursive_mutex> guard(client->mservers_mtx);
if(client->gamelists.empty()) {
return;
}
int i = 0, j = rand() % client->gamelists.size();
for(auto &e:client->gamelists) {
if(i == j) {
auto &games = e.second.games;
if(games.empty()) {
return;
}
int k = 0, m = rand() % games.size();
for(auto &e2:games) {
if(k == m) {
auto &addr = e2.first;
Logger::Info("mclient: sending query for host %s\n", addr.to_str().c_str());
client->send_action((pkg::metaserver_query_struct){
.action = pkg::MSAction::QUERY,
.addr = addr
});
return;
}
++k;
}
}
++i;
}
});
return !client->should_stop();
},
[&](const net::Blob &blob) {
if(client->has_quit() || client->has_hosted()) {
return !client->should_stop();
}
{
std::lock_guard<std::recursive_mutex> guard(client->mservers_mtx);
if(client->metaservers.find(blob.addr) == std::end(client->metaservers)) {
return !client->should_stop();
}
}
static_assert(net::Typecheck::all_distinct<
pkg::metaserver_query_response_struct,
pkg::metaserver_host_response_struct
>);
// recognize as a query response struct
blob.try_visit_as<pkg::metaserver_query_response_struct>([&](const auto response) mutable {
// unregister if no longer marked active
Logger::Info("mclient: received query response for %s\n", response.addr.to_str().c_str());
if(client->gamelists[blob.addr].find(response.addr) && !response.active) {
client->unregister_host(blob.addr, response.addr);
}
});
// recognize as a hosting respond struct
blob.try_visit_as<pkg::metaserver_host_response_struct>([&](const auto response) mutable {
switch(response.action) {
case pkg::MSAction::HELLO:break;
case pkg::MSAction::QUERY:break;
case pkg::MSAction::HOST:
Logger::Info("mclient: register game host=%s name=%s\n", blob.addr.to_str().c_str(), response.name);
client->register_host(blob.addr, response.host, response.name);
break;
case pkg::MSAction::UNHOST:
Logger::Info("mclient: unregister game host=%s\n", blob.addr.to_str().c_str());
client->unregister_host(blob.addr, response.host);
break;
}
});
return !client->should_stop();
}
);
}
std::recursive_mutex state_mtx;
enum class State {
DEFAULT,
HOSTED,
JOINED,
QUIT
};
State state_ = State::DEFAULT;
void set_state(State state) {
std::lock_guard<std::recursive_mutex> guard(state_mtx);
state_ = state;
}
State state() {
std::lock_guard<std::recursive_mutex> guard(state_mtx);
return state_;
}
bool has_hosted() {
return state() == State::HOSTED;
}
bool has_quit() {
return state() == State::QUIT;
}
bool has_joined() {
return state() == State::JOINED;
}
void register_host(net::Addr metaserver, net::Addr host, std::string gamename) {
ASSERT(gamename.length() < 30);
gamelists[metaserver].add_game(host, gamename);
}
void unregister_host(net::Addr metaserver, net::Addr host) {
gamelists[metaserver].delete_game(host);
}
void action_host(std::string gamename) {
set_state(State::HOSTED);
std::lock_guard<std::recursive_mutex> guard(lmaker_mtx);
lobbyMaker = (LobbyMaker){
.ltype = LobbyMaker::type::SERVER
};
pkg::metaserver_host_struct data = {
.action = pkg::MSAction::HOST
};
data.set_name(gamename);
Logger::Info("mclient: sending action host name='%s'\n", data.name);
send_action(data);
}
void action_join(net::Addr host) {
Logger::Info("sending action join game host=%s\n", host.to_str().c_str());
set_state(State::JOINED);
std::lock_guard<std::recursive_mutex> guard(lmaker_mtx);
lobbyMaker = (LobbyMaker){
.ltype = LobbyMaker::type::CLIENT,
.host = host
};
}
void add_metaserver(net::Addr addr) {
std::lock_guard<std::recursive_mutex> guard(mservers_mtx);
metaservers.insert(addr);
}
template <typename DataT>
void send_action(DataT data) {
std::lock_guard<std::recursive_mutex> mguard(mservers_mtx);
for(auto &m : metaservers) {
socket.send(net::make_package(m, data));
}
}
LobbyActor *make_lobby() {
std::lock_guard<std::recursive_mutex> lmguard(lmaker_mtx);
if(lobbyMaker.ltype == LobbyMaker::type::SERVER) {
return new LobbyServer(socket, metaservers, mservers_mtx);
} else if(lobbyMaker.ltype == LobbyMaker::type::CLIENT) {
return new LobbyClient(socket, lobbyMaker.host);
}
return nullptr;
}
void start() {
gamelists.clear();
set_state(State::DEFAULT);
std::string s = "[ ";
for(auto &m : metaservers) {
s += m.to_str() + " ";
}
s += "]";
Logger::Info("mclient: started, mserver=%s\n", s.c_str());
ASSERT(should_stop());
finalize = false;
user_thread = std::thread(MetaServerClient::run, this);
}
bool finalize = true;
bool should_stop() {
std::lock_guard<std::recursive_mutex> guard(finalize_mtx);
return finalize;
}
void stop() {
ASSERT(!should_stop());
{
std::lock_guard<std::recursive_mutex> guard(finalize_mtx);
finalize = true;
}
user_thread.join();
Logger::Info("mclient: finished\n");
}
~MetaServerClient()
{}
};