rippled
Loading...
Searching...
No Matches
TimeKeeper.h
1#pragma once
2
3#include <xrpl/basics/chrono.h>
4#include <xrpl/beast/clock/abstract_clock.h>
5
6#include <atomic>
7
8namespace xrpl {
9
11class TimeKeeper : public beast::abstract_clock<NetClock>
12{
13private:
15
16 // Adjust system_clock::time_point for NetClock epoch
17 static constexpr time_point
18 adjust(std::chrono::system_clock::time_point when)
19 {
20 return time_point(std::chrono::duration_cast<duration>(when.time_since_epoch() - epoch_offset));
21 }
22
23public:
24 virtual ~TimeKeeper() = default;
25
42 [[nodiscard]] time_point
43 now() const override
44 {
46 }
47
54 [[nodiscard]] time_point
55 closeTime() const
56 {
57 return now() + closeOffset_.load();
58 }
59
60 // This may return a negative value
61 [[nodiscard]] std::chrono::seconds
63 {
64 return closeOffset_.load();
65 }
66
70 {
71 using namespace std::chrono_literals;
72
73 auto offset = closeOffset_.load();
74
75 if (by == 0s && offset == 0s)
76 return offset;
77
78 // The close time adjustment is serialized externally to this
79 // code. The compare/exchange only serves as a weak check and
80 // should not fail. Even if it does, it's safe to simply just
81 // skip the adjustment.
82 closeOffset_.compare_exchange_strong(offset, [by, offset]() {
83 // Ignore small offsets and push the close time
84 // towards our wall time.
85 if (by > 1s)
86 return offset + ((by + 3s) / 4);
87
88 if (by < -1s)
89 return offset + ((by - 3s) / 4);
90
91 return (offset * 3) / 4;
92 }());
93
94 return closeOffset_.load();
95 }
96};
97
98} // namespace xrpl
Abstract interface to a clock.
typename Clock::time_point time_point
Manages various times used by the server.
Definition TimeKeeper.h:12
static constexpr time_point adjust(std::chrono::system_clock::time_point when)
Definition TimeKeeper.h:18
time_point now() const override
Returns the current time, using the server's clock.
Definition TimeKeeper.h:43
std::chrono::seconds closeOffset() const
Definition TimeKeeper.h:62
time_point closeTime() const
Returns the predicted close time, in network time.
Definition TimeKeeper.h:55
std::atomic< std::chrono::seconds > closeOffset_
Definition TimeKeeper.h:14
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:69
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:5
static constexpr std::chrono::seconds epoch_offset
Clock for measuring the network time.
Definition chrono.h:32