nautilus_core/time.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3// https://poseitrader.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 `fetch_add` with [`Ordering::AcqRel`] to ensure the increment is
222 /// atomic and visible to readers using `Acquire` loads.
223 ///
224 /// # Panics
225 ///
226 /// Panics if called while the clock is in real-time mode.
227 pub fn increment_time(&self, delta: u64) -> UnixNanos {
228 assert!(
229 !self.realtime.load(Ordering::Acquire),
230 "Cannot increment time while clock is in realtime mode"
231 );
232
233 let prev = self.fetch_add(delta, Ordering::AcqRel);
234 UnixNanos::from(prev + delta)
235 }
236
237 /// Retrieves and updates the current “real-time” clock, returning a strictly increasing
238 /// timestamp based on system time.
239 ///
240 /// Internally:
241 /// - We fetch `now` from [`SystemTime::now()`].
242 /// - We do an atomic compare-and-exchange (using [`Ordering::AcqRel`]) to ensure the stored
243 /// timestamp is never less than the last timestamp.
244 ///
245 /// This ensures:
246 /// 1. **Monotonic increments**: The returned timestamp is strictly greater than the previous
247 /// one (by at least 1 nanosecond).
248 /// 2. **No backward jumps**: If the OS time moves backward, we ignore that shift to preserve
249 /// monotonicity.
250 /// 3. **Visibility**: In a multi-threaded environment, other threads see the updated value
251 /// once this compare-and-exchange completes.
252 ///
253 /// # Panics
254 ///
255 /// Panics if the internal counter has reached `u64::MAX`, which would indicate the process has
256 /// been running for longer than the representable range (~584 years) *or* the clock was
257 /// manually corrupted.
258 pub fn time_since_epoch(&self) -> UnixNanos {
259 // This method guarantees strict consistency but may incur a performance cost under
260 // high contention due to retries in the `compare_exchange` loop.
261 let now = nanos_since_unix_epoch();
262 loop {
263 // Acquire to observe the latest stored value
264 let last = self.load(Ordering::Acquire);
265 // Ensure we never wrap past u64::MAX – treat that as a fatal error
266 let incremented = last
267 .checked_add(1)
268 .expect("AtomicTime overflow: reached u64::MAX");
269 let next = now.max(incremented);
270 // AcqRel on success ensures this new value is published,
271 // Acquire on failure reloads if we lost a CAS race.
272 //
273 // Note that under heavy contention (many threads calling this in tight loops),
274 // the CAS loop may increase latency.
275 //
276 // However, in practice, the loop terminates quickly because:
277 // - System time naturally advances between iterations
278 // - Each iteration increments time by at least 1ns, preventing ABA problems
279 // - True contention requiring retry is rare in normal usage patterns
280 //
281 // The concurrent stress test (4 threads × 100k iterations) validates this approach.
282 if self
283 .compare_exchange(last, next, Ordering::AcqRel, Ordering::Acquire)
284 .is_ok()
285 {
286 return UnixNanos::from(next);
287 }
288 }
289 }
290
291 /// Switches the clock to **real-time mode** (`realtime = true`).
292 ///
293 /// Uses [`Ordering::SeqCst`] for the mode store, which ensures a global ordering for the
294 /// mode switch if other threads also do `SeqCst` loads/stores of `realtime`.
295 /// Typically, switching modes is done infrequently, so the performance impact of `SeqCst`
296 /// here is acceptable.
297 pub fn make_realtime(&self) {
298 self.realtime.store(true, Ordering::SeqCst);
299 }
300
301 /// Switches the clock to **static mode** (`realtime = false`).
302 ///
303 /// Uses [`Ordering::SeqCst`] for the mode store, which ensures a global ordering for the
304 /// mode switch if other threads also do `SeqCst` loads/stores of `realtime`.
305 pub fn make_static(&self) {
306 self.realtime.store(false, Ordering::SeqCst);
307 }
308}
309
310////////////////////////////////////////////////////////////////////////////////
311// Tests
312////////////////////////////////////////////////////////////////////////////////
313#[cfg(test)]
314mod tests {
315 use std::sync::Arc;
316
317 use rstest::*;
318
319 use super::*;
320
321 #[rstest]
322 fn test_global_clocks_initialization() {
323 let realtime_clock = get_atomic_clock_realtime();
324 assert!(realtime_clock.get_time_ns().as_u64() > 0);
325
326 let static_clock = get_atomic_clock_static();
327 static_clock.set_time(UnixNanos::from(500_000_000)); // 500 ms
328 assert_eq!(static_clock.get_time_ns().as_u64(), 500_000_000);
329 }
330
331 #[rstest]
332 fn test_mode_switching() {
333 let time = AtomicTime::new(true, UnixNanos::default());
334
335 // Verify real-time mode
336 let realtime_ns = time.get_time_ns();
337 assert!(realtime_ns.as_u64() > 0);
338
339 // Switch to static mode
340 time.make_static();
341 time.set_time(UnixNanos::from(1_000_000_000)); // 1 second
342 let static_ns = time.get_time_ns();
343 assert_eq!(static_ns.as_u64(), 1_000_000_000);
344
345 // Switch back to real-time mode
346 time.make_realtime();
347 let new_realtime_ns = time.get_time_ns();
348 assert!(new_realtime_ns.as_u64() > static_ns.as_u64());
349 }
350
351 #[rstest]
352 #[should_panic(expected = "Cannot set time while clock is in realtime mode")]
353 fn test_set_time_panics_in_realtime_mode() {
354 let clock = AtomicTime::new(true, UnixNanos::default());
355 clock.set_time(UnixNanos::from(123));
356 }
357
358 #[rstest]
359 #[should_panic(expected = "Cannot increment time while clock is in realtime mode")]
360 fn test_increment_time_panics_in_realtime_mode() {
361 let clock = AtomicTime::new(true, UnixNanos::default());
362 let _ = clock.increment_time(1);
363 }
364
365 #[rstest]
366 #[should_panic(expected = "AtomicTime overflow")]
367 fn test_time_since_epoch_overflow_panics() {
368 use std::sync::atomic::{AtomicBool, AtomicU64};
369
370 // Manually construct a clock with the counter already at u64::MAX
371 let clock = AtomicTime {
372 realtime: AtomicBool::new(true),
373 timestamp_ns: AtomicU64::new(u64::MAX),
374 };
375
376 // This call will attempt to add 1 and must panic
377 let _ = clock.time_since_epoch();
378 }
379
380 #[rstest]
381 fn test_mode_switching_concurrent() {
382 let clock = Arc::new(AtomicTime::new(true, UnixNanos::default()));
383 let num_threads = 4;
384 let iterations = 10000;
385 let mut handles = Vec::with_capacity(num_threads);
386
387 for _ in 0..num_threads {
388 let clock_clone = Arc::clone(&clock);
389 let handle = std::thread::spawn(move || {
390 for i in 0..iterations {
391 if i % 2 == 0 {
392 clock_clone.make_static();
393 } else {
394 clock_clone.make_realtime();
395 }
396 // Retrieve the time; we’re not asserting a particular value here,
397 // but at least we’re exercising the mode switch logic under concurrency.
398 let _ = clock_clone.get_time_ns();
399 }
400 });
401 handles.push(handle);
402 }
403
404 for handle in handles {
405 handle.join().unwrap();
406 }
407 }
408
409 #[rstest]
410 fn test_static_time_is_stable() {
411 // Create a clock in static mode with an initial value
412 let clock = AtomicTime::new(false, UnixNanos::from(42));
413 let time1 = clock.get_time_ns();
414
415 // Sleep a bit to give the system time to change, if the clock were using real-time
416 std::thread::sleep(std::time::Duration::from_millis(10));
417 let time2 = clock.get_time_ns();
418
419 // In static mode, the value should remain unchanged
420 assert_eq!(time1, time2);
421 }
422
423 #[rstest]
424 fn test_increment_time() {
425 // Start in static mode
426 let time = AtomicTime::new(false, UnixNanos::from(0));
427
428 let updated_time = time.increment_time(500);
429 assert_eq!(updated_time.as_u64(), 500);
430
431 let updated_time = time.increment_time(1_000);
432 assert_eq!(updated_time.as_u64(), 1_500);
433 }
434
435 #[rstest]
436 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
437 fn test_nanos_since_unix_epoch_vs_system_time() {
438 let unix_nanos = nanos_since_unix_epoch();
439 let system_ns = duration_since_unix_epoch().as_nanos() as u64;
440 assert!((unix_nanos as i64 - system_ns as i64).abs() < NANOSECONDS_IN_SECOND as i64);
441 }
442
443 #[rstest]
444 fn test_time_since_epoch_monotonicity() {
445 let clock = get_atomic_clock_realtime();
446 let mut previous = clock.time_since_epoch();
447 for _ in 0..1_000_000 {
448 let current = clock.time_since_epoch();
449 assert!(current > previous);
450 previous = current;
451 }
452 }
453
454 #[rstest]
455 fn test_time_since_epoch_strictly_increasing_concurrent() {
456 let time = Arc::new(AtomicTime::new(true, UnixNanos::default()));
457 let num_threads = 4;
458 let iterations = 100_000;
459 let mut handles = Vec::with_capacity(num_threads);
460
461 for thread_id in 0..num_threads {
462 let time_clone = Arc::clone(&time);
463
464 let handle = std::thread::spawn(move || {
465 let mut previous = time_clone.time_since_epoch().as_u64();
466
467 for i in 0..iterations {
468 let current = time_clone.time_since_epoch().as_u64();
469 assert!(
470 current > previous,
471 "Thread {thread_id}: iteration {i}: time did not increase: previous={previous}, current={current}",
472 );
473 previous = current;
474 }
475 });
476
477 handles.push(handle);
478 }
479
480 for handle in handles {
481 handle.join().unwrap();
482 }
483 }
484
485 #[rstest]
486 fn test_duration_since_unix_epoch() {
487 let time = AtomicTime::new(true, UnixNanos::default());
488 let duration = Duration::from_nanos(time.get_time_ns().into());
489 let now = SystemTime::now();
490
491 // Check if the duration is close to the actual difference between now and UNIX_EPOCH
492 let delta = now
493 .duration_since(UNIX_EPOCH)
494 .unwrap()
495 .checked_sub(duration);
496 assert!(delta.unwrap_or_default() < Duration::from_millis(100));
497
498 // Check if the duration is greater than a certain value (assuming the test is run after that point)
499 assert!(duration > Duration::from_secs(1_650_000_000));
500 }
501
502 #[rstest]
503 fn test_unix_timestamp_is_monotonic_increasing() {
504 let time = AtomicTime::new(true, UnixNanos::default());
505 let result1 = time.get_time();
506 let result2 = time.get_time();
507 let result3 = time.get_time();
508 let result4 = time.get_time();
509 let result5 = time.get_time();
510
511 assert!(result2 >= result1);
512 assert!(result3 >= result2);
513 assert!(result4 >= result3);
514 assert!(result5 >= result4);
515 assert!(result1 > 1_650_000_000.0);
516 }
517
518 #[rstest]
519 fn test_unix_timestamp_ms_is_monotonic_increasing() {
520 let time = AtomicTime::new(true, UnixNanos::default());
521 let result1 = time.get_time_ms();
522 let result2 = time.get_time_ms();
523 let result3 = time.get_time_ms();
524 let result4 = time.get_time_ms();
525 let result5 = time.get_time_ms();
526
527 assert!(result2 >= result1);
528 assert!(result3 >= result2);
529 assert!(result4 >= result3);
530 assert!(result5 >= result4);
531 assert!(result1 >= 1_650_000_000_000);
532 }
533
534 #[rstest]
535 fn test_unix_timestamp_us_is_monotonic_increasing() {
536 let time = AtomicTime::new(true, UnixNanos::default());
537 let result1 = time.get_time_us();
538 let result2 = time.get_time_us();
539 let result3 = time.get_time_us();
540 let result4 = time.get_time_us();
541 let result5 = time.get_time_us();
542
543 assert!(result2 >= result1);
544 assert!(result3 >= result2);
545 assert!(result4 >= result3);
546 assert!(result5 >= result4);
547 assert!(result1 > 1_650_000_000_000_000);
548 }
549
550 #[rstest]
551 fn test_unix_timestamp_ns_is_monotonic_increasing() {
552 let time = AtomicTime::new(true, UnixNanos::default());
553 let result1 = time.get_time_ns();
554 let result2 = time.get_time_ns();
555 let result3 = time.get_time_ns();
556 let result4 = time.get_time_ns();
557 let result5 = time.get_time_ns();
558
559 assert!(result2 >= result1);
560 assert!(result3 >= result2);
561 assert!(result4 >= result3);
562 assert!(result5 >= result4);
563 assert!(result1.as_u64() > 1_650_000_000_000_000_000);
564 }
565}