nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
redis.cc
Go to the documentation of this file.
1#include "server/redis.h"
2
3// timeval, which hiredis takes for its timeouts.
4#if defined(_WIN32)
5#include <winsock2.h>
6#else
7#include <sys/time.h>
8#endif
9
10#include <algorithm>
11#include <cerrno>
12#include <chrono>
13#include <cstddef>
14#include <cstdint>
15#include <map>
16#include <memory>
17#include <optional>
18#include <span>
19#include <string>
20#include <string_view>
21#include <utility>
22#include <vector>
23
24#include "absl/memory/memory.h"
25#include "absl/status/status.h"
26#include "absl/strings/numbers.h"
27#include "absl/strings/str_cat.h"
28#include "absl/strings/str_join.h"
29#include "absl/time/time.h"
30#include "server/tracing.h"
31
32namespace nanommo {
33
34namespace {
35
36using Reply = std::unique_ptr<redisReply, decltype(&freeReplyObject)>;
37
38timeval TimevalOf(std::chrono::milliseconds time) {
39 return {.tv_sec = static_cast<decltype(timeval::tv_sec)>(time.count() / 1000),
40 .tv_usec = static_cast<decltype(timeval::tv_usec)>(
41 (time.count() % 1000) * 1000)};
42}
43
44// How long a read with BLOCK waits in Redis, where zero is for ever, or
45// nothing without BLOCK.
46std::optional<std::chrono::milliseconds> Blocks(
47 const std::vector<std::string>& words) {
48 const auto block = std::ranges::find(words, "BLOCK");
49 int64_t wait = 0;
50 if (block == words.end() || block + 1 == words.end() ||
51 !absl::SimpleAtoi(*(block + 1), &wait)) {
52 return std::nullopt;
53 }
54 return std::chrono::milliseconds(wait);
55}
56
57// A call, as a span under the request it's made for, named by its commands,
58// such as GETDEL, or SREM HMGET for a pipeline of both, without their keys or
59// values.
60Span StartCall(std::span<const std::vector<std::string>> commands) {
61 if (!InTrace()) {
62 return Span();
63 }
64 std::vector<std::string_view> names;
65 for (const std::vector<std::string>& words : commands) {
66 if (!words.empty() && std::ranges::find(names, words[0]) == names.end()) {
67 names.emplace_back(words[0]);
68 }
69 }
70 const std::string operation = absl::StrJoin(names, " ");
71 Span span =
72 StartChildSpan(absl::StrCat("redis ", operation), SpanKind::kClient);
73 span.SetAttribute("db.system", "redis");
74 span.SetAttribute("db.operation", operation);
75 return span;
76}
77
78void Append(redisContext* context, const std::vector<std::string>& words) {
79 // Each word goes with its length, so it can hold any bytes, spaces and all.
80 std::vector<const char*> argv;
81 std::vector<std::size_t> lengths;
82 for (const std::string& word : words) {
83 argv.push_back(word.data());
84 lengths.push_back(word.size());
85 }
86 redisAppendCommandArgv(context, static_cast<int>(argv.size()), argv.data(),
87 lengths.data());
88}
89
90std::string Text(const redisReply& reply) {
91 if (reply.type == REDIS_REPLY_INTEGER) {
92 return absl::StrCat(reply.integer);
93 }
94 return reply.str != nullptr ? std::string(reply.str, reply.len) : "";
95}
96
97// Each key in KEYS has to hold the value at its place in ARGV, or nothing
98// runs, and it returns those that don't. Past those values, ARGV has the
99// commands, each as how many words it has, and then its words.
100constexpr char kIf[] = R"lua(
101local wrong = {}
102for i, key in ipairs(KEYS) do
103 if redis.call('GET', key) ~= ARGV[i] then
104 wrong[#wrong + 1] = key
105 end
106end
107if #wrong > 0 then
108 return wrong
109end
110local i = #KEYS + 1
111while i <= #ARGV do
112 local words = tonumber(ARGV[i])
113 redis.call(unpack(ARGV, i + 1, i + words))
114 i = i + words + 1
115end
116return wrong
117)lua";
118
119} // namespace
120
121absl::StatusOr<std::unique_ptr<Redis>> Redis::Create(const std::string& host,
122 int port,
123 RedisTimeouts timeouts) {
124 // hiredis keeps its own copies of the timeouts, and connects with them
125 // again after a lost connection.
126 const timeval answer = TimevalOf(timeouts.answer);
127 redisOptions options{};
128 REDIS_OPTIONS_SET_TCP(&options, host.c_str(), port);
129 options.connect_timeout = &answer;
130 options.command_timeout = &answer;
131 redisContext* context = redisConnectWithOptions(&options);
132 if (context == nullptr) {
133 return absl::ResourceExhaustedError("out of memory connecting to Redis");
134 }
135 // The object owns the context from here, so an error below frees it.
136 std::unique_ptr<Redis> redis = absl::WrapUnique(new Redis(context, timeouts));
137 if (context->err != 0) {
138 return absl::UnavailableError(
139 absl::StrCat("couldn't connect to Redis: ", context->errstr));
140 }
141 return redis;
142}
143
144Redis::~Redis() { redisFree(context_); }
145
146void Redis::FailFast() {
147 failing_until_ = std::chrono::steady_clock::now() + timeouts_.fail_fast;
148}
149
150absl::Status Redis::Ready() {
151 if (std::chrono::steady_clock::now() < failing_until_) {
152 return absl::UnavailableError(
153 "Redis didn't answer a moment ago, so it isn't asked yet");
154 }
155 // A lost connection, say from Redis restarting, or one that timed out,
156 // leaves its error on the context, and hiredis can connect again with the
157 // settings it kept. A connection that timed out is never used again, as a
158 // reply that came late would answer the next command.
159 if (context_->err != 0 && redisReconnect(context_) != REDIS_OK) {
160 FailFast();
161 return absl::UnavailableError(
162 absl::StrCat("couldn't reconnect to Redis: ", context_->errstr));
163 }
164 return absl::OkStatus();
165}
166
167absl::StatusOr<Reply> Redis::NextReply() {
168 void* reply = nullptr;
169 if (redisGetReply(context_, &reply) != REDIS_OK) {
170 // A blocking socket whose wait for a reply runs out says to try again.
171 const bool timed_out = context_->err == REDIS_ERR_TIMEOUT ||
172 (context_->err == REDIS_ERR_IO &&
173 (errno == EAGAIN || errno == EWOULDBLOCK));
174 if (timed_out) {
175 FailFast();
176 return absl::UnavailableError(absl::StrCat(
177 "Redis didn't answer within ",
178 absl::FormatDuration(absl::FromChrono(timeouts_.answer))));
179 }
180 return absl::UnavailableError(
181 absl::StrCat("lost the connection to Redis: ", context_->errstr));
182 }
183 return Reply(static_cast<redisReply*>(reply), freeReplyObject);
184}
185
186absl::StatusOr<std::string> Redis::Command(
187 const std::vector<std::string>& words) {
188 const Span span = StartCall({&words, 1});
189 const absl::Status ready = Ready();
190 if (!ready.ok()) {
191 return ready;
192 }
193 Append(context_, words);
194 const absl::StatusOr<Reply> reply_or = NextReply();
195 if (!reply_or.ok()) {
196 return reply_or.status();
197 }
198 const Reply& reply = *reply_or;
199
200 switch (reply->type) {
201 case REDIS_REPLY_NIL:
202 return absl::NotFoundError("Redis has nothing there");
203 case REDIS_REPLY_INTEGER:
204 return absl::StrCat(reply->integer);
205 case REDIS_REPLY_STRING:
206 case REDIS_REPLY_STATUS:
207 return std::string(reply->str, reply->len);
208 case REDIS_REPLY_ERROR:
209 return absl::InternalError(
210 absl::StrCat("Redis: ", std::string_view(reply->str, reply->len)));
211 default:
212 return absl::UnimplementedError(
213 "Redis replied with a type we don't read");
214 }
215}
216
217absl::StatusOr<std::vector<Redis::Entry>> Redis::Read(
218 const std::vector<std::string>& words) {
219 const Span span = StartCall({&words, 1});
220 const absl::Status ready = Ready();
221 if (!ready.ok()) {
222 return ready;
223 }
224 Append(context_, words);
225 // A read that waits for entries to come waits that long for its reply, on
226 // top of the timeout, and then the timeout's as it was. BLOCK 0 waits for
227 // ever, and so does its read, as a timeout of zero is none.
228 const std::optional<std::chrono::milliseconds> blocks = Blocks(words);
229 if (blocks) {
230 const std::chrono::milliseconds wait =
231 blocks->count() == 0 ? *blocks : timeouts_.answer + *blocks;
232 redisSetTimeout(context_, TimevalOf(wait));
233 }
234 const absl::StatusOr<Reply> reply = NextReply();
235 // hiredis keeps the timeout for the connection it makes next, too, so it's
236 // put back even after a reply that didn't come.
237 if (blocks) {
238 redisSetTimeout(context_, TimevalOf(timeouts_.answer));
239 }
240 if (!reply.ok()) {
241 return reply.status();
242 }
243 if ((*reply)->type == REDIS_REPLY_ERROR) {
244 return absl::InternalError(absl::StrCat("Redis: ", Text(**reply)));
245 }
246 // Nil when it timed out, or else a list of streams, each a list of its name
247 // and its entries, each a list of its id and its fields.
248 std::vector<Entry> entries;
249 if ((*reply)->type != REDIS_REPLY_ARRAY || (*reply)->elements == 0) {
250 return entries;
251 }
252 const redisReply& stream = *(*reply)->element[0];
253 if (stream.type != REDIS_REPLY_ARRAY || stream.elements < 2 ||
254 stream.element[1]->type != REDIS_REPLY_ARRAY) {
255 return absl::InternalError("Redis: a stream we can't read");
256 }
257 const redisReply& read = *stream.element[1];
258 for (std::size_t i = 0; i < read.elements; ++i) {
259 const redisReply& entry = *read.element[i];
260 if (entry.type != REDIS_REPLY_ARRAY || entry.elements < 2) {
261 continue;
262 }
263 Entry& added = entries.emplace_back();
264 added.id = Text(*entry.element[0]);
265 // An entry trimmed away since it was read has nil for its fields.
266 const redisReply& fields = *entry.element[1];
267 for (std::size_t j = 0;
268 fields.type == REDIS_REPLY_ARRAY && j < fields.elements; ++j) {
269 added.fields.push_back(Text(*fields.element[j]));
270 }
271 }
272 return entries;
273}
274
275absl::StatusOr<std::vector<std::vector<std::string>>> Redis::Pipeline(
276 const std::vector<std::vector<std::string>>& commands) {
277 const Span span = StartCall(commands);
278 const absl::Status ready = Ready();
279 if (!ready.ok()) {
280 return ready;
281 }
282 for (const std::vector<std::string>& words : commands) {
283 Append(context_, words);
284 }
285 std::vector<std::vector<std::string>> replies;
286 absl::Status error;
287 for (std::size_t i = 0; i < commands.size(); ++i) {
288 const absl::StatusOr<Reply> reply = NextReply();
289 if (!reply.ok()) {
290 return reply.status();
291 }
292 if ((*reply)->type == REDIS_REPLY_ERROR) {
293 error.Update(absl::InternalError(absl::StrCat("Redis: ", Text(**reply))));
294 // We read on after an error, or the replies left over would come back
295 // as the replies to the next commands.
296 continue;
297 }
298 std::vector<std::string>& values = replies.emplace_back();
299 if ((*reply)->type == REDIS_REPLY_ARRAY) {
300 for (std::size_t j = 0; j < (*reply)->elements; ++j) {
301 values.push_back(Text(*(*reply)->element[j]));
302 }
303 } else if ((*reply)->type != REDIS_REPLY_NIL) {
304 values.push_back(Text(**reply));
305 }
306 }
307 if (!error.ok()) {
308 return error;
309 }
310 return replies;
311}
312
314 const std::vector<std::vector<std::string>>& commands) {
315 const Span span = StartCall(commands);
316 const absl::Status ready = Ready();
317 if (!ready.ok()) {
318 return ready;
319 }
320 Append(context_, {"MULTI"});
321 for (const std::vector<std::string>& words : commands) {
322 Append(context_, words);
323 }
324 Append(context_, {"EXEC"});
325 // MULTI's OK, and each command's QUEUED, or an error for one Redis
326 // wouldn't queue, which makes EXEC run none of them.
327 absl::Status error;
328 for (std::size_t i = 0; i <= commands.size(); ++i) {
329 const absl::StatusOr<Reply> reply = NextReply();
330 if (!reply.ok()) {
331 return reply.status();
332 }
333 if ((*reply)->type == REDIS_REPLY_ERROR) {
334 error.Update(absl::InternalError(absl::StrCat("Redis: ", Text(**reply))));
335 }
336 }
337 const absl::StatusOr<Reply> exec = NextReply();
338 if (!exec.ok()) {
339 return exec.status();
340 }
341 if (!error.ok()) {
342 return error;
343 }
344 // EXEC's reply is a list of the commands' replies, once it's run them.
345 // Redis doesn't undo the others when one fails as it runs, say on a key
346 // that holds another type, so that's an error too.
347 if ((*exec)->type != REDIS_REPLY_ARRAY ||
348 (*exec)->elements != commands.size()) {
349 return absl::InternalError(
350 absl::StrCat("Redis didn't run the transaction: ", Text(**exec)));
351 }
352 for (std::size_t i = 0; i < (*exec)->elements; ++i) {
353 if ((*exec)->element[i]->type == REDIS_REPLY_ERROR) {
354 return absl::InternalError(
355 absl::StrCat("Redis: ", Text(*(*exec)->element[i])));
356 }
357 }
358 return absl::OkStatus();
359}
360
361absl::StatusOr<std::vector<std::string>> Redis::TransactionIf(
362 const std::map<std::string, std::string>& holding,
363 const std::vector<std::vector<std::string>>& commands) {
364 std::vector<std::string> eval = {"EVAL", kIf, absl::StrCat(holding.size())};
365 for (const auto& [key, value] : holding) {
366 eval.push_back(key);
367 }
368 for (const auto& [key, value] : holding) {
369 eval.push_back(value);
370 }
371 for (const std::vector<std::string>& words : commands) {
372 eval.push_back(absl::StrCat(words.size()));
373 eval.insert(eval.end(), words.begin(), words.end());
374 }
375 absl::StatusOr<std::vector<std::vector<std::string>>> wrong =
376 Pipeline({eval});
377 if (!wrong.ok()) {
378 return wrong.status();
379 }
380 return std::move(wrong->front());
381}
382
383} // namespace nanommo
absl::StatusOr< std::string > Command(const std::vector< std::string > &words)
Definition redis.cc:186
Redis(const Redis &)=delete
absl::StatusOr< std::vector< std::vector< std::string > > > Pipeline(const std::vector< std::vector< std::string > > &commands)
Definition redis.cc:275
absl::StatusOr< std::vector< std::string > > TransactionIf(const std::map< std::string, std::string > &holding, const std::vector< std::vector< std::string > > &commands)
Definition redis.cc:361
absl::Status Transaction(const std::vector< std::vector< std::string > > &commands)
Definition redis.cc:313
static absl::StatusOr< std::unique_ptr< Redis > > Create(const std::string &host, int port=6379, RedisTimeouts timeouts={})
Connects to Redis, or returns why it couldn't.
Definition redis.cc:121
absl::StatusOr< std::vector< Entry > > Read(const std::vector< std::string > &words)
Definition redis.cc:217
Definition chat.cc:9
bool InTrace()
Definition tracing.cc:402
Span StartChildSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:404
std::chrono::milliseconds fail_fast
Definition redis.h:25
std::chrono::milliseconds answer
For connecting, and then for each reply.
Definition redis.h:21
std::vector< std::string > fields
Definition redis.h:70
std::string id
Definition redis.h:69