Skip to main content

nautilus_system/
clock_factory.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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//! Clock construction for kernel and component clocks.
17
18use std::{
19    cell::{OnceCell, RefCell},
20    fmt::Debug,
21    rc::Rc,
22};
23
24use nautilus_common::{
25    clock::{Clock, VirtualClock},
26    enums::Environment,
27};
28
29/// Clock source for the kernel clock and fresh component clocks.
30///
31/// The primary clock is created lazily and shared by the kernel and trader timestamps. Component
32/// clocks are freshly constructed so callback registration remains isolated per component.
33#[derive(Clone)]
34pub struct ClockFactory {
35    clock: Rc<OnceCell<Rc<RefCell<dyn Clock>>>>,
36    create_clock: Rc<dyn Fn() -> Rc<RefCell<dyn Clock>>>,
37}
38
39impl ClockFactory {
40    /// Create a [`ClockFactory`] from a re-invocable closure.
41    #[must_use]
42    pub fn new<F>(factory: F) -> Self
43    where
44        F: Fn() -> Rc<RefCell<dyn Clock>> + 'static,
45    {
46        Self {
47            clock: Rc::new(OnceCell::new()),
48            create_clock: Rc::new(factory),
49        }
50    }
51
52    /// Create a test-default [`ClockFactory`].
53    #[must_use]
54    pub fn test_default() -> Self {
55        Self::for_environment(Environment::Backtest)
56    }
57
58    /// Create the default [`ClockFactory`] for an environment.
59    #[must_use]
60    pub fn for_environment(environment: Environment) -> Self {
61        match environment {
62            Environment::Backtest => Self::new(|| Rc::new(RefCell::new(VirtualClock::new()))),
63            Environment::Live | Environment::Sandbox => Self::live_default(),
64        }
65    }
66
67    /// Return the primary clock.
68    #[must_use]
69    pub fn clock(&self) -> Rc<RefCell<dyn Clock>> {
70        self.clock.get_or_init(|| (self.create_clock)()).clone()
71    }
72
73    /// Build a fresh component clock instance.
74    ///
75    /// Virtual clocks start at the primary clock's current time when it exists.
76    #[must_use]
77    pub fn create_component_clock(&self) -> Rc<RefCell<dyn Clock>> {
78        let clock = (self.create_clock)();
79
80        if let Some(primary) = self.clock.get() {
81            let now = primary.borrow().timestamp_ns();
82            if let Some(clock) = clock
83                .borrow_mut()
84                .as_any_mut()
85                .downcast_mut::<VirtualClock>()
86            {
87                clock.set_time(now);
88            }
89        }
90
91        clock
92    }
93
94    #[cfg(feature = "live")]
95    fn live_default() -> Self {
96        Self::new(|| {
97            Rc::new(RefCell::new(
98                nautilus_common::live::clock::LiveClock::default(), // nautilus-import-ok
99            ))
100        })
101    }
102
103    #[cfg(not(feature = "live"))]
104    fn live_default() -> Self {
105        Self::new(|| {
106            panic!(
107                "Live/Sandbox environment requires the 'live' feature to be enabled. \
108                 Build with `--features live` or supply a clock factory."
109            )
110        })
111    }
112}
113
114impl Debug for ClockFactory {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.debug_struct(stringify!(ClockFactory))
117            .finish_non_exhaustive()
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use std::cell::Cell;
124
125    use rstest::rstest;
126
127    use super::*;
128
129    #[rstest]
130    fn test_clock_memoizes_primary_clock() {
131        let calls = Rc::new(Cell::new(0usize));
132        let calls_in_factory = calls.clone();
133        let factory = ClockFactory::new(move || {
134            calls_in_factory.set(calls_in_factory.get() + 1);
135            Rc::new(RefCell::new(VirtualClock::new()))
136        });
137
138        let first = factory.clock();
139        let second = factory.clock();
140
141        assert_eq!(calls.get(), 1);
142        assert!(Rc::ptr_eq(&first, &second));
143    }
144
145    #[rstest]
146    fn test_create_component_clock_returns_distinct_clocks() {
147        let factory = ClockFactory::test_default();
148
149        let first = factory.create_component_clock();
150        let second = factory.create_component_clock();
151
152        assert!(!Rc::ptr_eq(&first, &second));
153    }
154
155    #[rstest]
156    fn test_component_clock_starts_at_primary_time() {
157        let factory = ClockFactory::test_default();
158        let primary = factory.clock();
159        primary
160            .borrow_mut()
161            .as_any_mut()
162            .downcast_mut::<VirtualClock>()
163            .unwrap()
164            .set_time(42u64.into());
165        let first = factory.create_component_clock();
166        primary
167            .borrow_mut()
168            .as_any_mut()
169            .downcast_mut::<VirtualClock>()
170            .unwrap()
171            .set_time(84u64.into());
172        let second = factory.create_component_clock();
173
174        assert_eq!(first.borrow().timestamp_ns().as_u64(), 42);
175        assert_eq!(second.borrow().timestamp_ns().as_u64(), 84);
176        assert!(!Rc::ptr_eq(&primary, &first));
177        assert!(!Rc::ptr_eq(&first, &second));
178    }
179
180    #[rstest]
181    fn test_for_environment_backtest_uses_test_clock() {
182        let factory = ClockFactory::for_environment(Environment::Backtest);
183        let clock = factory.clock();
184
185        assert!(clock.borrow_mut().as_any_mut().is::<VirtualClock>());
186    }
187
188    #[rstest]
189    fn test_default_uses_test_clock() {
190        let factory = ClockFactory::test_default();
191        let clock = factory.clock();
192
193        assert!(clock.borrow_mut().as_any_mut().is::<VirtualClock>());
194    }
195}