Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_core/src/time/mod.rs

12.6 KiB, 1 run

created by r1870400018:74437, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1pub mod hlc;
2
3use crate::{
4 prelude::*,
5};
6
7use std::{
8 sync::OnceLock,
9 time::Duration,
10};
11#[cfg(not(target_arch = "wasm32"))]
12use std::{
13 path::PathBuf,
14 sync::atomic::{
15 AtomicU64,
16 Ordering,
17 },
18 time::{
19 Instant,
20 SystemTime,
21 UNIX_EPOCH,
22 },
23 thread,
24};
25
26/// Waits for the given boolean function to become true, or for the maximum duration to be reached.
27/// Returns the starting `Instant` and whether the operation timed out. Returns an error if the
28/// given `Duration`s are inconsistent.
29#[cfg(not(target_arch = "wasm32"))]
30pub fn wait_for_true(
31 check_interval: Duration,
32 max_wait: Duration,
33 fn_true: impl Fn() -> bool,
34)
35 -> Outcome<(Instant, bool)>
36{
37 if check_interval > max_wait {
38 return Err(err!(
39 "The given check interval, {:?}, should not be larger than the \
40 given max wait, {:?}.", check_interval, max_wait;
41 Invalid, Input));
42 }
43 let start = Instant::now();
44 loop {
45 if fn_true() {
46 return Ok((start, false));
47 } else {
48 thread::sleep(check_interval);
49 }
50 if start.elapsed() > max_wait {
51 return Ok((start, true));
52 }
53 }
54}
55
56#[cfg(target_arch = "wasm32")]
57pub fn wait_for_true(
58 _check_interval: Duration,
59 _max_wait: Duration,
60 _fn_true: impl Fn() -> bool,
61)
62 -> Outcome<(std::time::Instant, bool)>
63{
64 Err(err!(
65 "wait_for_true blocks the calling thread and is unavailable on the \
66 wasm32 target; use an asynchronous wait instead.";
67 Unimplemented))
68}
69
70/// A simple system clock stopwatch.
71#[derive(Debug, PartialEq, Copy, Clone)]
72pub struct Timer {
73 #[cfg(not(target_arch = "wasm32"))]
74 t0: Instant,
75 #[cfg(target_arch = "wasm32")]
76 t0: f64,
77 last: usize,
78}
79
80impl Timer {
81 #[cfg(not(target_arch = "wasm32"))]
82 pub fn new() -> Self {
83 Self {
84 t0: Instant::now(),
85 last: 0,
86 }
87 }
88
89 #[cfg(target_arch = "wasm32")]
90 pub fn new() -> Self {
91 Self {
92 t0: crate::wasm::now_ms(),
93 last: 0,
94 }
95 }
96
97 #[cfg(not(target_arch = "wasm32"))]
98 pub fn reset(&mut self) {
99 self.t0 = Instant::now();
100 self.last = 0;
101 }
102
103 #[cfg(target_arch = "wasm32")]
104 pub fn reset(&mut self) {
105 self.t0 = crate::wasm::now_ms();
106 self.last = 0;
107 }
108
109 #[cfg(not(target_arch = "wasm32"))]
110 pub fn split_micros(&mut self) -> Outcome<usize> {
111 self.last = try_sub!(self.t0.elapsed().as_micros() as usize, self.last);
112 Ok(self.last)
113 }
114
115 #[cfg(target_arch = "wasm32")]
116 pub fn split_micros(&mut self) -> Outcome<usize> {
117 let elapsed = ((crate::wasm::now_ms() - self.t0) * 1_000.0) as usize;
118 self.last = try_sub!(elapsed, self.last);
119 Ok(self.last)
120 }
121}
122
123/// Where a process reads the wall clock from.
124///
125/// `System` is the operating system clock. `Driven` reads the time from a
126/// file holding exactly eight bytes, a little-endian `u64` count of
127/// milliseconds since the Unix epoch, so that a test rig can move a process's
128/// clock by rewriting one file. The writer must replace the file by rename,
129/// so a reader never sees a half-written value.
130///
131/// The methods take `&self`, so a caller can hold its own source; [`clock`] is
132/// only the process default, set at most once by [`install`].
133#[derive(Debug)]
134pub enum ClockSource {
135 System,
136 #[cfg(not(target_arch = "wasm32"))]
137 Driven(Driven),
138}
139
140/// A clock read from a file, see [`ClockSource`].
141#[cfg(not(target_arch = "wasm32"))]
142#[derive(Debug)]
143pub struct Driven {
144 path: PathBuf,
145 last: AtomicU64, // Highest millisecond value returned
146 last_ns: AtomicU64, // Last now_nanos value returned, u64 until 2554
147}
148
149#[cfg(not(target_arch = "wasm32"))]
150impl Driven {
151 pub fn new<P: Into<PathBuf>>(path: P) -> Self {
152 Self {
153 path: path.into(),
154 last: AtomicU64::new(0),
155 last_ns: AtomicU64::new(0),
156 }
157 }
158
159 pub fn path(&self) -> &std::path::Path {
160 &self.path
161 }
162
163 // Test hook: n calls' worth of ties already handed out in this millisecond.
164 #[cfg(test)]
165 fn preset_ties(&self, ms: u64, n: u64) {
166 self.last_ns.store(ms * 1_000_000 + n, Ordering::SeqCst);
167 }
168
169 /// The file's milliseconds in nanoseconds, or one more than the last value
170 /// handed out if that is higher. A compare-and-swap loop rather than a
171 /// counter, so no value repeats or steps back across threads however long
172 /// the file is held still.
173 fn next_nanos(&self) -> Outcome<u64> {
174 let ms = res!(self.read_millis());
175 let cand = match ms.checked_mul(1_000_000) {
176 Some(n) => n,
177 None => return Err(err!(
178 "Driven clock file {:?} holds {} ms, beyond the u64 nanosecond \
179 range (the year 2554).", self.path, ms;
180 Invalid, Input, Overflow)),
181 };
182 let mut prev = self.last_ns.load(Ordering::SeqCst);
183 loop {
184 let next = match prev.checked_add(1) {
185 Some(p1) => cand.max(p1),
186 None => return Err(err!(
187 "Driven clock file {:?}: the nanosecond counter is exhausted at {}.",
188 self.path, prev;
189 Overflow)),
190 };
191 match self.last_ns.compare_exchange_weak(
192 prev, next, Ordering::SeqCst, Ordering::SeqCst)
193 {
194 Ok(_) => return Ok(next),
195 Err(cur) => prev = cur,
196 }
197 }
198 }
199
200 /// Reads the file and clamps the value so that it never goes backwards.
201 fn read_millis(&self) -> Outcome<u64> {
202 let bytes = match std::fs::read(&self.path) {
203 Ok(b) => b,
204 Err(e) => return Err(err!(e,
205 "Reading driven clock file {:?}.", self.path;
206 IO, File, Read)),
207 };
208 let ms = match <[u8; 8]>::try_from(bytes.as_slice()) {
209 Ok(arr) => u64::from_le_bytes(arr),
210 Err(_) => return Err(err!(
211 "Driven clock file {:?} holds {} bytes, expected exactly 8 \
212 (a little-endian u64 of milliseconds since the Unix epoch).",
213 self.path, bytes.len();
214 Invalid, Input, Size)),
215 };
216 let prev = self.last.fetch_max(ms, Ordering::SeqCst);
217 Ok(prev.max(ms))
218 }
219}
220
221impl ClockSource {
222 /// Parses a clock specification: absent or `"system"` for the operating
223 /// system clock, `"driven:<path>"` for a file-driven clock.
224 pub fn from_spec(spec: Option<&str>) -> Outcome<Self> {
225 let spec = match spec {
226 None => return Ok(Self::System),
227 Some(s) => s.trim(),
228 };
229 if spec.is_empty() || spec == "system" {
230 return Ok(Self::System);
231 }
232 if let Some(path) = spec.strip_prefix("driven:") {
233 if path.is_empty() {
234 return Err(err!(
235 "Clock spec '{}' names no file after 'driven:'.", spec;
236 Invalid, Input, Missing));
237 }
238 #[cfg(not(target_arch = "wasm32"))]
239 return Ok(Self::Driven(Driven::new(path)));
240 #[cfg(target_arch = "wasm32")]
241 return Err(err!(
242 "Clock spec '{}': a driven clock reads a file and is \
243 unavailable on the wasm32 target.", spec;
244 Unimplemented));
245 }
246 Err(err!(
247 "Clock spec '{}' is neither 'system' nor 'driven:<path>'.", spec;
248 Invalid, Input))
249 }
250
251 /// Is the time read from a file rather than the operating system?
252 pub fn is_driven(&self) -> bool {
253 match self {
254 Self::System => false,
255 #[cfg(not(target_arch = "wasm32"))]
256 Self::Driven(_) => true,
257 }
258 }
259
260 pub fn now_secs(&self) -> Outcome<u64> {
261 Ok(res!(self.now_millis()) / 1_000)
262 }
263
264 pub fn now_millis(&self) -> Outcome<u64> {
265 match self {
266 #[cfg(not(target_arch = "wasm32"))]
267 Self::System => Ok(res!(system_since_epoch()).as_millis() as u64),
268 #[cfg(target_arch = "wasm32")]
269 Self::System => Ok(crate::wasm::now_ms() as u64),
270 #[cfg(not(target_arch = "wasm32"))]
271 Self::Driven(d) => d.read_millis(),
272 }
273 }
274
275 /// The time as a `SystemTime`, for code that keeps `SystemTime` stamps. For
276 /// `Driven`, the file's milliseconds after the epoch. Native only, since
277 /// `SystemTime::now` is unavailable on wasm32.
278 #[cfg(not(target_arch = "wasm32"))]
279 pub fn now_system_time(&self) -> Outcome<SystemTime> {
280 match self {
281 Self::System => Ok(SystemTime::now()),
282 Self::Driven(d) => {
283 let ms = res!(d.read_millis());
284 match UNIX_EPOCH.checked_add(Duration::from_millis(ms)) {
285 Some(t) => Ok(t),
286 None => Err(err!(
287 "Driven clock file {:?} holds {} ms, beyond what SystemTime \
288 can represent.", d.path, ms;
289 Invalid, Input, Overflow)),
290 }
291 }
292 }
293 }
294
295 /// For `Driven`, the file's milliseconds scaled to nanoseconds, bumped to
296 /// one past the previous value when the file has not moved, so successive
297 /// calls strictly increase and can order ledger entries. Over a million
298 /// calls in one file millisecond run ahead of it until the file catches up.
299 pub fn now_nanos(&self) -> Outcome<u128> {
300 match self {
301 #[cfg(not(target_arch = "wasm32"))]
302 Self::System => Ok(res!(system_since_epoch()).as_nanos()),
303 #[cfg(target_arch = "wasm32")]
304 Self::System => Ok((crate::wasm::now_ms() * 1_000_000.0) as u128),
305 #[cfg(not(target_arch = "wasm32"))]
306 Self::Driven(d) => {
307 Ok(res!(d.next_nanos()) as u128)
308 }
309 }
310 }
311}
312
313#[cfg(not(target_arch = "wasm32"))]
314fn system_since_epoch() -> Outcome<Duration> {
315 Ok(res!(SystemTime::now().duration_since(UNIX_EPOCH)))
316}
317
318static CLOCK: OnceLock<ClockSource> = OnceLock::new();
319static SYSTEM: ClockSource = ClockSource::System;
320
321/// Sets the process clock. It can be set once; a second call is an error, so
322/// a process cannot quietly change its time source part way through.
323#[cfg(not(target_arch = "wasm32"))]
324pub fn install(src: ClockSource) -> Outcome<()> {
325 match CLOCK.set(src) {
326 Ok(()) => Ok(()),
327 Err(src) => Err(err!(
328 "The process clock is already installed ({:?}); refusing to \
329 replace it with {:?}.", CLOCK.get(), src;
330 Invalid, Input, Exists)),
331 }
332}
333
334/// The process clock, `System` unless [`install`] set another.
335pub fn clock() -> &'static ClockSource {
336 match CLOCK.get() {
337 Some(c) => c,
338 None => &SYSTEM,
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345 use std::thread::sleep;
346
347 #[test]
348 fn test_timer() -> Outcome<()> {
349 let mut t0 = Timer::new();
350 sleep(Duration::from_micros(1000));
351 let mut t = res!(t0.split_micros());
352 msg!("timer split: {}", t);
353 sleep(Duration::from_micros(2000));
354 t = res!(t0.split_micros());
355 msg!("timer split: {}", t);
356 Ok(())
357 }
358
359 // Holding the file still past 10^6 calls must neither repeat nor step back.
360 #[test]
361 fn test_driven_nanos_strictly_increase_past_wrap() -> Outcome<()> {
362 let dir = std::env::temp_dir().join(fmt!("fe2o3_clock_wrap_{}", std::process::id()));
363 res!(std::fs::create_dir_all(&dir));
364 let path = dir.join("clock");
365 let ms: u64 = 1_000_000;
366 res!(std::fs::write(&path, ms.to_le_bytes()));
367 let src = ClockSource::Driven(Driven::new(&path));
368 let mut prev = res!(src.now_nanos());
369 if let ClockSource::Driven(d) = &src {
370 d.preset_ties(ms, 999_998);
371 }
372 for i in 0..5 {
373 let t = res!(src.now_nanos());
374 if t <= prev {
375 return Err(err!(
376 "Call {} after the preset returned {} <= previous {}.", i, t, prev;
377 Test, Order));
378 }
379 prev = t;
380 }
381 // A later file value is still honoured once it passes the ties.
382 res!(std::fs::write(&path, (ms + 1_000).to_le_bytes()));
383 let t = res!(src.now_nanos());
384 if t != (ms as u128 + 1_000) * 1_000_000 {
385 return Err(err!("After advancing 1 s, got {} not {}.", t,
386 (ms as u128 + 1_000) * 1_000_000; Test, Unexpected));
387 }
388 let _ = std::fs::remove_dir_all(&dir);
389 Ok(())
390 }
391}