Skip to main content

nautilus_common/python/
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
16use std::str::FromStr;
17
18use nautilus_core::{
19    UUID4, UnixNanos,
20    python::{IntoPyObjectNautilusExt, to_pyvalue_err},
21};
22use pyo3::{
23    IntoPyObjectExt,
24    basic::CompareOp,
25    prelude::*,
26    types::{PyInt, PyString, PyTuple},
27};
28use ustr::Ustr;
29
30use crate::timer::TimeEvent;
31
32#[pymethods]
33#[pyo3_stub_gen::derive::gen_stub_pymethods]
34impl TimeEvent {
35    /// Represents a named timer event.
36    ///
37    /// `ts_event` records the scheduled event time, while `ts_init` records
38    /// when the event instance was initialized.
39    #[new]
40    fn py_new(name: &str, event_id: UUID4, ts_event: u64, ts_init: u64) -> Self {
41        Self::new(Ustr::from(name), event_id, ts_event.into(), ts_init.into())
42    }
43
44    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
45        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
46
47        let ts_event = py_tuple.get_item(2)?.cast::<PyInt>()?.extract::<u64>()?;
48        let ts_init: u64 = py_tuple.get_item(3)?.cast::<PyInt>()?.extract::<u64>()?;
49
50        self.name = Ustr::from(
51            py_tuple
52                .get_item(0)?
53                .cast::<PyString>()?
54                .extract::<&str>()?,
55        );
56        self.event_id = UUID4::from_str(
57            py_tuple
58                .get_item(1)?
59                .cast::<PyString>()?
60                .extract::<&str>()?,
61        )
62        .map_err(to_pyvalue_err)?;
63        self.ts_event = ts_event.into();
64        self.ts_init = ts_init.into();
65
66        Ok(())
67    }
68
69    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
70        (
71            self.name.to_string(),
72            self.event_id.to_string(),
73            self.ts_event.as_u64(),
74            self.ts_init.as_u64(),
75        )
76            .into_py_any(py)
77    }
78
79    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
80        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
81        let state = self.__getstate__(py)?;
82        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
83    }
84
85    #[staticmethod]
86    #[pyo3(name = "_safe_constructor")]
87    fn py_safe_constructor() -> Self {
88        Self::new(
89            Ustr::from("NULL"),
90            UUID4::new(),
91            UnixNanos::default(),
92            UnixNanos::default(),
93        )
94    }
95
96    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
97        match op {
98            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
99            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
100            _ => py.NotImplemented(),
101        }
102    }
103
104    fn __repr__(&self) -> String {
105        self.to_string()
106    }
107
108    #[getter]
109    #[pyo3(name = "name")]
110    fn py_name(&self) -> String {
111        self.name.to_string()
112    }
113
114    #[getter]
115    #[pyo3(name = "event_id")]
116    const fn py_event_id(&self) -> UUID4 {
117        self.event_id
118    }
119
120    #[getter]
121    #[pyo3(name = "ts_event")]
122    const fn py_ts_event(&self) -> u64 {
123        self.ts_event.as_u64()
124    }
125
126    #[getter]
127    #[pyo3(name = "ts_init")]
128    const fn py_ts_init(&self) -> u64 {
129        self.ts_init.as_u64()
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use std::{num::NonZeroU64, sync::Arc, time::Duration};
136
137    use nautilus_core::{
138        DurationNanos, UnixNanos, datetime::NANOSECONDS_IN_MILLISECOND,
139        python::IntoPyObjectNautilusExt, time::get_atomic_clock_realtime,
140    };
141    use pyo3::prelude::*;
142
143    use crate::{
144        live::timer::LiveTimer,
145        runner::{TimeEventMessage, TimeEventSender, set_time_event_sender},
146        testing::wait_until,
147        timer::{TimeEvent, TimeEventCallback},
148    };
149
150    #[pyfunction]
151    const fn receive_event(_py: Python, _event: TimeEvent) {
152        // TODO: Assert the length of a handler vec
153    }
154
155    #[derive(Debug)]
156    struct TestTimeEventSender;
157
158    impl TimeEventSender for TestTimeEventSender {
159        fn send(&self, _message: TimeEventMessage) {
160            // Test implementation - just ignore the events
161        }
162    }
163
164    #[tokio::test]
165    async fn test_live_timer_starts_and_stops() {
166        set_time_event_sender(Arc::new(TestTimeEventSender));
167
168        Python::initialize();
169        let callback = Python::attach(|py| {
170            let callable = wrap_pyfunction!(receive_event, py).unwrap();
171            let callable = callable.into_py_any_unwrap(py);
172            TimeEventCallback::from(callable)
173        });
174
175        // Create a new LiveTimer with no stop time
176        let clock = get_atomic_clock_realtime();
177        let start_time = clock.get_time_ns();
178        let interval_ns = NonZeroU64::new(100 * NANOSECONDS_IN_MILLISECOND).unwrap();
179
180        let test_sender = Arc::new(TestTimeEventSender);
181        let mut timer = LiveTimer::new(
182            "TEST_TIMER".into(),
183            interval_ns,
184            start_time,
185            None,
186            callback,
187            false,
188            Some(test_sender),
189        );
190
191        let next_time_ns = timer.next_time_ns();
192        timer.start();
193
194        // Wait for timer to run
195        tokio::time::sleep(Duration::from_millis(300)).await;
196
197        timer.cancel();
198        assert!(timer.is_expired(), "Timer should be expired after cancel");
199        assert!(timer.next_time_ns() > next_time_ns);
200    }
201
202    #[tokio::test]
203    async fn test_live_timer_with_stop_time() {
204        set_time_event_sender(Arc::new(TestTimeEventSender));
205
206        Python::initialize();
207        let callback = Python::attach(|py| {
208            let callable = wrap_pyfunction!(receive_event, py).unwrap();
209            let callable = callable.into_py_any_unwrap(py);
210            TimeEventCallback::from(callable)
211        });
212
213        // Create a new LiveTimer with a stop time
214        let clock = get_atomic_clock_realtime();
215        let start_time = clock.get_time_ns();
216        let interval_ns = NonZeroU64::new(100 * NANOSECONDS_IN_MILLISECOND).unwrap();
217        let stop_time = start_time + DurationNanos::from_millis(500);
218
219        let test_sender = Arc::new(TestTimeEventSender);
220        let mut timer = LiveTimer::new(
221            "TEST_TIMER".into(),
222            interval_ns,
223            start_time,
224            Some(stop_time),
225            callback,
226            false,
227            Some(test_sender),
228        );
229
230        let next_time_ns = timer.next_time_ns();
231        timer.start();
232
233        // Wait for a longer time than the stop time
234        tokio::time::sleep(Duration::from_secs(1)).await;
235
236        wait_until(|| timer.is_expired(), Duration::from_secs(2));
237        assert!(timer.next_time_ns() > next_time_ns);
238    }
239
240    #[tokio::test]
241    async fn test_live_timer_with_zero_interval_and_immediate_stop_time() {
242        set_time_event_sender(Arc::new(TestTimeEventSender));
243
244        Python::initialize();
245        let callback = Python::attach(|py| {
246            let callable = wrap_pyfunction!(receive_event, py).unwrap();
247            let callable = callable.into_py_any_unwrap(py);
248            TimeEventCallback::from(callable)
249        });
250
251        // Create a new LiveTimer with a stop time
252        let clock = get_atomic_clock_realtime();
253        let start_time = UnixNanos::default();
254        let interval_ns = NonZeroU64::new(1).unwrap();
255        let stop_time = clock.get_time_ns();
256
257        let test_sender = Arc::new(TestTimeEventSender);
258        let mut timer = LiveTimer::new(
259            "TEST_TIMER".into(),
260            interval_ns,
261            start_time,
262            Some(stop_time),
263            callback,
264            false,
265            Some(test_sender),
266        );
267
268        timer.start();
269
270        wait_until(|| timer.is_expired(), Duration::from_secs(2));
271    }
272}