forked from couchbaselabs/couchbase-cxx-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.hxx
390 lines (348 loc) · 12.6 KB
/
utils.hxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
* Copyright 2021-Present Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <couchbase/transactions/transaction_query_result.hxx>
#include <couchbase/transactions/transactions_config.hxx>
#include "core/transactions/result.hxx"
#include "exceptions_internal.hxx"
#include <chrono>
#include <cmath>
#include <functional>
#include <future>
#include <limits>
#include <random>
#include <string>
#include <thread>
#include <asio/steady_timer.hpp>
#include <utility>
namespace couchbase::core::transactions
{
// returns the parsed server time from the result of a lookup_in_spec::get(subdoc::lookup_in_macro::vbucket).xattr() call
std::uint64_t
now_ns_from_vbucket(const tao::json::value& vbucket);
std::string
jsonify(const tao::json::value& obj);
std::string
collection_spec_from_id(const core::document_id& id);
bool
document_ids_equal(const core::document_id& id1, const core::document_id& id2);
template<typename OStream>
OStream&
operator<<(OStream& os, const core::document_id& id)
{
os << "document_id{bucket: " << id.bucket() << ", scope: " << id.scope() << ", collection: " << id.collection() << ", key: " << id.key()
<< "}";
return os;
}
template<typename T>
T&
wrap_durable_request(T&& req, const couchbase::transactions::transactions_config::built& config)
{
req.durability_level = config.level;
return req;
}
template<typename T>
T&
wrap_durable_request(T&& req, durability_level level)
{
req.durability_level = level;
return req;
}
void
validate_operation_result(result& res, bool ignore_subdoc_errors = true);
result
wrap_operation_future(std::future<result>& fut, bool ignore_subdoc_errors = true);
inline void
wrap_collection_call(result& res, std::function<void(result&)> call);
template<typename Resp>
bool
is_error(const Resp& resp)
{
return !!resp.ctx.ec();
}
template<>
bool
is_error(const core::operations::mutate_in_response& resp);
template<typename Resp>
std::optional<error_class>
error_class_from_response_extras(const Resp&)
{
return {};
}
template<>
std::optional<error_class>
error_class_from_response_extras(const core::operations::mutate_in_response& resp);
template<typename Resp>
std::optional<error_class>
error_class_from_response(const Resp& resp)
{
if (!is_error(resp)) {
return {};
}
if (resp.ctx.ec() == couchbase::errc::key_value::document_not_found) {
return FAIL_DOC_NOT_FOUND;
}
if (resp.ctx.ec() == couchbase::errc::key_value::document_exists) {
return FAIL_DOC_ALREADY_EXISTS;
}
if (resp.ctx.ec() == couchbase::errc::common::cas_mismatch) {
return FAIL_CAS_MISMATCH;
}
if (resp.ctx.ec() == couchbase::errc::key_value::value_too_large) {
return FAIL_ATR_FULL;
}
if (resp.ctx.ec() == couchbase::errc::common::unambiguous_timeout || resp.ctx.ec() == couchbase::errc::common::temporary_failure ||
resp.ctx.ec() == couchbase::errc::key_value::durable_write_in_progress) {
return FAIL_TRANSIENT;
}
if (resp.ctx.ec() == couchbase::errc::key_value::durability_ambiguous || resp.ctx.ec() == couchbase::errc::common::ambiguous_timeout ||
resp.ctx.ec() == couchbase::errc::common::request_canceled) {
return FAIL_AMBIGUOUS;
}
if (resp.ctx.ec() == couchbase::errc::key_value::path_not_found) {
return FAIL_PATH_NOT_FOUND;
}
if (resp.ctx.ec() == couchbase::errc::key_value::path_exists) {
return FAIL_PATH_ALREADY_EXISTS;
}
if (resp.ctx.ec()) {
return FAIL_OTHER;
}
return error_class_from_response_extras(resp);
}
static constexpr std::chrono::milliseconds DEFAULT_RETRY_OP_DELAY{ 3 };
static constexpr std::chrono::milliseconds DEFAULT_RETRY_OP_EXP_DELAY{ 1 };
static constexpr std::chrono::milliseconds DEFAULT_RETRY_OP_MAX_EXP_DELAY{ 100 };
static constexpr std::size_t DEFAULT_RETRY_OP_MAX_RETRIES{ 100 };
static constexpr double RETRY_OP_JITTER{ 0.1 }; // means +/- 10% for jitter.
static constexpr std::size_t DEFAULT_RETRY_OP_EXPONENT_CAP{ 8 };
static inline double
jitter()
{
static std::mutex mtx;
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_real_distribution<> dist(1 - RETRY_OP_JITTER, 1 + RETRY_OP_JITTER);
std::lock_guard<std::mutex> lock(mtx);
return dist(gen);
}
template<typename R, typename R1, typename P1, typename R2, typename P2, typename R3, typename P3>
R
retry_op_exponential_backoff_timeout(std::chrono::duration<R1, P1> initial_delay,
std::chrono::duration<R2, P2> max_delay,
std::chrono::duration<R3, P3> timeout,
std::function<R()> func)
{
auto end_time = std::chrono::steady_clock::now() + timeout;
std::uint32_t retries = 0;
while (true) {
try {
return func();
} catch (const retry_operation&) {
auto now = std::chrono::steady_clock::now();
if (now > end_time) {
break;
}
auto delay = initial_delay * (jitter() * pow(2, retries++));
if (delay > max_delay) {
delay = max_delay;
}
if (now + delay > end_time) {
std::this_thread::sleep_for(end_time - now);
} else {
std::this_thread::sleep_for(delay);
}
}
}
throw retry_operation_timeout("timed out");
}
template<typename R, typename Rep, typename Period>
R
retry_op_exponential_backoff(std::chrono::duration<Rep, Period> delay, std::size_t max_retries, std::function<R()> func)
{
for (std::size_t retries = 0; retries <= max_retries; retries++) {
try {
return func();
} catch (const retry_operation&) {
// 2^7 = 128, so max delay fixed at 128 * delay
std::this_thread::sleep_for(delay * (jitter() * std::pow(2, std::fmin(DEFAULT_RETRY_OP_EXPONENT_CAP, retries))));
}
}
throw retry_operation_retries_exhausted("retry_op hit max retries!");
}
template<typename R>
R
retry_op_exp(std::function<R()> func)
{
return retry_op_exponential_backoff<R>(DEFAULT_RETRY_OP_EXP_DELAY, DEFAULT_RETRY_OP_MAX_RETRIES, func);
}
template<typename R, typename Rep, typename Period>
R
retry_op_constant_delay(std::chrono::duration<Rep, Period> delay, std::size_t max_retries, std::function<R()> func)
{
for (std::size_t retries = 0; retries <= max_retries; retries++) {
try {
return func();
} catch (const retry_operation&) {
std::this_thread::sleep_for(delay);
}
}
throw retry_operation_retries_exhausted("retry_op hit max retries!");
}
template<typename R>
R
retry_op(std::function<R()> func)
{
return retry_op_constant_delay<R>(DEFAULT_RETRY_OP_DELAY, std::numeric_limits<std::size_t>::max(), func);
}
struct exp_delay {
std::chrono::nanoseconds initial_delay;
std::chrono::nanoseconds max_delay;
std::chrono::nanoseconds timeout;
mutable std::uint32_t retries;
mutable std::optional<std::chrono::time_point<std::chrono::steady_clock>> end_time;
template<typename R1, typename P1, typename R2, typename P2, typename R3, typename P3>
exp_delay(std::chrono::duration<R1, P1> initial, std::chrono::duration<R2, P2> max, std::chrono::duration<R3, P3> limit)
: initial_delay(std::chrono::duration_cast<std::chrono::nanoseconds>(initial))
, max_delay(std::chrono::duration_cast<std::chrono::nanoseconds>(max))
, timeout(std::chrono::duration_cast<std::chrono::nanoseconds>(limit))
, retries(0)
, end_time()
{
}
void operator()() const
{
auto now = std::chrono::steady_clock::now();
if (!end_time) {
end_time = std::chrono::steady_clock::now() + timeout;
return;
}
if (now > *end_time) {
throw retry_operation_timeout("timed out");
}
auto delay = initial_delay * (jitter() * pow(2, retries++));
if (delay > max_delay) {
delay = max_delay;
}
if (now + delay > *end_time) {
std::this_thread::sleep_for(*end_time - now);
} else {
std::this_thread::sleep_for(delay);
}
}
};
template<typename R, typename P>
struct constant_delay {
std::chrono::duration<R, P> delay;
std::size_t max_retries;
std::size_t retries;
constant_delay(std::chrono::duration<R, P> d = DEFAULT_RETRY_OP_DELAY, std::size_t max = DEFAULT_RETRY_OP_MAX_RETRIES)
: delay(d)
, max_retries(max)
, retries(0)
{
}
void operator()()
{
if (retries++ >= max_retries) {
throw retry_operation_retries_exhausted("retries exhausted");
}
std::this_thread::sleep_for(delay);
}
};
struct async_exp_delay {
std::shared_ptr<asio::steady_timer> timer;
std::chrono::microseconds initial_delay;
std::chrono::microseconds max_delay;
std::size_t max_retries;
mutable std::size_t retries;
template<typename R1, typename P1, typename R2, typename P2>
async_exp_delay(std::shared_ptr<asio::steady_timer> timer,
std::chrono::duration<R1, P1> initial,
std::chrono::duration<R2, P2> max,
std::size_t max_retries)
: timer(std::move(timer))
, initial_delay(std::chrono::duration_cast<std::chrono::microseconds>(initial))
, max_delay(std::chrono::duration_cast<std::chrono::microseconds>(max))
, max_retries(max_retries)
, retries(0)
{
}
async_exp_delay(std::shared_ptr<asio::steady_timer> timer)
: async_exp_delay(std::move(timer), DEFAULT_RETRY_OP_EXP_DELAY, DEFAULT_RETRY_OP_MAX_EXP_DELAY, DEFAULT_RETRY_OP_MAX_RETRIES)
{
}
void operator()(utils::movable_function<void(std::exception_ptr)> callback) const
{
if (retries >= max_retries) {
callback(std::make_exception_ptr(retry_operation_retries_exhausted("retries exhausted")));
return;
}
auto delay =
std::chrono::duration_cast<std::chrono::microseconds>(initial_delay * (jitter() * pow(2, static_cast<double>(retries++))));
if (delay > max_delay) {
delay = max_delay;
}
timer->expires_after(delay);
timer->async_wait([callback = std::move(callback)](std::error_code ec) mutable {
if (ec == asio::error::operation_aborted) {
callback(std::make_exception_ptr(retry_operation_retries_exhausted("retry aborted")));
return;
}
callback({});
});
}
};
struct async_constant_delay {
std::shared_ptr<asio::steady_timer> timer;
std::chrono::microseconds delay;
std::size_t max_retries;
std::size_t retries;
template<typename R, typename P>
async_constant_delay(std::shared_ptr<asio::steady_timer> timer, std::chrono::duration<R, P> d, std::size_t max)
: timer(std::move(timer))
, delay(std::chrono::duration_cast<std::chrono::microseconds>(d))
, max_retries(max)
, retries(0)
{
}
explicit async_constant_delay(std::shared_ptr<asio::steady_timer> timer)
: async_constant_delay(std::move(timer), DEFAULT_RETRY_OP_DELAY, DEFAULT_RETRY_OP_MAX_RETRIES)
{
}
void operator()(utils::movable_function<void(std::exception_ptr)> callback)
{
if (retries++ >= max_retries) {
callback(std::make_exception_ptr(retry_operation_retries_exhausted("retries exhausted")));
return;
}
timer->expires_after(delay);
timer->async_wait([callback = std::move(callback)](std::error_code ec) mutable {
if (ec == asio::error::operation_aborted) {
callback(std::make_exception_ptr(retry_operation_retries_exhausted("retry aborted")));
return;
}
callback({});
});
}
};
std::list<std::string>
get_and_open_buckets(std::shared_ptr<core::cluster> c);
core::document_id
atr_id_from_bucket_and_key(const couchbase::transactions::transactions_config::built& cfg,
const std::string& bucket,
const std::string& key);
} // namespace couchbase::core::transactions