qubit_clock/timer/timer.rs
1// =============================================================================
2// Copyright (c) 2025 - 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Defines the asynchronous timer capability.
9
10use crate::{
11 MonotonicClock,
12 MonotonicInstant,
13 TimeError,
14 TimerFuture,
15};
16use std::time::Duration;
17
18/// Creates asynchronous notifications in one monotonic clock domain.
19///
20/// Calling [`at()`](Self::at) or [`after()`](Self::after) fixes the logical
21/// deadline and cancellation ownership before returning. The returned future
22/// waits for that fixed deadline. If the deadline is reached before the first
23/// poll, that first poll returns ready. As with every [`Future`], callers must
24/// not poll it again after it first returns ready. A backend may defer
25/// enrollment with its native scheduler until the future is polled. Dropping an
26/// incomplete future cancels the outstanding notification.
27///
28/// Every call to [`clock()`](Self::clock) on one Timer must report the same
29/// clock domain for the Timer's lifetime. Implementations must reject deadlines
30/// from a different domain with [`TimeError::ClockDomainMismatch`].
31/// [`MonotonicInstant::validate_domain`] provides the canonical validation and
32/// error construction for custom Timer implementations.
33///
34/// Timer failures have two stages: the outer [`Result`] reports registration
35/// failures, while the returned [`TimerFuture`] reports failures observed after
36/// registration, such as an unavailable scheduler worker or a Tokio runtime
37/// that shut down. Custom implementations may document additional lifecycle
38/// preconditions and panic conditions.
39pub trait Timer: Send + Sync {
40 /// Returns the monotonic clock whose domain this timer uses.
41 ///
42 /// Successive calls may return different handles, but every returned clock
43 /// must report the same domain for this Timer's lifetime.
44 ///
45 /// # Returns
46 ///
47 /// The clock retained by this timer.
48 ///
49 /// # Examples
50 ///
51 /// Discarding the retained clock is diagnosed when unused results are
52 /// denied:
53 ///
54 /// ```compile_fail
55 /// #![deny(unused_must_use)]
56 /// use qubit_clock::{MonotonicClock, StdMonotonicClock, Timer};
57 ///
58 /// let timer = StdMonotonicClock::new().new_timer();
59 /// timer.clock();
60 /// ```
61 #[must_use = "the Timer clock should be used to sample or validate deadlines"]
62 fn clock(&self) -> &dyn MonotonicClock;
63
64 /// Returns the current monotonic instant in this timer's clock domain.
65 ///
66 /// # Returns
67 ///
68 /// The current instant sampled from this timer's clock.
69 #[must_use = "the current timer instant should be used to measure or validate deadlines"]
70 #[inline(always)]
71 fn now(&self) -> MonotonicInstant {
72 self.clock().now()
73 }
74
75 /// Creates a notification for an absolute monotonic deadline.
76 ///
77 /// The deadline is fixed before this method returns. A deadline at or
78 /// before the current time produces a future that is already ready.
79 ///
80 /// # Parameters
81 ///
82 /// * `deadline` - Absolute deadline in this timer's clock domain.
83 ///
84 /// # Returns
85 ///
86 /// A future that returns `Ok(())` when `deadline` is reached. The future
87 /// returns a [`TimeError`] if the backend fails after registration.
88 ///
89 /// # Errors
90 ///
91 /// Returns [`TimeError::ClockDomainMismatch`] when `deadline` belongs to a
92 /// different clock domain. Returns another [`TimeError`] when the
93 /// notification cannot be created.
94 fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError>;
95
96 /// Registers a notification after a relative duration.
97 ///
98 /// The deadline is fixed by sampling [`clock()`](Self::clock) during this
99 /// call, not when the returned future is first polled.
100 ///
101 /// # Parameters
102 ///
103 /// * `duration` - Duration from the current monotonic instant.
104 ///
105 /// # Returns
106 ///
107 /// A future that returns `Ok(())` when the fixed deadline is reached. The
108 /// future returns a [`TimeError`] if the backend later fails.
109 ///
110 /// # Errors
111 ///
112 /// Returns [`TimeError::InstantOverflow`] when the deadline cannot be
113 /// represented. Returns any error produced while creating the notification
114 /// for that deadline.
115 #[inline]
116 fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
117 let deadline = self.now().checked_add(duration)?;
118 self.at(deadline)
119 }
120}
121
122impl<T> Timer for std::sync::Arc<T>
123where
124 T: Timer + ?Sized,
125{
126 /// Delegates access to the shared timer's clock.
127 ///
128 /// # Returns
129 ///
130 /// The clock exposed by the wrapped timer.
131 #[inline(always)]
132 fn clock(&self) -> &dyn MonotonicClock {
133 self.as_ref().clock()
134 }
135
136 /// Delegates absolute deadline registration to the shared timer.
137 ///
138 /// # Parameters
139 ///
140 /// * `deadline` - Absolute deadline in the wrapped timer's clock domain.
141 ///
142 /// # Returns
143 ///
144 /// The wrapped timer's cancellation-safe completion future.
145 ///
146 /// # Errors
147 ///
148 /// Returns any registration error reported by the wrapped timer.
149 #[inline(always)]
150 fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError> {
151 self.as_ref().at(deadline)
152 }
153
154 /// Delegates relative deadline registration to the shared timer.
155 ///
156 /// # Parameters
157 ///
158 /// * `duration` - Duration from the wrapped timer's current instant.
159 ///
160 /// # Returns
161 ///
162 /// The wrapped timer's cancellation-safe completion future.
163 ///
164 /// # Errors
165 ///
166 /// Returns any registration error reported by the wrapped timer.
167 #[inline(always)]
168 fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
169 self.as_ref().after(duration)
170 }
171}
172
173impl<T> Timer for Box<T>
174where
175 T: Timer + ?Sized,
176{
177 /// Delegates access to the boxed timer's clock.
178 ///
179 /// # Returns
180 ///
181 /// The clock exposed by the wrapped timer.
182 #[inline(always)]
183 fn clock(&self) -> &dyn MonotonicClock {
184 self.as_ref().clock()
185 }
186
187 /// Delegates absolute deadline registration to the boxed timer.
188 ///
189 /// # Parameters
190 ///
191 /// * `deadline` - Absolute deadline in the wrapped timer's clock domain.
192 ///
193 /// # Returns
194 ///
195 /// The wrapped timer's cancellation-safe completion future.
196 ///
197 /// # Errors
198 ///
199 /// Returns any registration error reported by the wrapped timer.
200 #[inline(always)]
201 fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError> {
202 self.as_ref().at(deadline)
203 }
204
205 /// Delegates relative deadline registration to the boxed timer.
206 ///
207 /// # Parameters
208 ///
209 /// * `duration` - Duration from the wrapped timer's current instant.
210 ///
211 /// # Returns
212 ///
213 /// The wrapped timer's cancellation-safe completion future.
214 ///
215 /// # Errors
216 ///
217 /// Returns any registration error reported by the wrapped timer.
218 #[inline(always)]
219 fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
220 self.as_ref().after(duration)
221 }
222}