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(
21 std::chrono::duration_cast<duration>(when.time_since_epoch() - epoch_offset));
22 }
23
24public:
25 virtual ~TimeKeeper() = default;
26
43 [[nodiscard]] time_point
44 now() const override
45 {
47 }
48
55 [[nodiscard]] time_point
56 closeTime() const
57 {
58 return now() + closeOffset_.load();
59 }
60
61 // This may return a negative value
62 [[nodiscard]] std::chrono::seconds
64 {
65 return closeOffset_.load();
66 }
67
71 {
72 using namespace std::chrono_literals;
73
74 auto offset = closeOffset_.load();
75
76 if (by == 0s && offset == 0s)
77 return offset;
78
79 // The close time adjustment is serialized externally to this
80 // code. The compare/exchange only serves as a weak check and
81 // should not fail. Even if it does, it's safe to simply just
82 // skip the adjustment.
83 closeOffset_.compare_exchange_strong(offset, [by, offset]() {
84 // Ignore small offsets and push the close time
85 // towards our wall time.
86 if (by > 1s)
87 return offset + ((by + 3s) / 4);
88
89 if (by < -1s)
90 return offset + ((by - 3s) / 4);
91
92 return (offset * 3) / 4;
93 }());
94
95 return closeOffset_.load();
96 }
97};
98
99} // 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:44
std::chrono::seconds closeOffset() const
Definition TimeKeeper.h:63
time_point closeTime() const
Returns the predicted close time, in network time.
Definition TimeKeeper.h:56
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:70
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:33