Skip to main content

nautilus_common/clock/
mod.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//! Real-time and virtual `Clock` implementations.
17//!
18//! Defines the [`Clock`] contract, the user-facing [`ClockApi`] facade, and the deterministic
19//! [`VirtualClock`] used for controlled time advancement. Shared validation and callback registration
20//! support virtual and live clock implementations.
21
22mod api;
23#[path = "virtual.rs"]
24mod virtual_clock;
25
26#[cfg(test)]
27mod tests;
28
29use std::{
30    any::Any,
31    collections::BTreeMap,
32    fmt::Debug,
33    sync::{
34        Arc,
35        atomic::{AtomicBool, Ordering},
36    },
37    time::Duration,
38};
39
40use ahash::AHashMap;
41pub use api::ClockApi; // Re-export
42use jiff::Timestamp;
43use nautilus_core::{
44    DurationNanos, UnixNanos,
45    correctness::{check_positive_u64, check_valid_string_utf8},
46    datetime::try_datetime_to_unix_nanos,
47};
48use ustr::Ustr;
49pub use virtual_clock::VirtualClock; // Re-export
50
51use crate::timer::{
52    TimeEvent, TimeEventCallback, TimeEventHandler, Timer, TimerInterval, TimerSchedule,
53    create_valid_interval,
54};
55
56/// Provides time access, timer scheduling, and callback registration.
57///
58/// An active timer is one that has not expired.
59pub trait Clock: Debug + Any {
60    /// Returns the current UTC timestamp.
61    fn utc_now(&self) -> Timestamp {
62        self.timestamp_ns().to_datetime_utc()
63    }
64
65    /// Returns the current UNIX timestamp in nanoseconds (ns).
66    fn timestamp_ns(&self) -> UnixNanos;
67
68    /// Returns the current UNIX timestamp in microseconds (μs).
69    fn timestamp_us(&self) -> u64;
70
71    /// Returns the current UNIX timestamp in milliseconds (ms).
72    fn timestamp_ms(&self) -> u64;
73
74    /// Returns the current UNIX timestamp in seconds.
75    fn timestamp(&self) -> f64;
76
77    /// Returns the names of active timers in the clock.
78    fn timer_names(&self) -> Vec<&str>;
79
80    /// Returns the count of active timers in the clock.
81    fn timer_count(&self) -> usize;
82
83    /// Returns whether an active timer named `name` exists.
84    fn timer_exists(&self, name: &Ustr) -> bool;
85
86    /// Registers the callback used when a timer has no named callback.
87    fn register_default_handler(&mut self, callback: TimeEventCallback);
88
89    /// Cancels the registered default event handler, if any.
90    ///
91    /// Queued time event handlers no longer invoke the default callback.
92    ///
93    /// Releases the held callback so any Python object owned by it can be dropped.
94    /// `Trader::release_component` calls this at component retirement to break the cycle
95    /// between a Python component and its clock: the clock holds the callback as a
96    /// `Py<PyAny>` that Python's cycle collector cannot reach through.
97    fn cancel_default_handler(&mut self);
98
99    /// Cancels all registered named event callbacks, preserving the default handler.
100    ///
101    /// Queued time event handlers no longer invoke named callbacks.
102    ///
103    /// Releases callbacks registered via [`Clock::set_time_alert_ns`] or
104    /// [`Clock::set_timer_ns`] with an explicit `callback` argument.
105    /// `Trader::release_component` calls this at component retirement, breaking the same
106    /// cycle as [`Clock::cancel_default_handler`].
107    fn cancel_callbacks(&mut self);
108
109    /// Sets a timer to alert at the specified time.
110    ///
111    /// See [`Clock::set_time_alert_ns`] for flag semantics.
112    ///
113    /// # Callback
114    ///
115    /// - `Some(callback)` registers and uses `callback` for the named alert.
116    /// - `None` uses a callback registered under `name`, falling back to the default callback.
117    ///
118    /// # Errors
119    ///
120    /// Returns an error if:
121    /// - `name` is invalid.
122    /// - `alert_time` is before the UNIX epoch or outside the [`UnixNanos`] range.
123    /// - The alert is in the past and `allow_past` is `Some(false)`.
124    /// - No explicit, named, or default callback is available.
125    fn set_time_alert(
126        &mut self,
127        name: &str,
128        alert_time: Timestamp,
129        callback: Option<TimeEventCallback>,
130        allow_past: Option<bool>,
131    ) -> anyhow::Result<()> {
132        self.set_time_alert_ns(
133            name,
134            try_datetime_to_unix_nanos(alert_time)?,
135            callback,
136            allow_past,
137        )
138    }
139
140    /// Sets a timer to alert at the specified time.
141    ///
142    /// Any active timer registered under the same `name` is canceled with a warning before the
143    /// new alert is scheduled. `allow_past` defaults to `true`.
144    ///
145    /// # Flags
146    ///
147    /// | `allow_past` | Behavior                                                               |
148    /// | ------------ | ---------------------------------------------------------------------- |
149    /// | `true`       | A past alert is moved to the current time and fires immediately.       |
150    /// | `false`      | An alert earlier than the current time returns an error.               |
151    ///
152    /// # Callback
153    ///
154    /// - `Some(callback)` registers and uses `callback` for the named alert.
155    /// - `None` uses a callback registered under `name`, falling back to the default callback.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if:
160    /// - `name` is invalid.
161    /// - `alert_time_ns` is earlier than now and `allow_past` is `Some(false)`.
162    /// - No explicit, named, or default callback is available.
163    fn set_time_alert_ns(
164        &mut self,
165        name: &str,
166        alert_time_ns: UnixNanos,
167        callback: Option<TimeEventCallback>,
168        allow_past: Option<bool>,
169    ) -> anyhow::Result<()>;
170
171    /// Sets a timer to fire time events at every interval between the start and stop times.
172    ///
173    /// Any active timer registered under the same `name` is canceled with a warning before the
174    /// new timer is scheduled.
175    ///
176    /// See [`Clock::set_timer_ns`] for flag semantics.
177    ///
178    /// # Callback
179    ///
180    /// - `Some(callback)` registers and uses `callback` for the named timer.
181    /// - `None` uses a callback registered under `name`, falling back to the default callback.
182    ///
183    /// # Errors
184    ///
185    /// Returns an error if:
186    /// - `name` is invalid.
187    /// - `interval` is zero or exceeds `u64::MAX` nanoseconds.
188    /// - `start_time` or `stop_time` is before the UNIX epoch or out of range for `UnixNanos`.
189    /// - The first event timestamp is out of range for `UnixNanos`.
190    /// - The first event is in the past when past times are disallowed.
191    /// - The stop time is not after the start time.
192    /// - The stop time is not after the current time when past times are disallowed.
193    /// - No explicit, named, or default callback is available.
194    #[expect(clippy::too_many_arguments)]
195    fn set_timer(
196        &mut self,
197        name: &str,
198        interval: Duration,
199        start_time: Option<Timestamp>,
200        stop_time: Option<Timestamp>,
201        callback: Option<TimeEventCallback>,
202        allow_past: Option<bool>,
203        fire_immediately: Option<bool>,
204    ) -> anyhow::Result<()> {
205        self.set_timer_ns(
206            name,
207            duration_to_nanos(interval)?,
208            start_time.map(try_datetime_to_unix_nanos).transpose()?,
209            stop_time.map(try_datetime_to_unix_nanos).transpose()?,
210            callback,
211            allow_past,
212            fire_immediately,
213        )
214    }
215
216    /// Sets a timer to fire time events at every interval between the start and stop times.
217    ///
218    /// Any active timer registered under the same `name` is canceled with a warning before the
219    /// new timer is scheduled. `allow_past` defaults to `true`, and `fire_immediately` defaults to
220    /// `false`.
221    ///
222    /// # Start Time
223    ///
224    /// - `None` or `Some(0)`: Uses the current time as start time.
225    /// - `Some(non_zero)`: Uses the specified timestamp as start time.
226    ///
227    /// # Flags
228    ///
229    /// | `allow_past` | `fire_immediately` | First event behavior                                |
230    /// | ------------ | ------------------ | --------------------------------------------------- |
231    /// | `true`       | `true`             | Fires at the start time, including a past start.    |
232    /// | `true`       | `false`            | Fires one interval after the start, including past. |
233    /// | `false`      | `true`             | A past start time returns an error.                 |
234    /// | `false`      | `false`            | A past first event returns an error.                |
235    ///
236    /// # Callback
237    ///
238    /// - `Some(callback)` registers and uses `callback` for the named timer.
239    /// - `None` uses a callback registered under `name`, falling back to the default callback.
240    ///
241    /// # Errors
242    ///
243    /// Returns an error if:
244    /// - `name` is invalid.
245    /// - `interval_ns` is zero.
246    /// - `start_time_ns + interval_ns` is out of range for `UnixNanos` when not firing immediately.
247    /// - The first event is in the past when past times are disallowed.
248    /// - The stop time is not after the start time.
249    /// - The stop time is not after the current time when past times are disallowed.
250    /// - No explicit, named, or default callback is available.
251    #[expect(clippy::too_many_arguments)]
252    fn set_timer_ns(
253        &mut self,
254        name: &str,
255        interval_ns: DurationNanos,
256        start_time_ns: Option<UnixNanos>,
257        stop_time_ns: Option<UnixNanos>,
258        callback: Option<TimeEventCallback>,
259        allow_past: Option<bool>,
260        fire_immediately: Option<bool>,
261    ) -> anyhow::Result<()>;
262
263    /// Registers a recurring source of absolute UTC deadlines.
264    ///
265    /// The schedule supplies its nominal start and deadlines. The clock owns event delivery,
266    /// cancellation, replacement, and the inclusive stop time. See [`Clock::set_timer_ns`] for
267    /// flag and callback semantics. An explicit epoch start supplied by the schedule stays at
268    /// the UNIX epoch.
269    ///
270    /// # Errors
271    ///
272    /// Returns an error if:
273    /// - This clock does not support deadline schedules.
274    /// - `name` is invalid.
275    /// - No valid first deadline exists when not firing immediately.
276    /// - The first event is in the past when past times are disallowed.
277    /// - The stop time is not after the start time.
278    /// - The stop time is not after the current time when past times are disallowed.
279    /// - No explicit, named, or default callback is available.
280    fn set_timer_schedule(
281        &mut self,
282        name: &str,
283        schedule: Arc<dyn TimerSchedule>,
284        stop_time_ns: Option<UnixNanos>,
285        callback: Option<TimeEventCallback>,
286        allow_past: Option<bool>,
287        fire_immediately: Option<bool>,
288    ) -> anyhow::Result<()> {
289        let _ = (
290            schedule,
291            stop_time_ns,
292            callback,
293            allow_past,
294            fire_immediately,
295        );
296        anyhow::bail!("Timer '{name}' needs a clock that supports deadline schedules")
297    }
298
299    /// Returns the next trigger timestamp for the active timer named `name`.
300    ///
301    /// Returns `None` if no active timer with that name exists.
302    fn next_time_ns(&self, name: &str) -> Option<UnixNanos>;
303
304    /// Cancels the timer named `name`, if it exists.
305    fn cancel_timer(&mut self, name: &str);
306
307    /// Cancels all timers.
308    fn cancel_timers(&mut self);
309
310    /// Resets scheduling state while preserving the default callback.
311    ///
312    /// The reset clears all timers and revokes named callbacks, including queued copies.
313    /// Static clocks also reset their stored time.
314    fn reset(&mut self);
315}
316
317impl dyn Clock {
318    /// Returns a reference to this clock as `Any` for downcasting.
319    pub fn as_any(&self) -> &dyn std::any::Any {
320        self
321    }
322
323    /// Returns a mutable reference to this clock as `Any` for downcasting.
324    pub fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
325        self
326    }
327}
328
329fn duration_to_nanos(duration: Duration) -> anyhow::Result<DurationNanos> {
330    DurationNanos::try_from(duration)
331        .map_err(|_| anyhow::anyhow!("Interval exceeds u64 nanoseconds"))
332}
333
334/// Registry for timer event callbacks.
335///
336/// Provides shared callback registration and retrieval logic used by both
337/// `VirtualClock` and `LiveClock`.
338#[derive(Debug, Default)]
339pub struct CallbackRegistry {
340    default_callback: Option<TimeEventCallback>,
341    callbacks: AHashMap<Ustr, TimeEventCallback>,
342    default_canceled: Option<Arc<AtomicBool>>,
343    callbacks_canceled: Option<Arc<AtomicBool>>,
344}
345
346impl CallbackRegistry {
347    /// Creates an empty callback registry.
348    #[must_use]
349    pub fn new() -> Self {
350        Self::default()
351    }
352
353    /// Registers the callback used when no callback exists for a timer name.
354    pub fn register_default_handler(&mut self, callback: TimeEventCallback) {
355        let canceled = self.default_canceled.get_or_insert_default().clone();
356        self.default_callback = Some(callback.with_cancellation(canceled));
357    }
358
359    /// Revokes current and replaced default callbacks, including queued copies.
360    ///
361    /// Named callbacks are preserved.
362    pub fn cancel_default_handler(&mut self) {
363        if let Some(canceled) = self.default_canceled.take() {
364            canceled.store(true, Ordering::Release);
365        }
366
367        self.default_callback = None;
368    }
369
370    /// Registers a callback for `name`, replacing any existing callback for that name.
371    pub fn register_callback(&mut self, name: Ustr, callback: TimeEventCallback) {
372        let canceled = self.callbacks_canceled.get_or_insert_default().clone();
373        self.callbacks
374            .insert(name, callback.with_cancellation(canceled));
375    }
376
377    /// Returns whether a named or default callback is available for `name`.
378    #[must_use]
379    pub fn has_any_callback(&self, name: &Ustr) -> bool {
380        self.callbacks.contains_key(name) || self.default_callback.is_some()
381    }
382
383    /// Returns the callback for `name`, falling back to the default callback.
384    #[must_use]
385    pub fn get_callback(&self, name: &Ustr) -> Option<TimeEventCallback> {
386        self.callbacks
387            .get(name)
388            .cloned()
389            .or_else(|| self.default_callback.clone())
390    }
391
392    /// Creates a handler for `event` using its named callback or the default callback.
393    ///
394    /// # Panics
395    ///
396    /// Panics if neither a named nor default callback exists for the event.
397    #[must_use]
398    pub fn get_handler(&self, event: TimeEvent) -> TimeEventHandler {
399        let callback = self
400            .get_callback(&event.name)
401            .unwrap_or_else(|| panic!("Event '{}' should have associated handler", event.name));
402
403        TimeEventHandler::new(event, callback)
404    }
405
406    /// Revokes all named callbacks, including queued copies, preserving the default callback.
407    pub fn clear(&mut self) {
408        if let Some(canceled) = self.callbacks_canceled.take() {
409            canceled.store(true, Ordering::Release);
410        }
411
412        self.callbacks.clear();
413    }
414}
415
416/// Validates and normalizes parameters for a time alert.
417///
418/// `allow_past` defaults to `true`. When enabled, a past alert timestamp is replaced with
419/// `ts_now`. Returns the interned name and normalized alert timestamp.
420///
421/// # Errors
422///
423/// Returns an error if `name` is invalid or the alert is in the past when past alerts are
424/// disallowed.
425pub fn validate_and_prepare_time_alert(
426    name: &str,
427    mut alert_time_ns: UnixNanos,
428    allow_past: Option<bool>,
429    ts_now: UnixNanos,
430) -> anyhow::Result<(Ustr, UnixNanos)> {
431    check_valid_string_utf8(name, stringify!(name))?;
432
433    let name = Ustr::from(name);
434    let allow_past = allow_past.unwrap_or(true);
435
436    if alert_time_ns < ts_now {
437        if allow_past {
438            log::warn!(
439                "Timer '{name}' alert time {} was in the past, adjusted to current time for immediate firing",
440                alert_time_ns.to_rfc3339(),
441            );
442            alert_time_ns = ts_now;
443        } else {
444            anyhow::bail!(
445                "Timer '{name}' alert time {} was in the past (current time is {ts_now})",
446                alert_time_ns.to_rfc3339(),
447            );
448        }
449    }
450
451    Ok((name, alert_time_ns))
452}
453
454/// Validates and normalizes parameters for a fixed interval timer.
455///
456/// A missing or zero `start_time_ns` resolves to `ts_now`. `allow_past` defaults to `true`, and
457/// `fire_immediately` defaults to `false`. Returns the interned name, normalized start and stop
458/// times, and resolved flag values.
459///
460/// # Errors
461///
462/// Returns an error if:
463/// - `name` is invalid.
464/// - `interval_ns` is zero.
465/// - `start_time_ns + interval_ns` is out of range for [`UnixNanos`] when not firing immediately.
466/// - The first event is in the past when past times are disallowed.
467/// - The stop time is not after the normalized start time.
468/// - The stop time is not after `ts_now` when past times are disallowed.
469pub fn validate_and_prepare_timer(
470    name: &str,
471    interval_ns: DurationNanos,
472    start_time_ns: Option<UnixNanos>,
473    stop_time_ns: Option<UnixNanos>,
474    allow_past: Option<bool>,
475    fire_immediately: Option<bool>,
476    ts_now: UnixNanos,
477) -> anyhow::Result<(Ustr, UnixNanos, Option<UnixNanos>, bool, bool)> {
478    check_positive_u64(interval_ns.as_u64(), stringify!(interval_ns))?;
479    validate_and_prepare_schedule(
480        name,
481        &TimerInterval::Fixed(create_valid_interval(interval_ns)),
482        start_time_ns.filter(|start| *start != 0),
483        stop_time_ns,
484        allow_past,
485        fire_immediately,
486        ts_now,
487    )
488}
489
490// Validates native timer registration before replacing an existing timer
491pub(crate) fn validate_and_prepare_schedule(
492    name: &str,
493    interval: &TimerInterval,
494    start_time_ns: Option<UnixNanos>,
495    stop_time_ns: Option<UnixNanos>,
496    allow_past: Option<bool>,
497    fire_immediately: Option<bool>,
498    ts_now: UnixNanos,
499) -> anyhow::Result<(Ustr, UnixNanos, Option<UnixNanos>, bool, bool)> {
500    check_valid_string_utf8(name, stringify!(name))?;
501
502    let name = Ustr::from(name);
503    let allow_past = allow_past.unwrap_or(true);
504    let fire_immediately = fire_immediately.unwrap_or(false);
505
506    let start_time_ns = start_time_ns.unwrap_or(ts_now);
507    let next_event_time = if fire_immediately {
508        start_time_ns
509    } else {
510        interval
511            .next_time_after(start_time_ns, start_time_ns, &mut 0)
512            .ok_or_else(|| {
513                anyhow::anyhow!("Timer '{name}' first event time exceeds UnixNanos range")
514            })?
515    };
516
517    if !allow_past && next_event_time < ts_now {
518        anyhow::bail!(
519            "Timer '{name}' next event time {} would be in the past (current time is {ts_now})",
520            next_event_time.to_rfc3339(),
521        );
522    }
523
524    if let Some(stop_time) = stop_time_ns {
525        if stop_time <= start_time_ns {
526            anyhow::bail!(
527                "Timer '{name}' stop time {} must be after start time {}",
528                stop_time.to_rfc3339(),
529                start_time_ns.to_rfc3339(),
530            );
531        }
532
533        if !allow_past && stop_time <= ts_now {
534            anyhow::bail!(
535                "Timer '{name}' stop time {} is in the past (current time is {ts_now})",
536                stop_time.to_rfc3339(),
537            );
538        }
539    }
540
541    Ok((
542        name,
543        start_time_ns,
544        stop_time_ns,
545        allow_past,
546        fire_immediately,
547    ))
548}
549
550// Cancels and removes the active timer registered under `name`, if any.
551//
552// Shared by `VirtualClock` and `LiveClock` to enforce one active timer per name.
553pub(crate) fn replace_existing_timer<T: Timer>(timers: &mut BTreeMap<Ustr, T>, name: &Ustr) {
554    let Some(mut timer) = timers.remove(name) else {
555        return;
556    };
557
558    if timer.is_expired() {
559        return;
560    }
561
562    timer.cancel();
563    log::warn!("Timer '{name}' replaced");
564}