nautilus_core/time.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! The core `AtomicTime` for real-time and static clocks.
17//!
18//! This module provides an atomic time abstraction that supports both real-time and static
19//! clocks. It ensures thread-safe operations and monotonic time retrieval with nanosecond precision.
20//!
21//! # Modes
22//!
23//! - **Real-time mode:** The clock continuously syncs with system wall-clock time (via
24//! [`SystemTime::now()`]). To ensure strict monotonic increments across multiple threads,
25//! the internal updates use an atomic compare-and-exchange loop (`time_since_epoch`).
26//! While this guarantees that every new timestamp is at least one nanosecond greater than the
27//! last, it may introduce higher contention if many threads call it heavily.
28//!
29//! - **Static mode:** The clock is manually controlled via [`AtomicTime::set_time`] or [`AtomicTime::increment_time`],
30//! which can be useful for simulations or backtesting. You can switch modes at runtime using
31//! [`AtomicTime::make_realtime`] or [`AtomicTime::make_static`]. In **static mode**, we use
32//! acquire/release semantics so that updates from one thread can be observed by another;
33//! however, we do not enforce strict global ordering for manual updates. If you need strong,
34//! multi-threaded ordering in **static mode**, you must coordinate higher-level synchronization yourself.
35
36use std::{
37 ops::Deref,
38 sync::{
39 OnceLock,
40 atomic::{AtomicBool, AtomicU64, Ordering},
41 },
42 time::{Duration, SystemTime, UNIX_EPOCH},
43};
44
45use crate::{
46 UnixNanos,
47 datetime::{NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND, NANOSECONDS_IN_SECOND},
48};
49
50/// Global atomic time in **real-time mode** for use across the system.
51///
52/// This clock operates in **real-time mode**, synchronizing with the system clock.
53/// It provides globally unique, strictly increasing timestamps across threads.
54pub static ATOMIC_CLOCK_REALTIME: OnceLock<AtomicTime> = OnceLock::new();
55
56/// Global atomic time in **static mode** for use across the system.
57///
58/// This clock operates in **static mode**, where the time value can be set or incremented
59/// manually. Useful for backtesting or simulated time control.
60pub static ATOMIC_CLOCK_STATIC: OnceLock<AtomicTime> = OnceLock::new();
61
62/// Returns a static reference to the global atomic clock in **real-time mode**.
63///
64/// This clock uses [`AtomicTime::time_since_epoch`] under the hood, ensuring strictly increasing
65/// timestamps across threads.
66pub fn get_atomic_clock_realtime() -> &'static AtomicTime {
67 ATOMIC_CLOCK_REALTIME.get_or_init(AtomicTime::default)
68}
69
70/// Returns a static reference to the global atomic clock in **static mode**.
71///
72/// This clock allows manual time control via [`AtomicTime::set_time`] or [`AtomicTime::increment_time`],
73/// and does not automatically sync with system time.
74pub fn get_atomic_clock_static() -> &'static AtomicTime {
75 ATOMIC_CLOCK_STATIC.get_or_init(|| AtomicTime::new(false, UnixNanos::default()))
76}
77
78/// Returns the duration since the UNIX epoch based on [`SystemTime::now()`].
79///
80/// # Panics
81///
82/// Panics if the system time is set before the UNIX epoch.
83#[inline(always)]
84#[must_use]
85pub fn duration_since_unix_epoch() -> Duration {
86 // SAFETY: The expect() is acceptable here because:
87 // - SystemTime failure indicates catastrophic system clock issues
88 // - This would affect the entire application's ability to function
89 // - Alternative error handling would complicate all time-dependent code paths
90 // - Such failures are extremely rare in practice and indicate hardware/OS problems
91 SystemTime::now()
92 .duration_since(UNIX_EPOCH)
93 .expect("Error calling `SystemTime`")
94}
95
96/// Returns the current UNIX time in nanoseconds, based on [`SystemTime::now()`].
97///
98/// # Panics
99///
100/// Panics if the duration in nanoseconds exceeds `u64::MAX`.
101#[inline(always)]
102#[must_use]
103pub fn nanos_since_unix_epoch() -> u64 {
104 let ns = duration_since_unix_epoch().as_nanos();
105 assert!(
106 ns <= u128::from(u64::MAX),
107 "System time overflow: value exceeds u64::MAX nanoseconds"
108 );
109 ns as u64
110}
111
112/// Represents an atomic timekeeping structure.
113///
114/// [`AtomicTime`] can act as a real-time clock or static clock based on its mode.
115/// It uses an [`AtomicU64`] to atomically update the value using only immutable
116/// references.
117///
118/// The `realtime` flag indicates which mode the clock is currently in.
119/// For concurrency, this struct uses atomic operations with appropriate memory orderings:
120/// - **Acquire/Release** for reading/writing in **static mode**.
121/// - **Compare-and-exchange (`AcqRel`)** in real-time mode to guarantee monotonic increments.
122#[repr(C)]
123#[derive(Debug)]
124pub struct AtomicTime {
125 /// Indicates whether the clock is operating in **real-time mode** (`true`) or **static mode** (`false`)
126 pub realtime: AtomicBool,
127 /// The last recorded time (in UNIX nanoseconds). Updated atomically with compare-and-exchange
128 /// in **real-time mode**, or simple store/fetch in **static mode**.
129 pub timestamp_ns: AtomicU64,
130}
131
132impl Deref for AtomicTime {
133 type Target = AtomicU64;
134
135 fn deref(&self) -> &Self::Target {
136 &self.timestamp_ns
137 }
138}
139
140impl Default for AtomicTime {
141 /// Creates a new default [`AtomicTime`] instance in **real-time mode**, starting at the current system time.
142 fn default() -> Self {
143 Self::new(true, UnixNanos::default())
144 }
145}
146
147impl AtomicTime {
148 /// Creates a new [`AtomicTime`] instance.
149 ///
150 /// - If `realtime` is `true`, the provided `time` is used only as an initial placeholder
151 /// and will quickly be overridden by calls to [`AtomicTime::time_since_epoch`].
152 /// - If `realtime` is `false`, this clock starts in **static mode**, with the given `time`
153 /// as its current value.
154 #[must_use]
155 pub fn new(realtime: bool, time: UnixNanos) -> Self {
156 Self {
157 realtime: AtomicBool::new(realtime),
158 timestamp_ns: AtomicU64::new(time.into()),
159 }
160 }
161
162 /// Returns the current time in nanoseconds, based on the clock’s mode.
163 ///
164 /// - In **real-time mode**, calls [`AtomicTime::time_since_epoch`], ensuring strictly increasing
165 /// timestamps across threads, using `AcqRel` semantics for the underlying atomic.
166 /// - In **static mode**, reads the stored time using [`Ordering::Acquire`]. Updates by other
167 /// threads using [`AtomicTime::set_time`] or [`AtomicTime::increment_time`] (Release/AcqRel)
168 /// will be visible here.
169 #[must_use]
170 pub fn get_time_ns(&self) -> UnixNanos {
171 if self.realtime.load(Ordering::Acquire) {
172 self.time_since_epoch()
173 } else {
174 UnixNanos::from(self.timestamp_ns.load(Ordering::Acquire))
175 }
176 }
177
178 /// Returns the current time as microseconds.
179 #[must_use]
180 pub fn get_time_us(&self) -> u64 {
181 self.get_time_ns().as_u64() / NANOSECONDS_IN_MICROSECOND
182 }
183
184 /// Returns the current time as milliseconds.
185 #[must_use]
186 pub fn get_time_ms(&self) -> u64 {
187 self.get_time_ns().as_u64() / NANOSECONDS_IN_MILLISECOND
188 }
189
190 /// Returns the current time as seconds.
191 #[must_use]
192 #[allow(clippy::cast_precision_loss)]
193 pub fn get_time(&self) -> f64 {
194 self.get_time_ns().as_f64() / (NANOSECONDS_IN_SECOND as f64)
195 }
196
197 /// Manually sets a new time for the clock (only meaningful in **static mode**).
198 ///
199 /// This uses an atomic store with [`Ordering::Release`], so any thread reading with
200 /// [`Ordering::Acquire`] will see the updated time. This does *not* enforce a total ordering
201 /// among all threads, but is enough to ensure that once a thread sees this update, it also
202 /// sees all writes made before this call in the writing thread.
203 ///
204 /// Typically used in single-threaded scenarios or coordinated concurrency in **static mode**,
205 /// since there’s no global ordering across threads.
206 ///
207 /// # Panics
208 ///
209 /// Panics if invoked when in real-time mode.
210 pub fn set_time(&self, time: UnixNanos) {
211 assert!(
212 !self.realtime.load(Ordering::Acquire),
213 "Cannot set time while clock is in realtime mode"
214 );
215
216 self.store(time.into(), Ordering::Release);
217 }
218
219 /// Increments the current (static-mode) time by `delta` nanoseconds and returns the updated value.
220 ///
221 /// Internally this uses [`AtomicU64::fetch_update`] with [`Ordering::AcqRel`] to ensure the increment is
222 /// atomic and visible to readers using `Acquire` loads.
223 ///
224 /// # Errors
225 ///
226 /// Returns an error if the increment would overflow `u64::MAX`.
227 ///
228 /// # Panics
229 ///
230 /// Panics if called while the clock is in real-time mode.
231 pub fn increment_time(&self, delta: u64) -> anyhow::Result<UnixNanos> {
232 assert!(
233 !self.realtime.load(Ordering::Acquire),
234 "Cannot increment time while clock is in realtime mode"
235 );
236
237 let previous =
238 match self
239 .timestamp_ns
240 .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
241 current.checked_add(delta)
242 }) {
243 Ok(prev) => prev,
244 Err(_) => anyhow::bail!("Cannot increment time beyond u64::MAX"),
245 };
246
247 Ok(UnixNanos::from(previous + delta))
248 }
249
250 /// Retrieves and updates the current “real-time” clock, returning a strictly increasing
251 /// timestamp based on system time.
252 ///
253 /// Internally:
254 /// - We fetch `now` from [`SystemTime::now()`].
255 /// - We do an atomic compare-and-exchange (using [`Ordering::AcqRel`]) to ensure the stored
256 /// timestamp is never less than the last timestamp.
257 ///
258 /// This ensures:
259 /// 1. **Monotonic increments**: The returned timestamp is strictly greater than the previous
260 /// one (by at least 1 nanosecond).
261 /// 2. **No backward jumps**: If the OS time moves backward, we ignore that shift to preserve
262 /// monotonicity.
263 /// 3. **Visibility**: In a multi-threaded environment, other threads see the updated value
264 /// once this compare-and-exchange completes.
265 ///
266 /// # Panics
267 ///
268 /// Panics if the internal counter has reached `u64::MAX`, which would indicate the process has
269 /// been running for longer than the representable range (~584 years) *or* the clock was
270 /// manually corrupted.
271 pub fn time_since_epoch(&self) -> UnixNanos {
272 // This method guarantees strict consistency but may incur a performance cost under
273 // high contention due to retries in the `compare_exchange` loop.
274 let now = nanos_since_unix_epoch();
275 loop {
276 // Acquire to observe the latest stored value
277 let last = self.load(Ordering::Acquire);
278 // Ensure we never wrap past u64::MAX – treat that as a fatal error
279 let incremented = last
280 .checked_add(1)
281 .expect("AtomicTime overflow: reached u64::MAX");
282 let next = now.max(incremented);
283 // AcqRel on success ensures this new value is published,
284 // Acquire on failure reloads if we lost a CAS race.
285 //
286 // Note that under heavy contention (many threads calling this in tight loops),
287 // the CAS loop may increase latency.
288 //
289 // However, in practice, the loop terminates quickly because:
290 // - System time naturally advances between iterations
291 // - Each iteration increments time by at least 1ns, preventing ABA problems
292 // - True contention requiring retry is rare in normal usage patterns
293 //
294 // The concurrent stress test (4 threads × 100k iterations) validates this approach.
295 if self
296 .compare_exchange(last, next, Ordering::AcqRel, Ordering::Acquire)
297 .is_ok()
298 {
299 return UnixNanos::from(next);
300 }
301 }
302 }
303
304 /// Switches the clock to **real-time mode** (`realtime = true`).
305 ///
306 /// Uses [`Ordering::SeqCst`] for the mode store, which ensures a global ordering for the
307 /// mode switch if other threads also do `SeqCst` loads/stores of `realtime`.
308 /// Typically, switching modes is done infrequently, so the performance impact of `SeqCst`
309 /// here is acceptable.
310 pub fn make_realtime(&self) {
311 self.realtime.store(true, Ordering::SeqCst);
312 }
313
314 /// Switches the clock to **static mode** (`realtime = false`).
315 ///
316 /// Uses [`Ordering::SeqCst`] for the mode store, which ensures a global ordering for the
317 /// mode switch if other threads also do `SeqCst` loads/stores of `realtime`.
318 pub fn make_static(&self) {
319 self.realtime.store(false, Ordering::SeqCst);
320 }
321}
322
323////////////////////////////////////////////////////////////////////////////////
324// Tests
325////////////////////////////////////////////////////////////////////////////////
326#[cfg(test)]
327mod tests {
328 use std::sync::Arc;
329
330 use rstest::*;
331
332 use super::*;
333
334 #[rstest]
335 fn test_global_clocks_initialization() {
336 let realtime_clock = get_atomic_clock_realtime();
337 assert!(realtime_clock.get_time_ns().as_u64() > 0);
338
339 let static_clock = get_atomic_clock_static();
340 static_clock.set_time(UnixNanos::from(500_000_000)); // 500 ms
341 assert_eq!(static_clock.get_time_ns().as_u64(), 500_000_000);
342 }
343
344 #[rstest]
345 fn test_mode_switching() {
346 let time = AtomicTime::new(true, UnixNanos::default());
347
348 // Verify real-time mode
349 let realtime_ns = time.get_time_ns();
350 assert!(realtime_ns.as_u64() > 0);
351
352 // Switch to static mode
353 time.make_static();
354 time.set_time(UnixNanos::from(1_000_000_000)); // 1 second
355 let static_ns = time.get_time_ns();
356 assert_eq!(static_ns.as_u64(), 1_000_000_000);
357
358 // Switch back to real-time mode
359 time.make_realtime();
360 let new_realtime_ns = time.get_time_ns();
361 assert!(new_realtime_ns.as_u64() > static_ns.as_u64());
362 }
363
364 #[rstest]
365 #[should_panic(expected = "Cannot set time while clock is in realtime mode")]
366 fn test_set_time_panics_in_realtime_mode() {
367 let clock = AtomicTime::new(true, UnixNanos::default());
368 clock.set_time(UnixNanos::from(123));
369 }
370
371 #[rstest]
372 #[should_panic(expected = "Cannot increment time while clock is in realtime mode")]
373 fn test_increment_time_panics_in_realtime_mode() {
374 let clock = AtomicTime::new(true, UnixNanos::default());
375 let _ = clock.increment_time(1);
376 }
377
378 #[rstest]
379 #[should_panic(expected = "AtomicTime overflow")]
380 fn test_time_since_epoch_overflow_panics() {
381 use std::sync::atomic::{AtomicBool, AtomicU64};
382
383 // Manually construct a clock with the counter already at u64::MAX
384 let clock = AtomicTime {
385 realtime: AtomicBool::new(true),
386 timestamp_ns: AtomicU64::new(u64::MAX),
387 };
388
389 // This call will attempt to add 1 and must panic
390 let _ = clock.time_since_epoch();
391 }
392
393 #[rstest]
394 fn test_mode_switching_concurrent() {
395 let clock = Arc::new(AtomicTime::new(true, UnixNanos::default()));
396 let num_threads = 4;
397 let iterations = 10000;
398 let mut handles = Vec::with_capacity(num_threads);
399
400 for _ in 0..num_threads {
401 let clock_clone = Arc::clone(&clock);
402 let handle = std::thread::spawn(move || {
403 for i in 0..iterations {
404 if i % 2 == 0 {
405 clock_clone.make_static();
406 } else {
407 clock_clone.make_realtime();
408 }
409 // Retrieve the time; we’re not asserting a particular value here,
410 // but at least we’re exercising the mode switch logic under concurrency.
411 let _ = clock_clone.get_time_ns();
412 }
413 });
414 handles.push(handle);
415 }
416
417 for handle in handles {
418 handle.join().unwrap();
419 }
420 }
421
422 #[rstest]
423 fn test_static_time_is_stable() {
424 // Create a clock in static mode with an initial value
425 let clock = AtomicTime::new(false, UnixNanos::from(42));
426 let time1 = clock.get_time_ns();
427
428 // Sleep a bit to give the system time to change, if the clock were using real-time
429 std::thread::sleep(std::time::Duration::from_millis(10));
430 let time2 = clock.get_time_ns();
431
432 // In static mode, the value should remain unchanged
433 assert_eq!(time1, time2);
434 }
435
436 #[rstest]
437 fn test_increment_time() {
438 // Start in static mode
439 let time = AtomicTime::new(false, UnixNanos::from(0));
440
441 let updated_time = time.increment_time(500).unwrap();
442 assert_eq!(updated_time.as_u64(), 500);
443
444 let updated_time = time.increment_time(1_000).unwrap();
445 assert_eq!(updated_time.as_u64(), 1_500);
446 }
447
448 #[rstest]
449 fn test_increment_time_overflow_errors() {
450 let time = AtomicTime::new(false, UnixNanos::from(u64::MAX - 5));
451
452 let err = time.increment_time(10).unwrap_err();
453 assert_eq!(err.to_string(), "Cannot increment time beyond u64::MAX");
454 }
455
456 #[rstest]
457 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
458 fn test_nanos_since_unix_epoch_vs_system_time() {
459 let unix_nanos = nanos_since_unix_epoch();
460 let system_ns = duration_since_unix_epoch().as_nanos() as u64;
461 assert!((unix_nanos as i64 - system_ns as i64).abs() < NANOSECONDS_IN_SECOND as i64);
462 }
463
464 #[rstest]
465 fn test_time_since_epoch_monotonicity() {
466 let clock = get_atomic_clock_realtime();
467 let mut previous = clock.time_since_epoch();
468 for _ in 0..1_000_000 {
469 let current = clock.time_since_epoch();
470 assert!(current > previous);
471 previous = current;
472 }
473 }
474
475 #[rstest]
476 fn test_time_since_epoch_strictly_increasing_concurrent() {
477 let time = Arc::new(AtomicTime::new(true, UnixNanos::default()));
478 let num_threads = 4;
479 let iterations = 100_000;
480 let mut handles = Vec::with_capacity(num_threads);
481
482 for thread_id in 0..num_threads {
483 let time_clone = Arc::clone(&time);
484
485 let handle = std::thread::spawn(move || {
486 let mut previous = time_clone.time_since_epoch().as_u64();
487
488 for i in 0..iterations {
489 let current = time_clone.time_since_epoch().as_u64();
490 assert!(
491 current > previous,
492 "Thread {thread_id}: iteration {i}: time did not increase: previous={previous}, current={current}",
493 );
494 previous = current;
495 }
496 });
497
498 handles.push(handle);
499 }
500
501 for handle in handles {
502 handle.join().unwrap();
503 }
504 }
505
506 #[rstest]
507 fn test_duration_since_unix_epoch() {
508 let time = AtomicTime::new(true, UnixNanos::default());
509 let duration = Duration::from_nanos(time.get_time_ns().into());
510 let now = SystemTime::now();
511
512 // Check if the duration is close to the actual difference between now and UNIX_EPOCH
513 let delta = now
514 .duration_since(UNIX_EPOCH)
515 .unwrap()
516 .checked_sub(duration);
517 assert!(delta.unwrap_or_default() < Duration::from_millis(100));
518
519 // Check if the duration is greater than a certain value (assuming the test is run after that point)
520 assert!(duration > Duration::from_secs(1_650_000_000));
521 }
522
523 #[rstest]
524 fn test_unix_timestamp_is_monotonic_increasing() {
525 let time = AtomicTime::new(true, UnixNanos::default());
526 let result1 = time.get_time();
527 let result2 = time.get_time();
528 let result3 = time.get_time();
529 let result4 = time.get_time();
530 let result5 = time.get_time();
531
532 assert!(result2 >= result1);
533 assert!(result3 >= result2);
534 assert!(result4 >= result3);
535 assert!(result5 >= result4);
536 assert!(result1 > 1_650_000_000.0);
537 }
538
539 #[rstest]
540 fn test_unix_timestamp_ms_is_monotonic_increasing() {
541 let time = AtomicTime::new(true, UnixNanos::default());
542 let result1 = time.get_time_ms();
543 let result2 = time.get_time_ms();
544 let result3 = time.get_time_ms();
545 let result4 = time.get_time_ms();
546 let result5 = time.get_time_ms();
547
548 assert!(result2 >= result1);
549 assert!(result3 >= result2);
550 assert!(result4 >= result3);
551 assert!(result5 >= result4);
552 assert!(result1 >= 1_650_000_000_000);
553 }
554
555 #[rstest]
556 fn test_unix_timestamp_us_is_monotonic_increasing() {
557 let time = AtomicTime::new(true, UnixNanos::default());
558 let result1 = time.get_time_us();
559 let result2 = time.get_time_us();
560 let result3 = time.get_time_us();
561 let result4 = time.get_time_us();
562 let result5 = time.get_time_us();
563
564 assert!(result2 >= result1);
565 assert!(result3 >= result2);
566 assert!(result4 >= result3);
567 assert!(result5 >= result4);
568 assert!(result1 > 1_650_000_000_000_000);
569 }
570
571 #[rstest]
572 fn test_unix_timestamp_ns_is_monotonic_increasing() {
573 let time = AtomicTime::new(true, UnixNanos::default());
574 let result1 = time.get_time_ns();
575 let result2 = time.get_time_ns();
576 let result3 = time.get_time_ns();
577 let result4 = time.get_time_ns();
578 let result5 = time.get_time_ns();
579
580 assert!(result2 >= result1);
581 assert!(result3 >= result2);
582 assert!(result4 >= result3);
583 assert!(result5 >= result4);
584 assert!(result1.as_u64() > 1_650_000_000_000_000_000);
585 }
586}