nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
recorder.cc
Go to the documentation of this file.
1#include "server/recorder.h"
2
3#include <string>
4#include <string_view>
5#include <utility>
6#include <vector>
7
8#include "absl/strings/match.h"
9#include "server/events.h"
10
11namespace nanommo {
12
13Recorder::Recorder(Redis& redis, std::string consumer, Sink sink,
14 std::chrono::milliseconds wait)
15 : redis_(redis),
16 consumer_(std::move(consumer)),
17 sink_(std::move(sink)),
18 wait_(wait) {}
19
20absl::StatusOr<int> Recorder::Record() {
21 if (!grouped_) {
22 // From the start of the stream, which MKSTREAM makes if it isn't there. A
23 // group that's there already is fine.
24 const absl::StatusOr<std::string> created = redis_.Command(
25 {"XGROUP", "CREATE", kEventStream, kGroup, "0", "MKSTREAM"});
26 if (!created.ok() &&
27 !absl::StrContains(created.status().message(), "BUSYGROUP")) {
28 return created.status();
29 }
30 grouped_ = true;
31 }
32 // Zero reads what this consumer took and hasn't acknowledged, and > what
33 // nobody in the group has taken yet, waiting for it.
34 std::vector<std::string> words = {"XREADGROUP", "GROUP", kGroup, consumer_};
35 words.insert(words.end(), {"COUNT", std::to_string(kBatch)});
36 if (!pending_) {
37 words.insert(words.end(), {"BLOCK", std::to_string(wait_.count())});
38 }
39 words.insert(words.end(), {"STREAMS", kEventStream, pending_ ? "0" : ">"});
40 const absl::StatusOr<std::vector<Redis::Entry>> entries = redis_.Read(words);
41 if (!entries.ok()) {
42 return entries.status();
43 }
44 if (entries->empty()) {
45 pending_ = false;
46 return 0;
47 }
48 std::string rows;
49 std::vector<std::string> ack = {"XACK", kEventStream, kGroup};
50 for (const Redis::Entry& entry : *entries) {
51 // Fields and values take turns.
52 for (std::size_t i = 0; i + 1 < entry.fields.size(); i += 2) {
53 if (entry.fields[i] == "row") {
54 rows += entry.fields[i + 1];
55 rows += '\n';
56 }
57 }
58 ack.push_back(entry.id);
59 }
60 if (!rows.empty()) {
61 const absl::Status stored = sink_(rows);
62 if (!stored.ok()) {
63 // They stay taken and unacknowledged, for the next try.
64 pending_ = true;
65 return stored;
66 }
67 }
68 const absl::StatusOr<std::string> acked = redis_.Command(ack);
69 if (!acked.ok()) {
70 return acked.status();
71 }
72 return static_cast<int>(entries->size());
73}
74
75} // namespace nanommo
absl::StatusOr< int > Record()
Definition recorder.cc:20
static constexpr char kGroup[]
Definition recorder.h:25
std::function< absl::Status(std::string_view rows)> Sink
Stores a batch of rows, one a line, or says why it couldn't.
Definition recorder.h:20
Recorder(Redis &redis, std::string consumer, Sink sink, std::chrono::milliseconds wait=std::chrono::seconds(1))
Waits up to wait each time for events to come, as the consumer.
Definition recorder.cc:13
Definition chat.cc:9
constexpr char kEventStream[]
Definition events.h:20