userver: userver/storages/redis/command_options.hpp Source File
Loading...
Searching...
No Matches
command_options.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file
4/// @brief Definitions of structures representing options for different commands
5
6#include <optional>
7#include <string>
8#include <vector>
9
10#include <userver/formats/json/value.hpp>
11#include <userver/storages/redis/base.hpp>
12#include <userver/storages/redis/command_control.hpp>
13#include <userver/storages/redis/exception.hpp>
14#include <userver/storages/redis/scan_tag.hpp>
15#include <userver/utils/span.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace storages::redis {
20
21using Longitude = utils::StrongTypedef<struct LongitudeTag, double>;
22using Latitude = utils::StrongTypedef<struct LatitudeTag, double>;
23using BoxWidth = utils::StrongTypedef<struct BoxWidthTag, double>;
24using BoxHeight = utils::StrongTypedef<struct BoxHeightTag, double>;
25
26/// A key condition for optimistic transaction execution with Valkey 9.2 or newer.
28public:
29 /// The comparison performed before executing the queued commands.
30 enum class Type {
31 /// The key contains a string equal to the expected value.
33 /// The key is absent or contains a string different from the expected value.
35 /// The key does not exist.
37 /// The key exists, regardless of its value type.
39 };
40
41 /// Creates a string equality condition; see @ref Type::kIfEq.
42 static ExecCondition IfEq(std::string key, std::string value);
43 /// Creates a string inequality condition; see @ref Type::kIfNe.
44 static ExecCondition IfNe(std::string key, std::string value);
45 /// Creates a key absence condition; see @ref Type::kNx.
46 static ExecCondition Nx(std::string key);
47 /// Creates a key existence condition; see @ref Type::kXx.
48 static ExecCondition Xx(std::string key);
49
50 /// Returns the comparison to perform.
51 Type GetType() const { return type_; }
52 /// Returns the key to check.
53 const std::string& GetKey() const { return key_; }
54 /// Returns the comparison value for IfEq and IfNe, or an empty string for Nx and Xx.
55 const std::string& GetValue() const { return value_; }
56
57private:
58 ExecCondition(Type type, std::string key, std::string value);
59
60 Type type_;
61 std::string key_;
62 std::string value_;
63};
64
65/// Conditions for @ref Transaction::Exec. All conditions must match to execute the transaction.
66/// The conditions are consumed during @ref Transaction::Exec and are not retained by the returned request.
67/// The referenced conditions must stay alive until @ref Transaction::Exec returns.
68/// A temporary initializer list may be passed directly to Exec, but must not be used to initialize a stored
69/// ExecOptions.
71
73 std::optional<size_t> offset;
74 std::optional<size_t> count;
75};
76
77struct GeoaddArg {
78 double lon;
79 double lat;
80 std::string member;
81};
82
84 enum class Sort { kNone, kAsc, kDesc };
85 enum class Unit { kM, kKm, kMi, kFt };
86
87 Unit unit = Unit::kM;
88 bool withcoord = false;
89 bool withdist = false;
90 bool withhash = false;
91 size_t count = 0;
92 Sort sort = Sort::kNone;
93};
94
96 enum class Sort { kNone, kAsc, kDesc };
97 enum class Unit { kM, kKm, kMi, kFt };
98
99 Unit unit = Unit::kM;
100 bool withcoord = false;
101 bool withdist = false;
102 bool withhash = false;
103 size_t count = 0;
104 Sort sort = Sort::kNone;
105};
106
108 enum class Exist { kAddAlways, kAddIfNotExist, kAddIfExist };
109 enum class Compare { kNone, kGreaterThan, kLessThan };
110 enum class ReturnValue { kAddedCount, kChangedCount };
111
112 ZaddOptions() = default;
113 constexpr ZaddOptions(
114 Exist exist,
115 ReturnValue return_value = ReturnValue::kAddedCount,
116 Compare compare = Compare::kNone
117 )
118 : exist(exist),
119 compare(compare),
120 return_value(return_value)
121 {}
122 constexpr ZaddOptions(Exist exist, Compare compare, ReturnValue return_value = ReturnValue::kAddedCount)
123 : exist(exist),
124 compare(compare),
125 return_value(return_value)
126 {}
127
128 constexpr ZaddOptions(ReturnValue return_value, Exist exist = Exist::kAddAlways, Compare compare = Compare::kNone)
129 : exist(exist),
130 compare(compare),
131 return_value(return_value)
132 {}
133 constexpr ZaddOptions(ReturnValue return_value, Compare compare, Exist exist = Exist::kAddAlways)
134 : exist(exist),
135 compare(compare),
136 return_value(return_value)
137 {}
138
139 constexpr ZaddOptions(
140 Compare compare,
141 Exist exist = Exist::kAddAlways,
142 ReturnValue return_value = ReturnValue::kAddedCount
143 )
144 : exist(exist),
145 compare(compare),
146 return_value(return_value)
147 {}
148 constexpr ZaddOptions(Compare compare, ReturnValue return_value, Exist exist = Exist::kAddAlways)
149 : exist(exist),
150 compare(compare),
151 return_value(return_value)
152 {}
153
154 Exist exist = Exist::kAddAlways;
155 Compare compare = Compare::kNone;
156 ReturnValue return_value = ReturnValue::kAddedCount;
157};
158
159constexpr ZaddOptions operator|(ZaddOptions::Exist exist, ZaddOptions::ReturnValue return_value) {
160 return {exist, return_value};
161}
162constexpr ZaddOptions operator|(ZaddOptions::Exist exist, ZaddOptions::Compare compare) { return {exist, compare}; }
163constexpr ZaddOptions operator|(ZaddOptions::Compare compare, ZaddOptions::Exist exist) { return {compare, exist}; }
164constexpr ZaddOptions operator|(ZaddOptions::Compare compare, ZaddOptions::ReturnValue return_value) {
165 return {compare, return_value};
166}
167constexpr ZaddOptions operator|(ZaddOptions::ReturnValue return_value, ZaddOptions::Exist exist) {
168 return {return_value, exist};
169}
170constexpr ZaddOptions operator|(ZaddOptions::ReturnValue return_value, ZaddOptions::Compare compare) {
171 return {return_value, compare};
172}
173
174/// @brief A command option to use in Scan, Hscan, Scan and Zscan commands.
175///
176/// Sample usage:
177/// @snippet redis/src/storages/redis/client_scan_redistest.cpp Sample Scan usage
178class Match final {
179public:
180 explicit Match(std::string value)
181 : value_(std::move(value))
182 {}
183
184 const std::string& Get() const& { return value_; }
185
186 std::string Get() && { return std::move(value_); }
187
188private:
189 std::string value_;
190};
191
192/// @brief A hint for Scan, Hscan, Scan and Zscan commands.
193class Count final {
194public:
195 constexpr explicit Count(std::size_t value) noexcept : value_(value) {}
196
197 constexpr std::size_t Get() const noexcept { return value_; }
198
199private:
200 std::size_t value_;
201};
202
203/// @brief A command option to use in Scan, Hscan, Scan and Zscan commands that combines Match and Count options.
205public:
206 using Match = storages::redis::Match;
207 using Count = storages::redis::Count;
208
209 ScanOptionsGeneric() = default;
210
211 ScanOptionsGeneric(const ScanOptionsGeneric& other) = default;
212 ScanOptionsGeneric& operator=(const ScanOptionsGeneric& other) = default;
213
214 ScanOptionsGeneric(ScanOptionsGeneric&& other) = default;
215 ScanOptionsGeneric& operator=(ScanOptionsGeneric&& other) = default;
216
217 template <typename... Args>
218 ScanOptionsGeneric(Args... args) {
219 (Apply(std::move(args)), ...);
220 }
221
222 const std::optional<Match>& GetMatchOptional() const noexcept { return pattern_; }
223
224 const std::optional<Count>& GetCountOptional() const noexcept { return count_; }
225
226 std::optional<Match> ExtractMatch() noexcept { return std::move(pattern_); }
227
228 std::optional<Count> ExtractCount() noexcept { return std::move(count_); }
229
230private:
231 void Apply(Match pattern) {
232 if (pattern_) {
233 throw InvalidArgumentException("duplicate Match parameter");
234 }
235 pattern_ = std::move(pattern);
236 }
237
238 void Apply(Count count) {
239 if (count_) {
240 throw InvalidArgumentException("duplicate Count parameter");
241 }
242 count_ = count;
243 }
244
245 std::optional<Match> pattern_;
246 std::optional<Count> count_;
247};
248
249template <ScanTag TScanTag>
250using ScanOptionsTmpl [[deprecated("Just use ScanOptionsGeneric")]] = ScanOptionsGeneric;
251
252using ScanOptions = ScanOptionsGeneric;
253using SscanOptions = ScanOptionsGeneric;
254using HscanOptions = ScanOptionsGeneric;
255using ZscanOptions = ScanOptionsGeneric;
256
258 enum class Exist { kSetAlways, kSetIfNotExist, kSetIfExist };
259
260 int seconds = 0;
261 int milliseconds = 0;
262 Exist exist = Exist::kSetAlways;
263};
264
265/// @brief Options for MSETEX (NX/XX combined with EX/PX/EXAT/PXAT/KEEPTTL).
267 /// Existence precondition for the affected keys.
268 enum class Exist : std::uint8_t {
269 /// No precondition (default).
271 /// NX — set only if none of the affected keys currently exists.
273 /// XX — set only if all of the affected keys currently exist.
275 };
276 /// What TTL clause to attach to the new values.
277 enum class TtlAction : std::uint8_t {
278 /// No TTL clause on the wire — server applies default behavior.
280 /// EX seconds.
282 /// PX milliseconds.
284 /// EXAT unix-ts-sec.
286 /// PXAT unix-ts-ms.
288 /// KEEPTTL — keep the existing TTL of each key if any; @c ttl is ignored.
290 };
291
293 TtlAction ttl_action{TtlAction::kNone};
294 std::chrono::milliseconds ttl{0};
295
296 /// @brief No TTL clause on the wire — server applies default behavior.
298 /// @brief KEEPTTL — keep the existing TTL of each key if any.
300 /// @brief Set TTL to a relative duration. Posted on the wire as PX (ms-precision).
301 static MsetexOptions Expire(std::chrono::milliseconds ttl);
302 /// @brief Set TTL to an absolute deadline. Posted on the wire as PXAT (ms-precision).
303 static MsetexOptions ExpireAt(std::chrono::system_clock::time_point deadline);
304
305 /// @brief Chainable modifier — NX: write only if **none** of the affected
306 /// keys currently exist.
309 return *this;
310 }
311 /// @brief Chainable modifier — XX: write only if **all** of the affected
312 /// keys currently exist.
314 exist = Exist::kSetIfAllExist;
315 return *this;
316 }
317 /// @brief NX (rvalue overload).
320 return std::move(*this);
321 }
322 /// @brief XX (rvalue overload).
324 exist = Exist::kSetIfAllExist;
325 return std::move(*this);
326 }
327};
328
330 enum class Exist { kSetAlways, kSetIfNotExist, kSetIfExist };
331 enum class Compare { kNone, kGreaterThan, kLessThan };
332
333 ExpireOptions() = default;
334 constexpr ExpireOptions(Exist exist, Compare compare = Compare::kNone)
335 : exist(exist),
336 compare(compare)
337 {
338 if (exist == Exist::kSetIfNotExist && compare != Compare::kNone) {
339 // @see https://redis-docs.ru/commands/expire/
340 throw std::invalid_argument("When exist is kSetIfNotExist, compare must be kNone");
341 }
342 }
343
344 constexpr ExpireOptions(Compare compare, Exist exist = Exist::kSetAlways)
345 : exist(exist),
346 compare(compare)
347 {
348 if (exist == Exist::kSetIfNotExist && compare != Compare::kNone) {
349 // @see https://redis-docs.ru/commands/expire/
350 throw std::invalid_argument("When exist is kSetIfNotExist, compare must be kNone");
351 }
352 }
353
354 Exist exist = Exist::kSetAlways;
355 Compare compare = Compare::kNone;
356};
357
359 bool withscores = false;
360};
361
363 ScoreOptions score_options;
364 RangeOptions range_options;
365};
366
367/// @brief Data type for JSON.MSET command arguments (key + path + JSON value triplet).
368struct JsonKeyPathValue final {
369 std::string key;
370 std::string path;
371 formats::json::Value value;
372};
373
374/// @brief Options for HGETEX command — at most one TTL action per call.
376 /// What to do with the TTL of each fetched field.
377 enum class TtlAction : std::uint8_t {
378 /// Leave the TTL unchanged (no modifier on the wire).
380 /// EX seconds — set TTL to a duration; @c ttl is interpreted as whole seconds.
382 /// PX milliseconds — set TTL to a duration; @c ttl is used as-is in milliseconds.
384 /// EXAT unix-ts-sec — set absolute expiration; @c ttl is interpreted as whole seconds since epoch.
386 /// PXAT unix-ts-ms — set absolute expiration; @c ttl is used as-is in milliseconds since epoch.
388 /// PERSIST — remove TTL from the fields; @c ttl is ignored.
390 };
391
392 TtlAction ttl_action{TtlAction::kKeep};
393 std::chrono::milliseconds ttl{0};
394
395 /// @brief Do not touch the TTL of the read fields (no modifier on the wire).
397 /// @brief Remove TTL on all read fields (PERSIST modifier).
399 /// @brief Set TTL to a relative duration. Posted on the wire as PX (ms-precision).
400 static HgetexOptions Expire(std::chrono::milliseconds ttl);
401 /// @brief Set TTL to an absolute deadline. Posted on the wire as PXAT (ms-precision).
402 static HgetexOptions ExpireAt(std::chrono::system_clock::time_point deadline);
403};
404
405/// @brief Single field/value entry for HSETEX.
407 std::string field;
408 std::string value;
409};
410
411/// @brief Options for HSETEX (FNX/FXX combined with EX/PX/EXAT/PXAT/KEEPTTL).
413 /// Existence precondition for the affected fields.
414 enum class Exist : std::uint8_t {
415 /// No precondition (default).
417 /// FNX — set only if none of the affected fields currently exists.
419 /// FXX — set only if all of the affected fields currently exist.
421 };
422 /// What TTL clause to attach to the new values.
423 enum class TtlAction : std::uint8_t {
424 /// No TTL clause on the wire — server applies default behavior.
426 /// EX seconds.
428 /// PX milliseconds.
430 /// EXAT unix-ts-sec.
432 /// PXAT unix-ts-ms.
434 /// KEEPTTL — keep the existing TTL of each field if any; @c ttl is ignored.
436 };
437
439 TtlAction ttl_action{TtlAction::kNone};
440 std::chrono::milliseconds ttl{0};
441
442 /// @brief No TTL clause on the wire — server applies default behavior.
444 /// @brief KEEPTTL — keep the existing TTL of each field if any.
446 /// @brief Set TTL to a relative duration. Posted on the wire as PX (ms-precision).
447 static HsetexOptions Expire(std::chrono::milliseconds ttl);
448 /// @brief Set TTL to an absolute deadline. Posted on the wire as PXAT (ms-precision).
449 static HsetexOptions ExpireAt(std::chrono::system_clock::time_point deadline);
450
451 /// @brief Chainable modifier — FNX: write only if **none** of the affected
452 /// fields currently exist.
455 return *this;
456 }
457 /// @brief Chainable modifier — FXX: write only if **all** of the affected
458 /// fields currently exist.
460 exist = Exist::kSetIfAllExist;
461 return *this;
462 }
463 /// @brief FNX (rvalue overload).
466 return std::move(*this);
467 }
468 /// @brief FXX (rvalue overload).
470 exist = Exist::kSetIfAllExist;
471 return std::move(*this);
472 }
473};
474
475} // namespace storages::redis
476
477USERVER_NAMESPACE_END