Skip to main content

nautilus_common/live/
timer.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//! Live timer implementation using Tokio for real-time scheduling.
17
18use std::{
19    num::NonZeroU64,
20    sync::{
21        Arc,
22        atomic::{self, AtomicU64},
23    },
24};
25
26#[cfg(feature = "python")]
27use nautilus_core::consts::NAUTILUS_PREFIX;
28use nautilus_core::{
29    UUID4, UnixNanos,
30    correctness::{FAILED, check_valid_string_utf8},
31    datetime::floor_to_nearest_microsecond,
32    time::get_atomic_clock_realtime,
33};
34#[cfg(feature = "python")]
35use pyo3::{Py, PyAny, Python};
36use tokio::{
37    task::JoinHandle,
38    time::{Duration, Instant},
39};
40use ustr::Ustr;
41
42use super::runtime::get_runtime;
43use crate::{
44    runner::TimeEventSender,
45    timer::{TimeEvent, TimeEventCallback, TimeEventHandler},
46};
47
48/// A live timer for use with a `LiveClock`.
49///
50/// `LiveTimer` triggers events at specified intervals in a real-time environment,
51/// using Tokio's async runtime to handle scheduling and execution.
52///
53/// # Threading
54///
55/// The timer runs on the runtime thread that created it and dispatches events across threads as needed.
56#[derive(Debug)]
57pub struct LiveTimer {
58    /// The name of the timer.
59    pub name: Ustr,
60    /// The start time of the timer in UNIX nanoseconds.
61    pub interval_ns: NonZeroU64,
62    /// The start time of the timer in UNIX nanoseconds.
63    pub start_time_ns: UnixNanos,
64    /// The optional stop time of the timer in UNIX nanoseconds.
65    pub stop_time_ns: Option<UnixNanos>,
66    /// If the timer should fire immediately at start time.
67    pub fire_immediately: bool,
68    next_time_ns: Arc<AtomicU64>,
69    callback: TimeEventCallback,
70    task_handle: Option<JoinHandle<()>>,
71    sender: Option<Arc<dyn TimeEventSender>>,
72}
73
74impl LiveTimer {
75    /// Creates a new [`LiveTimer`] instance.
76    ///
77    /// # Panics
78    ///
79    /// Panics if `name` is not a valid string.
80    #[allow(clippy::too_many_arguments)]
81    #[must_use]
82    pub fn new(
83        name: Ustr,
84        interval_ns: NonZeroU64,
85        start_time_ns: UnixNanos,
86        stop_time_ns: Option<UnixNanos>,
87        callback: TimeEventCallback,
88        fire_immediately: bool,
89        sender: Option<Arc<dyn TimeEventSender>>,
90    ) -> Self {
91        check_valid_string_utf8(name, stringify!(name)).expect(FAILED);
92
93        let next_time_ns = if fire_immediately {
94            start_time_ns.as_u64()
95        } else {
96            start_time_ns.as_u64() + interval_ns.get()
97        };
98
99        log::debug!("Creating timer '{name}'");
100
101        Self {
102            name,
103            interval_ns,
104            start_time_ns,
105            stop_time_ns,
106            fire_immediately,
107            next_time_ns: Arc::new(AtomicU64::new(next_time_ns)),
108            callback,
109            task_handle: None,
110            sender,
111        }
112    }
113
114    /// Returns the next time in UNIX nanoseconds when the timer will fire.
115    ///
116    /// Provides the scheduled time for the next event based on the current state of the timer.
117    #[must_use]
118    pub fn next_time_ns(&self) -> UnixNanos {
119        UnixNanos::from(self.next_time_ns.load(atomic::Ordering::SeqCst))
120    }
121
122    /// Returns whether the timer is expired.
123    ///
124    /// An expired timer will not trigger any further events.
125    /// A timer that has not been started is not expired.
126    #[must_use]
127    pub fn is_expired(&self) -> bool {
128        self.task_handle
129            .as_ref()
130            .is_some_and(tokio::task::JoinHandle::is_finished)
131    }
132
133    /// Starts the timer.
134    ///
135    /// Time events will begin triggering at the specified intervals.
136    /// The generated events are handled by the provided callback function.
137    ///
138    /// # Panics
139    ///
140    /// Panics if using a Rust callback (`Rust` or `RustLocal`) without a `TimeEventSender`.
141    #[allow(unused_variables)]
142    pub fn start(&mut self) {
143        let event_name = self.name;
144        let stop_time_ns = self.stop_time_ns;
145        let interval_ns = self.interval_ns.get();
146        let callback = self.callback.clone();
147
148        // Get current time
149        let clock = get_atomic_clock_realtime();
150        let now_ns = clock.get_time_ns();
151
152        // Check if the timer's alert time is in the past and adjust if needed
153        let now_raw = now_ns.as_u64();
154        let mut observed_next = self.next_time_ns.load(atomic::Ordering::SeqCst);
155
156        if observed_next <= now_raw {
157            loop {
158                match self.next_time_ns.compare_exchange(
159                    observed_next,
160                    now_raw,
161                    atomic::Ordering::SeqCst,
162                    atomic::Ordering::SeqCst,
163                ) {
164                    Ok(_) => {
165                        if observed_next < now_raw {
166                            let original = UnixNanos::from(observed_next);
167                            log::warn!(
168                                "Timer '{event_name}' alert time {} was in the past, adjusted to current time for immediate fire",
169                                original.to_rfc3339(),
170                            );
171                        }
172                        observed_next = now_raw;
173                        break;
174                    }
175                    Err(actual) => {
176                        observed_next = actual;
177                        if observed_next > now_raw {
178                            break;
179                        }
180                    }
181                }
182            }
183        }
184
185        // Floor the next time to the nearest microsecond which is within the timers accuracy
186        let mut next_time_ns = UnixNanos::from(floor_to_nearest_microsecond(observed_next));
187        let next_time_atomic = self.next_time_ns.clone();
188        next_time_atomic.store(next_time_ns.as_u64(), atomic::Ordering::SeqCst);
189
190        let sender = self.sender.clone();
191
192        let rt = get_runtime();
193        let handle = rt.spawn(async move {
194            let clock = get_atomic_clock_realtime();
195
196            // 1-millisecond delay to account for the overhead of initializing a tokio timer
197            let overhead = Duration::from_millis(1);
198            let delay_ns = next_time_ns.saturating_sub(now_ns.as_u64());
199            let mut delay = Duration::from_nanos(delay_ns);
200
201            // Subtract the estimated startup overhead; saturating to zero for sub-ms delays
202            if delay > overhead {
203                delay -= overhead;
204            } else {
205                delay = Duration::from_nanos(0);
206            }
207
208            let start = Instant::now() + delay;
209
210            let mut timer = tokio::time::interval_at(start, Duration::from_nanos(interval_ns));
211
212            loop {
213                // SAFETY: `timer.tick` is cancellation safe, if the cancel branch completes
214                // first then no tick has been consumed (no event was ready).
215                timer.tick().await;
216                let now_ns = clock.get_time_ns();
217
218                let event = TimeEvent::new(event_name, UUID4::new(), next_time_ns, now_ns);
219
220                match callback {
221                    #[cfg(feature = "python")]
222                    TimeEventCallback::Python(ref callback) => {
223                        call_python_with_time_event(event, callback);
224                    }
225                    TimeEventCallback::Rust(_) | TimeEventCallback::RustLocal(_) => {
226                        debug_assert!(
227                            sender.is_some(),
228                            "LiveTimer with Rust callback requires TimeEventSender"
229                        );
230                        let sender = sender
231                            .as_ref()
232                            .expect("timer event sender was unset for Rust callback system");
233
234                        // TODO: This clone happens on a Tokio worker thread. For `RustLocal`
235                        // callbacks containing `Rc`, this violates thread safety (Rc::clone
236                        // is not thread-safe). The callback should be stored separately and
237                        // looked up by timer name on the receiving thread, rather than being
238                        // cloned here. This affects any code using RustLocal with LiveTimer.
239                        let handler = TimeEventHandler::new(event, callback.clone());
240                        sender.send(handler);
241                    }
242                }
243
244                // Prepare next time interval
245                next_time_ns += interval_ns;
246                next_time_atomic.store(next_time_ns.as_u64(), atomic::Ordering::SeqCst);
247
248                // Check if expired
249                if let Some(stop_time_ns) = stop_time_ns
250                    && std::cmp::max(next_time_ns, now_ns) >= stop_time_ns
251                {
252                    break; // Timer expired
253                }
254            }
255        });
256
257        self.task_handle = Some(handle);
258    }
259
260    /// Cancels the timer.
261    ///
262    /// The timer will not generate a final event.
263    pub fn cancel(&mut self) {
264        log::debug!("Cancel timer '{}'", self.name);
265        if let Some(ref handle) = self.task_handle {
266            handle.abort();
267        }
268    }
269}
270
271#[cfg(feature = "python")]
272fn call_python_with_time_event(event: TimeEvent, callback: &Py<PyAny>) {
273    use nautilus_core::python::IntoPyObjectNautilusExt;
274    use pyo3::types::PyCapsule;
275
276    Python::attach(|py| {
277        // Create a new PyCapsule that owns `event` and registers a destructor so
278        // the contained `TimeEvent` is properly freed once the capsule is
279        // garbage-collected by Python. Without the destructor the memory would
280        // leak because the capsule would not know how to drop the Rust value.
281
282        // Register a destructor that simply drops the `TimeEvent` once the
283        // capsule is freed on the Python side.
284        let capsule: Py<PyAny> = PyCapsule::new_with_destructor(py, event, None, |_, _| {})
285            .expect("Error creating `PyCapsule`")
286            .into_py_any_unwrap(py);
287
288        match callback.call1(py, (capsule,)) {
289            Ok(_) => {}
290            Err(e) => eprintln!("{NAUTILUS_PREFIX} Error on callback: {e:?}"),
291        }
292    });
293}
294
295#[cfg(test)]
296mod tests {
297    use std::{num::NonZeroU64, sync::Arc};
298
299    use nautilus_core::{UnixNanos, time::get_atomic_clock_realtime};
300    use rstest::*;
301    use ustr::Ustr;
302
303    use super::LiveTimer;
304    use crate::{
305        runner::TimeEventSender,
306        timer::{TimeEventCallback, TimeEventHandler},
307    };
308
309    #[rstest]
310    fn test_live_timer_fire_immediately_field() {
311        let timer = LiveTimer::new(
312            Ustr::from("TEST_TIMER"),
313            NonZeroU64::new(1000).unwrap(),
314            UnixNanos::from(100),
315            None,
316            TimeEventCallback::from(|_| {}),
317            true, // fire_immediately = true
318            None, // time_event_sender
319        );
320
321        // Verify the field is set correctly
322        assert!(timer.fire_immediately);
323
324        // With fire_immediately=true, next_time_ns should be start_time_ns
325        assert_eq!(timer.next_time_ns(), UnixNanos::from(100));
326    }
327
328    #[rstest]
329    fn test_live_timer_fire_immediately_false_field() {
330        let timer = LiveTimer::new(
331            Ustr::from("TEST_TIMER"),
332            NonZeroU64::new(1000).unwrap(),
333            UnixNanos::from(100),
334            None,
335            TimeEventCallback::from(|_| {}),
336            false, // fire_immediately = false
337            None,  // time_event_sender
338        );
339
340        // Verify the field is set correctly
341        assert!(!timer.fire_immediately);
342
343        // With fire_immediately=false, next_time_ns should be start_time_ns + interval
344        assert_eq!(timer.next_time_ns(), UnixNanos::from(1100));
345    }
346
347    #[rstest]
348    fn test_live_timer_adjusts_past_due_start_time() {
349        #[derive(Debug)]
350        struct NoopSender;
351
352        impl TimeEventSender for NoopSender {
353            fn send(&self, _handler: TimeEventHandler) {}
354        }
355
356        let sender = Arc::new(NoopSender);
357        let mut timer = LiveTimer::new(
358            Ustr::from("PAST_TIMER"),
359            NonZeroU64::new(1).unwrap(),
360            UnixNanos::from(0),
361            None,
362            TimeEventCallback::from(|_| {}),
363            true,
364            Some(sender),
365        );
366
367        let before = get_atomic_clock_realtime().get_time_ns();
368
369        timer.start();
370
371        assert!(timer.next_time_ns() >= before);
372
373        timer.cancel();
374    }
375}