yo_kv/clock.rs
1//! The coarse clock expiry compares against.
2//!
3//! `04` section 5 is explicit about this: there is no global clock read on the
4//! data path. The shard reads the clock once per turn of the loop and every
5//! command in that batch of 64 compares against the same number. A clock read
6//! is a vDSO call, so it is not a syscall, but it is still tens of nanoseconds
7//! against a budget of a hundred and fifty for the whole command, and paying it
8//! per command would mean paying it 64 times for one answer that did not change.
9//!
10//! `TIME` and `EXPIRETIME` read the fine clock instead, because their contract
11//! is to report the time and not to compare against it. That is what
12//! [`Clock::fine_now_ms`] is for and it is the only thing that should call it.
13//!
14//! A fixed clock is not a testing convenience bolted on the side. Expiry is the
15//! one part of a database whose behaviour is a function of the wall clock, and a
16//! test that sleeps to move time forward is a test that is slow and flaky at the
17//! same time. Every expiry test in this crate drives a fixed clock instead.
18
19use std::sync::Arc;
20use std::sync::atomic::AtomicU64;
21use std::sync::atomic::Ordering::Relaxed;
22use std::time::{SystemTime, UNIX_EPOCH};
23
24/// Where a clock takes its readings from.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26enum Source {
27 /// The operating system, read on every [`Clock::refresh`].
28 System,
29 /// Whatever the owner last set, and nothing else.
30 Fixed,
31}
32
33/// A millisecond clock that only moves when it is told to.
34///
35/// A handle and not a value. Cloning one gives a second handle onto the same
36/// reading, which is what lets every stripe of every database on a server read
37/// the time a command is being judged against without any of them being told
38/// separately. Moving the clock is one store however many stripes there are.
39///
40/// # Why a shared reading is not a shared line
41///
42/// It is read on every command on every thread, so the obvious worry is a line
43/// that bounces between cores. It does not, because a refresh only writes when
44/// the millisecond has actually changed and a turn of the loop is a few
45/// microseconds. The reading changes about a thousand times a second and is
46/// read millions of times, so the line sits in every core's cache in the shared
47/// state and the writer disturbs it about as often as a timer would.
48#[derive(Debug, Clone)]
49pub struct Clock {
50 now_ms: Arc<AtomicU64>,
51 source: Source,
52}
53
54impl Clock {
55 /// A clock that follows the system, read once now.
56 pub fn system() -> Clock {
57 Clock::at(Clock::fine_now_ms(), Source::System)
58 }
59
60 /// A clock that reads `ms` until somebody moves it.
61 pub fn fixed(ms: u64) -> Clock {
62 Clock::at(ms, Source::Fixed)
63 }
64
65 /// A clock reading `ms` from `source`.
66 fn at(ms: u64, source: Source) -> Clock {
67 Clock {
68 now_ms: Arc::new(AtomicU64::new(ms)),
69 source,
70 }
71 }
72
73 /// The current reading, in milliseconds since the unix epoch.
74 #[inline]
75 pub fn now_ms(&self) -> u64 {
76 self.now_ms.load(Relaxed)
77 }
78
79 /// Take a new reading, which a system clock does from the operating system
80 /// and a fixed clock does not do at all.
81 ///
82 /// Called once per turn of the shard loop, from the maintenance slice. The
83 /// store only happens when the millisecond has changed, which is what keeps
84 /// a reading every thread is looking at from being a line every thread is
85 /// fighting over.
86 ///
87 /// Shared and not exclusive, because on a server running more than one
88 /// thread every one of them turns a loop and every one of them refreshes.
89 /// Two threads that read the operating system a nanosecond apart write the
90 /// same millisecond, and a thread that reads the field between the two
91 /// stores gets that millisecond either way.
92 #[inline]
93 pub fn refresh(&self) {
94 if self.source == Source::System {
95 let ms = Clock::fine_now_ms();
96 if self.now_ms() != ms {
97 self.now_ms.store(ms, Relaxed);
98 }
99 }
100 }
101
102 /// Move the clock to `ms` by hand.
103 ///
104 /// On a system clock the next [`Clock::refresh`] will overwrite this, so it
105 /// is only meaningful on a fixed one.
106 #[inline]
107 pub fn set(&self, ms: u64) {
108 self.now_ms.store(ms, Relaxed);
109 }
110
111 /// Move a clock forward by `ms`.
112 ///
113 /// A read and a store and not an add, because it saturates. Nothing moves a
114 /// clock this way but a test, which is one thread.
115 #[inline]
116 pub fn advance(&self, ms: u64) {
117 self.set(self.now_ms().saturating_add(ms));
118 }
119
120 /// Read the operating system's clock right now.
121 ///
122 /// A time before the unix epoch reads as zero rather than failing. There is
123 /// nothing useful a database can do about a machine whose clock says 1969,
124 /// and every key expiring immediately is a more honest outcome than a panic
125 /// on a path that has no error to return.
126 #[inline]
127 pub fn fine_now_ms() -> u64 {
128 SystemTime::now()
129 .duration_since(UNIX_EPOCH)
130 .map_or(0, |d| d.as_millis() as u64)
131 }
132}
133
134impl Default for Clock {
135 fn default() -> Clock {
136 Clock::system()
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn a_fixed_clock_stays_where_it_is_put() {
146 let c = Clock::fixed(1_000);
147 assert_eq!(c.now_ms(), 1_000);
148 c.refresh();
149 assert_eq!(c.now_ms(), 1_000, "refresh moved a fixed clock");
150 c.advance(500);
151 assert_eq!(c.now_ms(), 1_500);
152 c.set(7);
153 assert_eq!(c.now_ms(), 7);
154 }
155
156 #[test]
157 fn a_system_clock_reads_a_plausible_time() {
158 let c = Clock::system();
159 // 2020-01-01, which this build is comfortably after.
160 assert!(c.now_ms() > 1_577_836_800_000, "clock read {}", c.now_ms());
161 }
162
163 #[test]
164 fn a_system_clock_does_not_move_until_it_is_refreshed() {
165 let c = Clock::system();
166 let first = c.now_ms();
167 // Busy work rather than a sleep, because the point is that the reading
168 // is stable across it and a sleep would only make the test slow.
169 let mut spin = 0u64;
170 for i in 0..200_000u64 {
171 spin = spin.wrapping_add(i);
172 }
173 assert_eq!(c.now_ms(), first, "the clock moved on its own {spin}");
174 c.refresh();
175 assert!(c.now_ms() >= first);
176 }
177
178 /// Two handles onto one clock are one clock, which is what lets a database
179 /// hand the same reading to every stripe it was cut into.
180 #[test]
181 fn a_cloned_clock_reads_what_the_original_was_moved_to() {
182 let one = Clock::fixed(1_000);
183 let two = one.clone();
184 one.advance(500);
185 assert_eq!(two.now_ms(), 1_500);
186 two.set(9);
187 assert_eq!(one.now_ms(), 9);
188 }
189
190 #[test]
191 fn advancing_past_the_end_of_time_stops_there() {
192 let c = Clock::fixed(u64::MAX - 1);
193 c.advance(10);
194 assert_eq!(c.now_ms(), u64::MAX);
195 }
196}