nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
players.cc
Go to the documentation of this file.
1#include "server/players.h"
2
3#include <algorithm>
4#include <cstddef>
5#include <map>
6#include <optional>
7#include <set>
8#include <string>
9#include <string_view>
10#include <utility>
11#include <vector>
12
13#include "absl/strings/numbers.h"
14#include "absl/strings/str_cat.h"
15#include "absl/strings/str_join.h"
16#include "absl/strings/str_split.h"
17#include "absl/time/clock.h"
18#include "absl/time/time.h"
19#include "content/items.h"
20#include "google/protobuf/util/json_util.h"
21#include "server/inventory.h"
22#include "server/tracing.h"
23#include "terrain/lands.h"
24
25namespace nanommo {
26
27namespace {
28
29constexpr char kUnsaved[] = "players:unsaved";
30// The players whose bags changed, which are in kUnsaved too.
31constexpr char kItemsUnsaved[] = "items:unsaved";
32// The players, and the bags, in the batch the saver's taking to MySQL. They
33// stay here until MySQL has them, so that a saver that dies with a batch, or
34// whose MySQL fails, leaves it for the next flush, rather than losing it.
35constexpr char kSaving[] = "players:saving";
36constexpr char kItemsSaving[] = "items:saving";
37// The trades that aren't in MySQL yet, oldest first.
38constexpr char kTrades[] = "trades";
39// The war kills that aren't on their wars' scores in MySQL yet, oldest first.
40constexpr char kWarKills[] = "war_kills";
41
42std::string Key(const std::string& world, uint32_t id) {
43 return absl::StrCat("player:", world, ":", id);
44}
45
46// The lease on a player, which names the instance of the world that plays
47// them.
48std::string LeaseKey(const std::string& world, uint32_t id) {
49 return absl::StrCat("playing:", world, ":", id);
50}
51
52// The world's counter, which each lease takes its fencing number from.
53std::string FencingKey(const std::string& world) {
54 return absl::StrCat("fencing:", world);
55}
56
57// The players whose leases these are, by their keys.
58std::set<uint32_t> Leased(const std::vector<std::string>& keys) {
59 std::set<uint32_t> players;
60 for (const std::string& key : keys) {
61 uint32_t id = 0;
62 if (absl::SimpleAtoi(std::string_view(key).substr(key.rfind(':') + 1),
63 &id)) {
64 players.insert(id);
65 }
66 }
67 return players;
68}
69
70// Each script runs in Redis as one, with nothing else in between, so a lease
71// can't change between reading it and writing it.
72//
73// Takes the lease in KEYS[1] for the instance in ARGV[1], for ARGV[2]
74// milliseconds, with the next number from the counter in KEYS[2], unless
75// another instance has it, so that a hello it turns away uses up no number.
76// One handed to this instance is its already, and runs for as long again.
77// Returns the lease as it is then.
78constexpr char kTake[] = R"lua(
79local lease = redis.call('GET', KEYS[1])
80if not lease then
81 lease = ARGV[1] .. ' ' .. redis.call('INCR', KEYS[2])
82 redis.call('SET', KEYS[1], lease, 'PX', ARGV[2])
83elseif string.sub(lease, 1, #ARGV[1] + 1) == ARGV[1] .. ' ' then
84 redis.call('PEXPIRE', KEYS[1], ARGV[2])
85end
86return lease
87)lua";
88
89// Each lease in KEYS that's still the same in ARGV, past the first, runs for
90// another ARGV[1] milliseconds. Returns those that aren't.
91constexpr char kRenew[] = R"lua(
92local lost = {}
93for i, key in ipairs(KEYS) do
94 if redis.call('GET', key) == ARGV[i + 1] then
95 redis.call('PEXPIRE', key, ARGV[1])
96 else
97 lost[#lost + 1] = key
98 end
99end
100return lost
101)lua";
102
103// Deletes the lease in KEYS[1] if it's still ARGV[1].
104constexpr char kRelease[] = R"lua(
105if redis.call('GET', KEYS[1]) == ARGV[1] then
106 return redis.call('DEL', KEYS[1])
107end
108return 0
109)lua";
110
111// Hands each lease in KEYS, past the counter in KEYS[1], that's still the
112// same in ARGV, past the first two, to the instance in ARGV[1], with the next
113// number from the counter, for ARGV[2] milliseconds. Returns those it handed.
114constexpr char kPass[] = R"lua(
115local passed = {}
116for i = 2, #KEYS do
117 if redis.call('GET', KEYS[i]) == ARGV[i + 1] then
118 local lease = ARGV[1] .. ' ' .. redis.call('INCR', KEYS[1])
119 redis.call('SET', KEYS[i], lease, 'PX', ARGV[2])
120 passed[#passed + 1] = KEYS[i]
121 end
122end
123return passed
124)lua";
125
126// Takes up to ARGV[1] players out of the set in KEYS[1] and into the one in
127// KEYS[2], at once, as SPOP and SADD would one after the other, and returns
128// them.
129constexpr char kTakeBatch[] = R"lua(
130local taken = redis.call('SPOP', KEYS[1], ARGV[1])
131if #taken > 0 then
132 redis.call('SADD', KEYS[2], unpack(taken))
133end
134return taken
135)lua";
136
137// How many members the sets in KEYS[1] and KEYS[2] have between them, each
138// once, however many of the two it's in.
139constexpr char kCountUnion[] = R"lua(
140return #redis.call('SUNION', KEYS[1], KEYS[2])
141)lua";
142
143// In words, as lands are, so that the rows read well: "bag 0" to "bag 23", or
144// the slot that's worn, such as "main hand".
145std::string PlaceName(const protocol::Place& place) {
146 return place.has_bag() ? absl::StrCat("bag ", place.bag())
147 : std::string(SlotName(place.worn()));
148}
149
150absl::StatusOr<protocol::Place> PlaceNamed(std::string_view name) {
151 uint32_t slot = 0;
152 if (name.starts_with("bag ") && absl::SimpleAtoi(name.substr(4), &slot)) {
153 return InBag(slot);
154 }
155 for (int worn = items::Slot_MIN; worn <= items::Slot_MAX; ++worn) {
156 if (items::Slot_IsValid(worn) &&
157 SlotName(static_cast<items::Slot>(worn)) == name) {
158 return Worn(static_cast<items::Slot>(worn));
159 }
160 }
161 return absl::InternalError(
162 absl::StrCat("an item saved in ", name, ", which isn't a place we know"));
163}
164
165// What one of an item has of its own, past its item and count, which have
166// columns of their own, as protobuf's JSON for a stack, or nothing. A field
167// that a later server adds goes in without a migration.
168std::string StateOf(const items::Stack& stack) {
169 items::Stack state = stack;
170 state.clear_item();
171 state.clear_count();
172 std::string json;
173 if (state.ByteSizeLong() == 0 ||
174 !google::protobuf::util::MessageToJsonString(state, &json).ok()) {
175 return "";
176 }
177 return json;
178}
179
180// What one side gave in a trade, as protobuf's JSON, which MySQL keeps.
181std::string GaveOf(protocol::TradeSide side) {
182 side.clear_ready();
183 std::string json;
184 google::protobuf::util::MessageToJsonString(side, &json).IgnoreError();
185 return json;
186}
187
188// The value of a stream entry's field, or nothing if it hasn't the field.
189std::string FieldOf(const Redis::Entry& entry, std::string_view name) {
190 for (std::size_t i = 0; i + 1 < entry.fields.size(); i += 2) {
191 if (entry.fields[i] == name) {
192 return entry.fields[i + 1];
193 }
194 }
195 return "";
196}
197
198// The span a batch's trades go on with their traces in, from when they were
199// read off the stream: under the oldest's, as a span has one parent, and
200// linked to the rest. None for a batch without traced trades.
201Span StartSavingTrades(const std::vector<Redis::Entry>& trades,
202 absl::Time read) {
203 std::vector<SpanContext> published;
204 for (const Redis::Entry& trade : trades) {
205 if (const absl::StatusOr<SpanContext> context =
206 ParseTraceparent(FieldOf(trade, "traceparent"));
207 context.ok()) {
208 published.push_back(*context);
209 }
210 }
211 if (published.empty()) {
212 return Span();
213 }
214 Span span =
215 StartSpan("save trades", SpanKind::kConsumer, published.front(), read);
216 for (std::size_t i = 1; i < published.size(); ++i) {
217 span.AddLink(published[i]);
218 }
219 span.SetAttribute("messaging.system", "redis");
220 span.SetAttribute("messaging.destination.name", kTrades);
221 span.SetAttribute("messaging.batch.message_count",
222 static_cast<int64_t>(trades.size()));
223 return span;
224}
225
226// A player's quests as one message, which Redis keeps the bytes of, and
227// MySQL the JSON.
228protocol::Quests QuestsOf(const Progress& progress) {
229 protocol::Quests quests;
230 quests.mutable_on()->insert(progress.quests.begin(), progress.quests.end());
231 quests.mutable_done()->Add(progress.quests_done.begin(),
232 progress.quests_done.end());
233 quests.set_revision(progress.quests_revision);
234 return quests;
235}
236
237// The bag from its rows: place, item, count and state, with its revision
238// and gold from the player's row. What an earlier server doesn't know of a
239// later one's state, it leaves out.
240absl::StatusOr<protocol::Inventory> BagOf(const Result& rows,
241 const std::string& revision,
242 const std::string& gold) {
243 protocol::Inventory bag;
244 uint32_t number = 0;
245 if (!revision.empty() && !absl::SimpleAtoi(revision, &number)) {
246 return absl::InternalError("a saved revision that isn't a number");
247 }
248 bag.set_revision(number);
249 uint32_t coins = 0;
250 if (!gold.empty() && !absl::SimpleAtoi(gold, &coins)) {
251 return absl::InternalError("a saved gold that isn't a number");
252 }
253 bag.set_gold(coins);
254 google::protobuf::util::JsonParseOptions options;
255 options.ignore_unknown_fields = true;
256 for (const std::vector<std::string>& row : rows.rows) {
257 const absl::StatusOr<protocol::Place> place = PlaceNamed(row[0]);
258 if (!place.ok()) {
259 return place.status();
260 }
261 items::Stack stack;
262 if (!row[3].empty() &&
263 !google::protobuf::util::JsonStringToMessage(row[3], &stack, options)
264 .ok()) {
265 return absl::InternalError("a saved item whose state isn't a stack's");
266 }
267 uint32_t item = 0;
268 uint32_t count = 0;
269 if (!absl::SimpleAtoi(row[1], &item) || !absl::SimpleAtoi(row[2], &count)) {
270 return absl::InternalError("a saved item that isn't numbers");
271 }
272 stack.set_item(item);
273 stack.set_count(count);
274 auto& slots = place->has_bag() ? *bag.mutable_bag() : *bag.mutable_worn();
275 slots[place->has_bag() ? place->bag()
276 : static_cast<uint32_t>(place->worn())] =
277 std::move(stack);
278 }
279 return bag;
280}
281
282} // namespace
283
284absl::StatusOr<Player> Players::Load(const std::string& world, uint32_t id) {
285 Span span = StartChildSpan("load player", SpanKind::kInternal);
286 // A character in another world is no player of this one's.
287 const absl::StatusOr<Result> result = database_.Run(
288 "SELECT name, x, z, experience, health, land, items_revision, quests, "
289 "gold, build, skin, hair_color, hair, shirt, faction FROM players "
290 "WHERE id = ? AND world = ?",
291 {std::to_string(id), world});
292 if (!result.ok()) {
293 return result.status();
294 }
295 if (result->rows.empty()) {
296 return absl::NotFoundError(
297 absl::StrCat("no character ", id, " in ", world));
298 }
299 const std::vector<std::string>& row = result->rows.front();
300 Player player{.name = row[0]};
301 // How they chose to look, which never changes, so it's only ever in MySQL.
302 // A character from before there were looks to choose has none.
303 if (!row[9].empty()) {
304 protocol::Looks looks;
305 uint32_t build = 0;
306 uint32_t skin = 0;
307 uint32_t hair_color = 0;
308 uint32_t hair = 0;
309 if (!absl::SimpleAtoi(row[9], &build) ||
310 !absl::SimpleAtoi(row[10], &skin) ||
311 !absl::SimpleAtoi(row[11], &hair_color) ||
312 !absl::SimpleAtoi(row[12], &hair)) {
313 return absl::InternalError("looks that aren't numbers");
314 }
315 looks.set_build(build);
316 looks.set_skin(skin);
317 looks.set_hair_color(hair_color);
318 looks.set_hair(hair);
319 // And the colour of their clothes, unless they're from before there was
320 // one to choose.
321 uint32_t shirt = 0;
322 if (!row[13].empty()) {
323 if (!absl::SimpleAtoi(row[13], &shirt)) {
324 return absl::InternalError("looks that aren't numbers");
325 }
326 looks.set_shirt(shirt);
327 }
328 player.looks = looks;
329 }
330 // Where they are, their experience, health and land, and next their skills.
331 std::vector<std::string> saved(row.begin() + 1, row.begin() + 6);
332 // A row for each skill, which we join the way Redis keeps them.
333 const absl::StatusOr<Result> skills = database_.Run(
334 "SELECT skill FROM player_skills WHERE player = ?", {std::to_string(id)});
335 if (!skills.ok()) {
336 return skills.status();
337 }
338 std::vector<std::string> known;
339 for (const std::vector<std::string>& skill : skills->rows) {
340 known.push_back(skill[0]);
341 }
342 saved.push_back(absl::StrJoin(known, ","));
343 // And a row for each stack in the bag, and each item worn.
344 const absl::StatusOr<Result> items = database_.Run(
345 "SELECT place, item, count, state FROM player_items WHERE player = ?",
346 {std::to_string(id)});
347 if (!items.ok()) {
348 return items.status();
349 }
350 absl::StatusOr<protocol::Inventory> bag = BagOf(*items, row[6], row[8]);
351 if (!bag.ok()) {
352 return bag.status();
353 }
354 // And the quests, from their JSON.
355 protocol::Quests quests;
356 google::protobuf::util::JsonParseOptions options;
357 options.ignore_unknown_fields = true;
358 if (!row[7].empty() &&
359 !google::protobuf::util::JsonStringToMessage(row[7], &quests, options)
360 .ok()) {
361 return absl::InternalError("saved quests that aren't any");
362 }
363
364 const absl::StatusOr<std::vector<std::vector<std::string>>> newer =
365 redis_.Pipeline(
366 {{"HMGET", Key(world, id), "x", "z", "experience", "health", "land",
367 "skills", "items", "quests", "faction"}});
368 if (!newer.ok()) {
369 return newer.status();
370 }
371 const std::vector<std::string>& hash = newer->front();
372 if (!hash[0].empty()) {
373 saved.assign(hash.begin(), hash.begin() + 6);
374 }
375 // Redis has the bag from when it last changed, and a hash from a server
376 // from before bags, or one written since the bag came from MySQL, has none,
377 // so MySQL's is the newest.
378 if (!hash[6].empty() && !bag->ParseFromString(hash[6])) {
379 return absl::InternalError("a saved bag that isn't one");
380 }
381 // The same goes for the quests, from a server from before them.
382 if (!hash[7].empty() && !quests.ParseFromString(hash[7])) {
383 return absl::InternalError("saved quests that aren't any");
384 }
385 player.quests = {quests.on().begin(), quests.on().end()};
386 player.quests_done = {quests.done().begin(), quests.done().end()};
387 player.quests_revision = quests.revision();
388 // Their faction is for good: MySQL's, once the saver's taken it there, or
389 // Redis's until then. None is empty in both.
390 const std::string& faction = !row[14].empty() ? row[14] : hash[8];
391 if (!faction.empty() && !absl::SimpleAtoi(faction, &player.faction)) {
392 return absl::InternalError("a saved faction that isn't a number");
393 }
394 player.inventory = Inventory(*std::move(bag));
395 if (!absl::SimpleAtof(saved[0], &player.x) ||
396 !absl::SimpleAtof(saved[1], &player.z) ||
397 !absl::SimpleAtoi(saved[2], &player.experience)) {
398 return absl::InternalError("a saved player that isn't numbers");
399 }
400 if (!saved[3].empty() && !absl::SimpleAtoi(saved[3], &player.health)) {
401 return absl::InternalError("a saved health that isn't a number");
402 }
403 player.land = LandNamed(saved[4]);
404 for (const std::string_view skill :
405 absl::StrSplit(saved[5], ',', absl::SkipEmpty())) {
406 uint32_t id = 0;
407 if (!absl::SimpleAtoi(skill, &id)) {
408 return absl::InternalError("a saved skill that isn't a number");
409 }
410 player.skills.insert(id);
411 }
412 return player;
413}
414
415absl::StatusOr<std::string> Players::Lease(const std::string& world,
416 uint32_t id,
417 const std::string& instance) {
418 Span span = StartChildSpan("lease player", SpanKind::kInternal);
419 absl::StatusOr<std::string> lease = redis_.Command(
420 {"EVAL", kTake, "2", LeaseKey(world, id), FencingKey(world), instance,
421 absl::StrCat(kLease.count())});
422 if (!lease.ok()) {
423 return lease.status();
424 }
425 // The instance that has it comes before its number.
426 const std::string_view holder =
427 std::string_view(*lease).substr(0, lease->rfind(' '));
428 if (holder != instance) {
429 return absl::FailedPreconditionError(
430 absl::StrCat("they're playing on ", holder));
431 }
432 return lease;
433}
434
435absl::StatusOr<std::set<uint32_t>> Players::Renew(
436 const std::string& world, const std::map<uint32_t, std::string>& leases) {
437 if (leases.empty()) {
438 return std::set<uint32_t>();
439 }
440 std::vector<std::string> eval = {"EVAL", kRenew, absl::StrCat(leases.size())};
441 for (const auto& [id, lease] : leases) {
442 eval.push_back(LeaseKey(world, id));
443 }
444 eval.push_back(absl::StrCat(kLease.count()));
445 for (const auto& [id, lease] : leases) {
446 eval.push_back(lease);
447 }
448 const absl::StatusOr<std::vector<std::vector<std::string>>> lost =
449 redis_.Pipeline({eval});
450 if (!lost.ok()) {
451 return lost.status();
452 }
453 return Leased(lost->front());
454}
455
456absl::Status Players::Release(const std::string& world, uint32_t id,
457 const std::string& lease) {
458 return redis_.Command({"EVAL", kRelease, "1", LeaseKey(world, id), lease})
459 .status();
460}
461
462absl::StatusOr<std::set<uint32_t>> Players::Pass(
463 const std::string& world, const std::map<uint32_t, std::string>& leases,
464 const std::string& next) {
465 Span span = StartChildSpan("pass leases", SpanKind::kInternal);
466 std::vector<std::string> eval = {
467 "EVAL", kPass, absl::StrCat(leases.size() + 1), FencingKey(world)};
468 for (const auto& [id, lease] : leases) {
469 eval.push_back(LeaseKey(world, id));
470 }
471 eval.insert(eval.end(), {next, absl::StrCat(kLease.count())});
472 for (const auto& [id, lease] : leases) {
473 eval.push_back(lease);
474 }
475 const absl::StatusOr<std::vector<std::vector<std::string>>> passed =
476 redis_.Pipeline({eval});
477 if (!passed.ok()) {
478 return passed.status();
479 }
480 return Leased(passed->front());
481}
482
483absl::StatusOr<std::set<uint32_t>> Players::Save(
484 const std::string& world, const std::map<uint32_t, Progress>& changed,
485 const std::map<uint32_t, protocol::Inventory>& bags,
486 const std::map<uint32_t, std::string>& leases,
487 const std::optional<Traded>& traded, const std::vector<WarKill>& kills) {
488 if (changed.empty() && !traded && kills.empty()) {
489 return std::set<uint32_t>();
490 }
491 Span span = StartChildSpan("save players", SpanKind::kInternal);
492 std::vector<std::vector<std::string>> commands;
493 std::vector<std::string> unsaved = {"SADD", kUnsaved};
494 std::vector<std::string> items_unsaved = {"SADD", kItemsUnsaved};
495 for (const auto& [id, progress] : changed) {
496 // A player who's sworn to no faction has none, as in a hash from before
497 // factions.
498 const std::string faction =
499 progress.faction != 0 ? absl::StrCat(progress.faction) : "";
500 std::vector<std::string>& hset =
501 commands.emplace_back(std::vector<std::string>{
502 "HSET", Key(world, id),
503 "world", world,
504 "player", absl::StrCat(id),
505 "x", absl::StrCat(progress.x),
506 "z", absl::StrCat(progress.z),
507 "experience", absl::StrCat(progress.experience),
508 "health", absl::StrCat(progress.health),
509 "land", kLands[progress.land].name,
510 "weapon", absl::StrCat(progress.weapon),
511 "skills", absl::StrJoin(progress.skills, ","),
512 "quests", QuestsOf(progress).SerializeAsString(),
513 "faction", faction});
514 unsaved.push_back(Key(world, id));
515 // The bag goes as its message, in protobuf's bytes, which Redis keeps as
516 // they are.
517 if (const auto bag = bags.find(id); bag != bags.end()) {
518 hset.insert(hset.end(), {"items", bag->second.SerializeAsString()});
519 items_unsaved.push_back(Key(world, id));
520 }
521 }
522 if (unsaved.size() > 2) {
523 commands.push_back(unsaved);
524 }
525 if (items_unsaved.size() > 2) {
526 commands.push_back(items_unsaved);
527 }
528 // The trade's record goes with its bags, so the saver takes them to MySQL
529 // together. It's a message to the saver, through the stream, with the
530 // traceparent of this span, which the saver's span for it goes under.
531 const Span publishing =
532 traded ? StartChildSpan("publish trade", SpanKind::kProducer) : Span();
533 if (traded) {
534 std::vector<std::string>& added =
535 commands.emplace_back(std::vector<std::string>{
536 "XADD", kTrades, "*", "id", traded->id, "world", world, "player",
537 absl::StrCat(traded->player), "player_gave",
538 GaveOf(traded->player_gave), "partner",
539 absl::StrCat(traded->partner), "partner_gave",
540 GaveOf(traded->partner_gave)});
541 if (publishing.recording()) {
542 added.insert(added.end(),
543 {"traceparent", Traceparent(publishing.context())});
544 }
545 }
546 // Each war kill goes to the saver in a stream of its own, with the players
547 // it changed, for its war's score.
548 for (const WarKill& kill : kills) {
549 commands.push_back(
550 {"XADD", kWarKills, "*", "id", kill.id, "war", absl::StrCat(kill.war),
551 "world", world, "killer", absl::StrCat(kill.killer), "victim",
552 absl::StrCat(kill.victim), "guild", absl::StrCat(kill.guild)});
553 }
554 // Another instance that's taken a player has saved them since, and its
555 // saves are the ones to keep.
556 std::map<std::string, std::string> holding;
557 for (const auto& [id, lease] : leases) {
558 holding[LeaseKey(world, id)] = lease;
559 }
560 const absl::StatusOr<std::vector<std::string>> lost =
561 redis_.TransactionIf(holding, commands);
562 if (!lost.ok()) {
563 return lost.status();
564 }
565 return Leased(*lost);
566}
567
568absl::Status Players::PutBack() {
569 // SUNIONSTORE takes the set it stores into as one of its sources, so a
570 // player marked unsaved again since stays so, once.
571 return redis_.Transaction(
572 {{"SUNIONSTORE", kUnsaved, kUnsaved, kSaving},
573 {"DEL", kSaving},
574 {"SUNIONSTORE", kItemsUnsaved, kItemsUnsaved, kItemsSaving},
575 {"DEL", kItemsSaving}});
576}
577
578absl::StatusOr<int> Players::Flush() {
579 // A batch that a flush before took and didn't save, as the saver died, or
580 // MySQL failed, goes back with the unsaved players first.
581 if (const absl::Status back = PutBack(); !back.ok()) {
582 return back;
583 }
584 // As many as are unsaved now, and as many trades and war kills: whoever
585 // changes meanwhile waits for next time.
586 const absl::StatusOr<std::vector<std::vector<std::string>>> counts =
587 redis_.Pipeline(
588 {{"SCARD", kUnsaved}, {"XLEN", kTrades}, {"XLEN", kWarKills}});
589 int left = 0;
590 int trades_left = 0;
591 int kills_left = 0;
592 if (!counts.ok() || !absl::SimpleAtoi(counts->at(0).at(0), &left) ||
593 !absl::SimpleAtoi(counts->at(1).at(0), &trades_left) ||
594 !absl::SimpleAtoi(counts->at(2).at(0), &kills_left)) {
595 return absl::UnavailableError("couldn't count the unsaved players");
596 }
597 int saved = 0;
598 while (left > 0 || trades_left > 0 || kills_left > 0) {
599 // The oldest trades go first, each with both its players, so that MySQL
600 // has a trade's record and both bags from after it, or none of it.
601 std::vector<Redis::Entry> trades;
602 const absl::Time read = absl::Now();
603 if (trades_left > 0) {
604 absl::StatusOr<std::vector<Redis::Entry>> oldest = redis_.Read(
605 {"XREAD", "COUNT", absl::StrCat(std::min(trades_left, kBatch / 2)),
606 "STREAMS", kTrades, "0-0"});
607 if (!oldest.ok()) {
608 return oldest.status();
609 }
610 trades = *std::move(oldest);
611 trades_left =
612 trades.empty() ? 0 : trades_left - static_cast<int>(trades.size());
613 }
614 // And the oldest war kills, which go onto their wars' scores with it.
615 std::vector<Redis::Entry> kills;
616 if (kills_left > 0) {
617 absl::StatusOr<std::vector<Redis::Entry>> oldest = redis_.Read(
618 {"XREAD", "COUNT", absl::StrCat(std::min(kills_left, kBatch)),
619 "STREAMS", kWarKills, "0-0"});
620 if (!oldest.ok()) {
621 return oldest.status();
622 }
623 kills = *std::move(oldest);
624 kills_left =
625 kills.empty() ? 0 : kills_left - static_cast<int>(kills.size());
626 }
627 // The batch's statements in MySQL go under it.
628 const Span saving = StartSavingTrades(trades, read);
629 std::vector<std::string> keys;
630 const auto take = [&keys](const std::string& key) {
631 if (std::ranges::find(keys, key) == keys.end()) {
632 keys.push_back(key);
633 }
634 };
635 for (const Redis::Entry& trade : trades) {
636 for (const char* side : {"player", "partner"}) {
637 uint32_t id = 0;
638 if (absl::SimpleAtoi(FieldOf(trade, side), &id)) {
639 take(Key(FieldOf(trade, "world"), id));
640 }
641 }
642 }
643 // They're in this batch, so they go from the set into the batch's.
644 if (!keys.empty()) {
645 std::vector<std::vector<std::string>> taken;
646 taken.reserve(keys.size());
647 for (const std::string& key : keys) {
648 taken.push_back({"SMOVE", kUnsaved, kSaving, key});
649 }
650 const absl::StatusOr<std::vector<std::vector<std::string>>> moved =
651 redis_.Pipeline(taken);
652 if (!moved.ok()) {
653 return moved.status();
654 }
655 }
656 // The rest come out of the set and into the batch's together, so one who
657 // changes after this is marked unsaved again, and goes in a later batch.
658 const int room = std::min(left, kBatch - static_cast<int>(keys.size()));
659 if (room > 0) {
660 const absl::StatusOr<std::vector<std::vector<std::string>>> popped =
661 redis_.Pipeline({{"EVAL", kTakeBatch, "2", kUnsaved, kSaving,
662 absl::StrCat(room)}});
663 if (!popped.ok()) {
664 return popped.status();
665 }
666 for (const std::string& key : popped->front()) {
667 take(key);
668 }
669 left = popped->front().empty()
670 ? 0
671 : left - static_cast<int>(popped->front().size());
672 }
673 if (keys.empty() && kills.empty()) {
674 break;
675 }
676
677 // Each player's mark for their bag goes into the batch's before their
678 // hash is read, so that a bag that changes in between is marked again,
679 // for next time.
680 std::vector<std::vector<std::string>> reads;
681 reads.reserve(2 * keys.size());
682 for (const std::string& key : keys) {
683 reads.push_back({"SMOVE", kItemsUnsaved, kItemsSaving, key});
684 }
685 for (const std::string& key : keys) {
686 reads.push_back({"HMGET", key, "world", "player", "x", "z", "experience",
687 "health", "land", "weapon", "skills", "items", "quests",
688 "faction"});
689 }
690 const absl::StatusOr<std::vector<std::vector<std::string>>> replies =
691 redis_.Pipeline(reads);
692 if (!replies.ok()) {
693 return replies.status();
694 }
695
696 // The characters' rows are there already, from the login server, so a
697 // batch updates them, as a table of its rows joined to theirs: a character
698 // deleted since leaves nothing to join, and its row stays gone.
699 std::string sql = "UPDATE players JOIN (VALUES ";
700 std::vector<std::string> values;
701 int rows = 0;
702 // IGNORE skips the skills and the bags of a character that's gone, with a
703 // warning, so that one row MySQL refuses doesn't hold back the batch.
704 std::string skills_sql =
705 "INSERT IGNORE INTO player_skills (player, skill) VALUES ";
706 std::vector<std::string> skill_values;
707 // The bags that changed: their old rows go, and their new ones go in.
708 std::string gone_sql = "DELETE FROM player_items WHERE player IN (";
709 std::vector<std::string> gone_values;
710 // Five values a row.
711 std::vector<std::string> item_values;
712 for (std::size_t i = 0; i < keys.size(); ++i) {
713 const bool bag_changed = (*replies)[i] == std::vector<std::string>{"1"};
714 const std::vector<std::string>& hash = (*replies)[keys.size() + i];
715 // A player whose hash is gone has nothing to save, and one from before
716 // characters, saved by its account, has nothing to say which character
717 // it was: the saver flushed those before the characters came.
718 if (hash[0].empty() || hash[1].empty()) {
719 continue;
720 }
721 // A hash saved before we kept health or weapons has none, which goes in
722 // as NULL, and one saved before lands is in the Meadows. A bag that
723 // hasn't changed keeps the revision and the gold MySQL has.
724 absl::StrAppend(&sql, rows == 0 ? "" : ", ",
725 "ROW(?, ?, ?, ?, ?, NULLIF(?, ''), "
726 "COALESCE(NULLIF(?, ''), 'Meadows'), NULLIF(?, ''), "
727 "NULLIF(?, ''), NULLIF(?, ''), NULLIF(?, ''), "
728 "NULLIF(?, ''))");
729 ++rows;
730 const std::string& world = hash[0];
731 const std::string& player = hash[1];
732 values.insert(values.end(), {player, world});
733 values.insert(values.end(), hash.begin() + 2, hash.begin() + 8);
734 protocol::Inventory bag;
735 if (!bag_changed || hash[9].empty() || !bag.ParseFromString(hash[9])) {
736 values.insert(values.end(), {"", ""});
737 } else {
738 values.push_back(absl::StrCat(bag.revision()));
739 values.push_back(absl::StrCat(bag.gold()));
740 absl::StrAppend(&gone_sql, gone_values.empty() ? "" : ", ", "?");
741 gone_values.push_back(player);
742 const auto add = [&](const protocol::Place& place,
743 const items::Stack& stack) {
744 item_values.insert(
745 item_values.end(),
746 {player, PlaceName(place), absl::StrCat(stack.item()),
747 absl::StrCat(stack.count()), StateOf(stack)});
748 };
749 for (const auto& [slot, stack] : bag.bag()) {
750 add(InBag(slot), stack);
751 }
752 for (const auto& [slot, stack] : bag.worn()) {
753 add(Worn(static_cast<items::Slot>(slot)), stack);
754 }
755 }
756 // The quests go with the row, as JSON, and a hash without them, from
757 // before quests, leaves MySQL's. Once they've changed, they have their
758 // revision, so a player who's given up all they were on saves as that.
759 protocol::Quests quests;
760 std::string json;
761 if (!hash[10].empty() && quests.ParseFromString(hash[10])) {
762 google::protobuf::util::MessageToJsonString(quests, &json)
763 .IgnoreError();
764 }
765 values.push_back(json);
766 // And their faction, if they've sworn to one.
767 values.push_back(hash[11]);
768 // The skills go into a table of their own, a row each.
769 for (const std::string_view skill :
770 absl::StrSplit(hash[8], ',', absl::SkipEmpty())) {
771 absl::StrAppend(&skills_sql, skill_values.empty() ? "" : ", ",
772 "(?, ?)");
773 skill_values.insert(skill_values.end(), {player, std::string(skill)});
774 }
775 }
776 // Each trade's record, from the millisecond Redis took it, by its entry's
777 // id. IGNORE skips one that's in MySQL already, from a batch that MySQL
778 // committed without the saver hearing so, which it tries again.
779 std::string trades_sql =
780 "INSERT IGNORE INTO trades (id, world, player, player_gave, partner, "
781 "partner_gave, traded_at) VALUES ";
782 std::vector<std::string> trade_values;
783 std::vector<std::string> recorded = {"XDEL", kTrades};
784 for (const Redis::Entry& trade : trades) {
785 absl::StrAppend(&trades_sql, trade_values.empty() ? "" : ", ",
786 "(?, ?, ?, ?, ?, ?, FROM_UNIXTIME(? / 1000))");
787 for (const char* field : {"id", "world", "player", "player_gave",
788 "partner", "partner_gave"}) {
789 trade_values.push_back(FieldOf(trade, field));
790 }
791 trade_values.push_back(trade.id.substr(0, trade.id.find('-')));
792 recorded.push_back(trade.id);
793 }
794 // Each war kill is a row of its own, by the id the world server gave it,
795 // from the millisecond Redis took it, as a trade's record is. IGNORE
796 // skips one that's in MySQL already, from a batch MySQL committed that
797 // the saver reads again, and one whose war has gone since. A kill from a
798 // server before 0.92.0, during a deploy, has no id, and goes by its
799 // entry's.
800 std::string kills_sql =
801 "INSERT IGNORE INTO war_kills (id, war, world, killer, victim, guild, "
802 "killed_at) VALUES ";
803 std::vector<std::string> kill_values;
804 std::vector<std::string> counted = {"XDEL", kWarKills};
805 for (const Redis::Entry& kill : kills) {
806 absl::StrAppend(&kills_sql, kill_values.empty() ? "" : ", ",
807 "(COALESCE(NULLIF(?, ''), ?), ?, ?, ?, ?, ?, "
808 "FROM_UNIXTIME(? / 1000))");
809 kill_values.push_back(FieldOf(kill, "id"));
810 kill_values.push_back(kill.id);
811 for (const char* field : {"war", "world", "killer", "victim", "guild"}) {
812 kill_values.push_back(FieldOf(kill, field));
813 }
814 kill_values.push_back(kill.id.substr(0, kill.id.find('-')));
815 counted.push_back(kill.id);
816 }
817 if (rows == 0 && trades.empty() && kills.empty()) {
818 redis_.Command({"DEL", kSaving, kItemsSaving}).IgnoreError();
819 continue;
820 }
821 absl::StrAppend(
822 &sql,
823 ") AS saved (id, world, x, z, experience, health, land, weapon, "
824 "items_revision, gold, quests, faction) "
825 "ON players.id = saved.id AND players.world = saved.world "
826 "SET players.x = saved.x, players.z = saved.z, "
827 "players.experience = saved.experience, players.health = saved.health, "
828 "players.land = saved.land, players.weapon = saved.weapon, "
829 "players.items_revision = "
830 "COALESCE(saved.items_revision, players.items_revision), "
831 "players.gold = COALESCE(saved.gold, players.gold), "
832 "players.quests = COALESCE(saved.quests, players.quests), "
833 // A faction is for good, so the saver writes one only where there's
834 // none, and nothing switches it, nor does a hash with none take it.
835 "players.faction = COALESCE(players.faction, saved.faction)");
836 absl::StrAppend(&gone_sql, ")");
837 // A bag's rows can't go without the rows that take their place, or a
838 // failure between the two would empty it, so the batch is a transaction.
839 const absl::Status written = database_.Transaction([&] {
840 absl::StatusOr<Result> result =
841 rows > 0 ? database_.Run(sql, values) : Result();
842 // A skill once learned stays learned, so each flush inserts each skill
843 // a player knows, and IGNORE skips the ones MySQL has already, and those
844 // of a player whose row it refused.
845 if (result.ok() && !skill_values.empty()) {
846 result = database_.Run(skills_sql, skill_values);
847 }
848 if (result.ok() && !gone_values.empty()) {
849 result = database_.Run(gone_sql, gone_values);
850 }
851 // A statement takes up to 65,535 values, and the rows of 500 full bags
852 // have more, so they go in statements of kItemRows rows.
853 constexpr std::size_t kRowValues = 5;
854 for (std::size_t first = 0; result.ok() && first < item_values.size();
855 first += kItemRows * kRowValues) {
856 const std::size_t last =
857 std::min(item_values.size(), first + kItemRows * kRowValues);
858 std::string items_sql =
859 "INSERT IGNORE INTO player_items (player, place, item, "
860 "count, state) VALUES ";
861 for (std::size_t row = first; row < last; row += kRowValues) {
862 absl::StrAppend(&items_sql, row == first ? "" : ", ",
863 "(?, ?, ?, ?, NULLIF(?, ''))");
864 }
865 result = database_.Run(items_sql, {item_values.begin() + first,
866 item_values.begin() + last});
867 }
868 if (result.ok() && !trade_values.empty()) {
869 result = database_.Run(trades_sql, trade_values);
870 }
871 if (result.ok() && !kill_values.empty()) {
872 result = database_.Run(kills_sql, kill_values);
873 }
874 return result.status();
875 });
876 if (!written.ok()) {
877 // Back into the sets, so that the next flush tries them again, or, if
878 // that fails too, as the next flush starts.
879 PutBack().IgnoreError();
880 return written;
881 }
882 // MySQL has them, so the batch's set goes. Should this fail, the next
883 // flush saves them again, as it does the trades, which IGNORE skips.
884 if (!trades.empty()) {
885 redis_.Pipeline({recorded, {"DEL", kSaving, kItemsSaving}}).IgnoreError();
886 } else {
887 redis_.Command({"DEL", kSaving, kItemsSaving}).IgnoreError();
888 }
889 // The kills are on their wars' scores, so they leave the stream.
890 if (!kills.empty()) {
891 redis_.Command(counted).IgnoreError();
892 }
893 saved += rows;
894 }
895 return saved;
896}
897
898absl::StatusOr<int> Players::Unsaved() {
899 // Those in a batch that's being saved, or was and wasn't, aren't saved yet
900 // either, and one who's changed since is in both sets, and counts once.
901 const absl::StatusOr<std::string> counted =
902 redis_.Command({"EVAL", kCountUnion, "2", kUnsaved, kSaving});
903 if (!counted.ok()) {
904 return counted.status();
905 }
906 int unsaved = 0;
907 if (!absl::SimpleAtoi(*counted, &unsaved)) {
908 return absl::InternalError("a count of unsaved players that isn't one");
909 }
910 return unsaved;
911}
912
913absl::StatusOr<int> Players::Duplicates() {
914 // By player_items' serial, from V13, which MySQL takes from each row's
915 // state, and indexes.
916 const absl::StatusOr<Result> counted = database_.Run(
917 "SELECT COUNT(*) FROM (SELECT serial FROM player_items "
918 "WHERE serial IS NOT NULL GROUP BY serial HAVING COUNT(*) > 1) AS twice");
919 if (!counted.ok()) {
920 return counted.status();
921 }
922 int duplicates = 0;
923 if (counted->rows.empty() ||
924 !absl::SimpleAtoi(counted->rows.front().front(), &duplicates)) {
925 return absl::InternalError("a count of duplicates that isn't a number");
926 }
927 return duplicates;
928}
929
930} // namespace nanommo
static constexpr int kBatch
Definition players.h:64
absl::Status Release(const std::string &world, uint32_t id, const std::string &lease)
Definition players.cc:456
absl::StatusOr< std::set< uint32_t > > Renew(const std::string &world, const std::map< uint32_t, std::string > &leases)
Definition players.cc:435
absl::StatusOr< std::set< uint32_t > > Pass(const std::string &world, const std::map< uint32_t, std::string > &leases, const std::string &next)
Definition players.cc:462
absl::StatusOr< int > Duplicates()
Definition players.cc:913
absl::StatusOr< int > Flush()
Definition players.cc:578
absl::StatusOr< int > Unsaved()
Definition players.cc:898
static constexpr std::chrono::milliseconds kLease
How long a lease on a player lasts, unless its instance renews it.
Definition players.h:68
static constexpr std::size_t kItemRows
The most rows of the bags that go in one statement.
Definition players.h:66
absl::StatusOr< std::set< uint32_t > > Save(const std::string &world, const std::map< uint32_t, Progress > &changed, const std::map< uint32_t, protocol::Inventory > &bags={}, const std::map< uint32_t, std::string > &leases={}, const std::optional< Traded > &traded=std::nullopt, const std::vector< WarKill > &kills={})
Definition players.cc:483
absl::StatusOr< Player > Load(const std::string &world, uint32_t id)
Definition players.cc:284
absl::StatusOr< std::string > Lease(const std::string &world, uint32_t id, const std::string &instance)
Definition players.cc:415
absl::Status Transaction(const std::vector< std::vector< std::string > > &commands)
Definition redis.cc:313
bool recording() const
Definition tracing.h:71
Definition chat.cc:9
Span StartSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:389
int LandNamed(std::string_view name)
Its place in the list, or the first land's for a name that isn't there.
Definition lands.cc:10
constexpr std::array< Land, 3 > kLands
Definition lands.h:31
absl::StatusOr< SpanContext > ParseTraceparent(std::string_view traceparent)
Definition tracing.cc:274
protocol::Place Worn(items::Slot slot)
A slot that's worn.
Definition places.cc:13
protocol::World BagOf(const Player &player)
Their bag, and their quests, each as it goes when it's changed.
Definition shown.cc:136
protocol::Place InBag(uint32_t slot)
A place in the bag, by its slot from zero.
Definition places.cc:7
protocol::World QuestsOf(const Player &player)
Definition shown.cc:142
Span StartChildSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:404
std::string_view SlotName(items::Slot slot)
The slot's name, as a player would say it, such as "main hand".
Definition items.cc:106
uint32_t experience
Definition world.h:64
std::set< uint32_t > skills
The skills the player knows, by their ids in the skills file.
Definition world.h:72
int land
Which of the world's lands, by its place in kLands.
Definition world.h:67
std::set< uint32_t > quests_done
The quests they've turned in, which they can't take again.
Definition world.h:77
std::optional< protocol::Looks > looks
Definition world.h:52
uint32_t quests_revision
Definition world.h:80
std::map< uint32_t, uint32_t > quests
Definition world.h:75
uint32_t faction
Definition world.h:58
Inventory inventory
What the player carries and wears.
Definition world.h:69
What we keep of a player from one session to the next.
Definition players.h:23