xrpld
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#include <chrono>
8
9namespace xrpl {
10
14class TimeKeeper : public beast::AbstractClock<NetClock>
15{
16private:
18
19 // Adjust system_clock::time_point for NetClock epoch
20 static constexpr time_point
21 adjust(std::chrono::system_clock::time_point when)
22 {
23 return time_point(
24 std::chrono::duration_cast<duration>(when.time_since_epoch() - kEpochOffset));
25 }
26
27public:
28 ~TimeKeeper() override = default;
29
47 [[nodiscard]] time_point
48 now() const override
49 {
51 }
52
60 [[nodiscard]] time_point
61 closeTime() const
62 {
63 return now() + closeOffset_.load();
64 }
65
66 // This may return a negative value
67 [[nodiscard]] std::chrono::seconds
69 {
70 return closeOffset_.load();
71 }
72
78 {
79 using namespace std::chrono_literals;
80
81 auto offset = closeOffset_.load();
82
83 if (by == 0s && offset == 0s)
84 return offset;
85
86 // The close time adjustment is serialized externally to this
87 // code. The compare/exchange only serves as a weak check and
88 // should not fail. Even if it does, it's safe to simply just
89 // skip the adjustment.
90 closeOffset_.compare_exchange_strong(offset, [by, offset]() {
91 // Ignore small offsets and push the close time
92 // towards our wall time.
93 if (by > 1s)
94 return offset + ((by + 3s) / 4);
95
96 if (by < -1s)
97 return offset + ((by - 3s) / 4);
98
99 return (offset * 3) / 4;
100 }());
101
102 return closeOffset_.load();
103 }
104};
105
106} // namespace xrpl
Abstract interface to a clock.
NetClock::time_point time_point
Manages various times used by the server.
Definition TimeKeeper.h:15
static constexpr time_point adjust(std::chrono::system_clock::time_point when)
Definition TimeKeeper.h:21
time_point now() const override
Returns the current time, using the server's clock.
Definition TimeKeeper.h:48
std::chrono::seconds closeOffset() const
Definition TimeKeeper.h:68
time_point closeTime() const
Returns the predicted close time, in network time.
Definition TimeKeeper.h:61
std::atomic< std::chrono::seconds > closeOffset_
Definition TimeKeeper.h:17
~TimeKeeper() override=default
std::chrono::seconds adjustCloseTime(std::chrono::seconds by)
Adjust the close time, based on the network's view of time.
Definition TimeKeeper.h:77
T duration_cast(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 kEpochOffset
Clock for measuring the network time.
Definition chrono.h:35