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"
36using Reply = std::unique_ptr<redisReply,
decltype(&freeReplyObject)>;
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)};
46std::optional<std::chrono::milliseconds> Blocks(
47 const std::vector<std::string>& words) {
48 const auto block = std::ranges::find(words,
"BLOCK");
50 if (block == words.end() || block + 1 == words.end() ||
51 !absl::SimpleAtoi(*(block + 1), &wait)) {
54 return std::chrono::milliseconds(wait);
60Span StartCall(std::span<
const std::vector<std::string>> commands) {
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]);
70 const std::string operation = absl::StrJoin(names,
" ");
73 span.SetAttribute(
"db.system",
"redis");
74 span.SetAttribute(
"db.operation", operation);
78void Append(redisContext* context,
const std::vector<std::string>& words) {
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());
86 redisAppendCommandArgv(context,
static_cast<int>(argv.size()), argv.data(),
90std::string Text(
const redisReply& reply) {
91 if (reply.type == REDIS_REPLY_INTEGER) {
92 return absl::StrCat(reply.integer);
94 return reply.str !=
nullptr ? std::string(reply.str, reply.len) :
"";
100constexpr char kIf[] = R
"lua(
102for i, key in ipairs(KEYS) do
103 if redis.call('GET', key) ~= ARGV[i] then
104 wrong[#wrong + 1] = key
112 local words = tonumber(ARGV[i])
113 redis.call(unpack(ARGV, i + 1, i + words))
121absl::StatusOr<std::unique_ptr<Redis>>
Redis::Create(
const std::string& host,
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");
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));
146void Redis::FailFast() {
147 failing_until_ = std::chrono::steady_clock::now() + timeouts_.
fail_fast;
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");
159 if (context_->err != 0 && redisReconnect(context_) != REDIS_OK) {
161 return absl::UnavailableError(
162 absl::StrCat(
"couldn't reconnect to Redis: ", context_->errstr));
164 return absl::OkStatus();
167absl::StatusOr<Reply> Redis::NextReply() {
168 void* reply =
nullptr;
169 if (redisGetReply(context_, &reply) != REDIS_OK) {
171 const bool timed_out = context_->err == REDIS_ERR_TIMEOUT ||
172 (context_->err == REDIS_ERR_IO &&
173 (errno == EAGAIN || errno == EWOULDBLOCK));
176 return absl::UnavailableError(absl::StrCat(
177 "Redis didn't answer within ",
178 absl::FormatDuration(absl::FromChrono(timeouts_.answer))));
180 return absl::UnavailableError(
181 absl::StrCat(
"lost the connection to Redis: ", context_->errstr));
183 return Reply(
static_cast<redisReply*
>(reply), freeReplyObject);
187 const std::vector<std::string>& words) {
188 const Span span = StartCall({&words, 1});
189 const absl::Status ready = Ready();
193 Append(context_, words);
194 const absl::StatusOr<Reply> reply_or = NextReply();
195 if (!reply_or.ok()) {
196 return reply_or.status();
198 const Reply& reply = *reply_or;
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)));
212 return absl::UnimplementedError(
213 "Redis replied with a type we don't read");
218 const std::vector<std::string>& words) {
219 const Span span = StartCall({&words, 1});
220 const absl::Status ready = Ready();
224 Append(context_, words);
228 const std::optional<std::chrono::milliseconds> blocks = Blocks(words);
230 const std::chrono::milliseconds wait =
231 blocks->count() == 0 ? *blocks : timeouts_.answer + *blocks;
232 redisSetTimeout(context_, TimevalOf(wait));
234 const absl::StatusOr<Reply> reply = NextReply();
238 redisSetTimeout(context_, TimevalOf(timeouts_.answer));
241 return reply.status();
243 if ((*reply)->type == REDIS_REPLY_ERROR) {
244 return absl::InternalError(absl::StrCat(
"Redis: ", Text(**reply)));
248 std::vector<Entry> entries;
249 if ((*reply)->type != REDIS_REPLY_ARRAY || (*reply)->elements == 0) {
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");
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) {
263 Entry& added = entries.emplace_back();
264 added.
id = Text(*entry.element[0]);
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]));
276 const std::vector<std::vector<std::string>>& commands) {
277 const Span span = StartCall(commands);
278 const absl::Status ready = Ready();
282 for (
const std::vector<std::string>& words : commands) {
283 Append(context_, words);
285 std::vector<std::vector<std::string>> replies;
287 for (std::size_t i = 0; i < commands.size(); ++i) {
288 const absl::StatusOr<Reply> reply = NextReply();
290 return reply.status();
292 if ((*reply)->type == REDIS_REPLY_ERROR) {
293 error.Update(absl::InternalError(absl::StrCat(
"Redis: ", Text(**reply))));
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]));
303 }
else if ((*reply)->type != REDIS_REPLY_NIL) {
304 values.push_back(Text(**reply));
314 const std::vector<std::vector<std::string>>& commands) {
315 const Span span = StartCall(commands);
316 const absl::Status ready = Ready();
320 Append(context_, {
"MULTI"});
321 for (
const std::vector<std::string>& words : commands) {
322 Append(context_, words);
324 Append(context_, {
"EXEC"});
328 for (std::size_t i = 0; i <= commands.size(); ++i) {
329 const absl::StatusOr<Reply> reply = NextReply();
331 return reply.status();
333 if ((*reply)->type == REDIS_REPLY_ERROR) {
334 error.Update(absl::InternalError(absl::StrCat(
"Redis: ", Text(**reply))));
337 const absl::StatusOr<Reply> exec = NextReply();
339 return exec.status();
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)));
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])));
358 return absl::OkStatus();
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) {
368 for (
const auto& [key, value] : holding) {
369 eval.push_back(value);
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());
375 absl::StatusOr<std::vector<std::vector<std::string>>> wrong =
378 return wrong.status();
380 return std::move(wrong->front());
absl::StatusOr< std::string > Command(const std::vector< std::string > &words)
Redis(const Redis &)=delete
absl::StatusOr< std::vector< std::vector< std::string > > > Pipeline(const std::vector< std::vector< std::string > > &commands)
absl::StatusOr< std::vector< std::string > > TransactionIf(const std::map< std::string, std::string > &holding, const std::vector< std::vector< std::string > > &commands)
absl::Status Transaction(const std::vector< std::vector< std::string > > &commands)
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.
absl::StatusOr< std::vector< Entry > > Read(const std::vector< std::string > &words)
Span StartChildSpan(std::string_view name, SpanKind kind)
std::chrono::milliseconds fail_fast
std::chrono::milliseconds answer
For connecting, and then for each reply.
std::vector< std::string > fields