rippled
Loading...
Searching...
No Matches
TimeKeeper.h
1#ifndef XRPL_CORE_TIMEKEEPER_H_INCLUDED
2#define XRPL_CORE_TIMEKEEPER_H_INCLUDED
3
4#include <xrpl/basics/chrono.h>
5#include <xrpl/beast/clock/abstract_clock.h>
6
7#include <atomic>
8
9namespace ripple {
10
12class TimeKeeper : public beast::abstract_clock<NetClock>
13{
14private:
16
17 // Adjust system_clock::time_point for NetClock epoch
18 static constexpr time_point
19 adjust(std::chrono::system_clock::time_point when)
20 {
21 return time_point(std::chrono::duration_cast<duration>(
22 when.time_since_epoch() - epoch_offset));
23 }
24
25public:
26 virtual ~TimeKeeper() = default;
27
44 [[nodiscard]] time_point
45 now() const override
46 {
48 }
49
56 [[nodiscard]] time_point
57 closeTime() const
58 {
59 return now() + closeOffset_.load();
60 }
61
62 // This may return a negative value
63 [[nodiscard]] std::chrono::seconds
65 {
66 return closeOffset_.load();
67 }
68
72 {
73 using namespace std::chrono_literals;
74
75 auto offset = closeOffset_.load();
76
77 if (by == 0s && offset == 0s)
78 return offset;
79
80 // The close time adjustment is serialized externally to this
81 // code. The compare/exchange only serves as a weak check and
82 // should not fail. Even if it does, it's safe to simply just
83 // skip the adjustment.
84 closeOffset_.compare_exchange_strong(offset, [by, offset]() {
85 // Ignore small offsets and push the close time
86 // towards our wall time.
87 if (by > 1s)
88 return offset + ((by + 3s) / 4);
89
90 if (by < -1s)
91 return offset + ((by - 3s) / 4);
92
93 return (offset * 3) / 4;
94 }());
95
96 return closeOffset_.load();
97 }
98};
99
100} // namespace ripple
101
102#endif
Abstract interface to a clock.
typename Clock::time_point time_point
Manages various times used by the server.
Definition TimeKeeper.h:13
std::atomic< std::chrono::seconds > closeOffset_
Definition TimeKeeper.h:15
static constexpr time_point adjust(std::chrono::system_clock::time_point when)
Definition TimeKeeper.h:19
time_point now() const override
Returns the current time, using the server's clock.
Definition TimeKeeper.h:45
std::chrono::seconds closeOffset() const
Definition TimeKeeper.h:64
virtual ~TimeKeeper()=default
std::chrono::seconds adjustCloseTime(std::chrono::seconds by)
Adjust the close time, based on the network's view of time.
Definition TimeKeeper.h:71
time_point closeTime() const
Returns the predicted close time, in network time.
Definition TimeKeeper.h:57
T compare_exchange_strong(T... args)
T load(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:6
static constexpr std::chrono::seconds epoch_offset
Clock for measuring the network time.
Definition chrono.h:36