/Users/deen/code/yugabyte-db/ent/src/yb/server/random_error_clock.cc
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) YugaByte, Inc. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
4 | | // in compliance with the License. You may obtain a copy of the License at |
5 | | // |
6 | | // http://www.apache.org/licenses/LICENSE-2.0 |
7 | | // |
8 | | // Unless required by applicable law or agreed to in writing, software distributed under the License |
9 | | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
10 | | // or implied. See the License for the specific language governing permissions and limitations |
11 | | // under the License. |
12 | | // |
13 | | |
14 | | #include "yb/server/random_error_clock.h" |
15 | | |
16 | | #include "yb/server/hybrid_clock.h" |
17 | | |
18 | | #include "yb/util/ntp_clock.h" |
19 | | #include "yb/util/random_util.h" |
20 | | #include "yb/util/result.h" |
21 | | |
22 | | using namespace std::literals; |
23 | | |
24 | | namespace yb { |
25 | | namespace server { |
26 | | |
27 | | const std::string RandomErrorClock::kName = "random_error"; |
28 | | const std::string RandomErrorClock::kNtpName = "ntp_random_error"; |
29 | | |
30 | | namespace { |
31 | | |
32 | | constexpr int64_t kMaxError = |
33 | | std::chrono::duration_cast<std::chrono::microseconds>(100ms).count(); |
34 | | |
35 | | } |
36 | | |
37 | 0 | RandomErrorClock::RandomErrorClock(PhysicalClockPtr clock) : impl_(std::move(clock)) {} |
38 | | |
39 | 0 | void RandomErrorClock::Register() { |
40 | 0 | HybridClock::RegisterProvider(kName, [](const std::string& options) { |
41 | 0 | return std::make_shared<RandomErrorClock>(WallClock()); |
42 | 0 | }); |
43 | 0 | HybridClock::RegisterProvider(kNtpName, [](const std::string& options) { |
44 | 0 | return CreateNtpClock(); |
45 | 0 | }); |
46 | 0 | } |
47 | | |
48 | 0 | Result<PhysicalTime> RandomErrorClock::Now() { |
49 | 0 | auto result = VERIFY_RESULT(impl_->Now()); |
50 | 0 | auto error = RandomUniformInt(-kMaxError, kMaxError); |
51 | | // Return an interval that includes the "real time" returned by the underlying clock. |
52 | 0 | return PhysicalTime{result.time_point + error, static_cast<MicrosTime>(std::abs(error))}; |
53 | 0 | } |
54 | | |
55 | 0 | MicrosTime RandomErrorClock::MaxGlobalTime(PhysicalTime time) { |
56 | 0 | return time.time_point + time.max_error + kMaxError; |
57 | 0 | } |
58 | | |
59 | 0 | PhysicalClockPtr RandomErrorClock::CreateNtpClock() { |
60 | 0 | return std::make_shared<NtpClock>(std::make_shared<RandomErrorClock>(WallClock())); |
61 | 0 | } |
62 | | |
63 | | } // namespace server |
64 | | } // namespace yb |