deadline_machines 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,331 +1,32 @@
1
- #![cfg_attr(not(feature = "std"), no_std)]
1
+ //! Monotonic deadline arithmetic and cooperative cancellation trees.
2
+ //!
3
+ //! [`Deadline`] is `Copy`, allocation-free and reads no clock: the caller
4
+ //! passes `now` as a [`Duration`](core::time::Duration) since an epoch it
5
+ //! picks, and every span (timeout, extension, sleep) is a `Duration` too.
6
+ //! [`CancelToken`](cancel::CancelToken) and [`Scope`] share cancellation
7
+ //! through `Arc`, so they need the `alloc` feature. The `tokio` feature adds
8
+ //! a Tokio clock and timeout adapter, the one place this crate reads a clock.
9
+ #![no_std]
10
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
11
 
3
12
  #[cfg(feature = "alloc")]
4
13
  extern crate alloc;
5
14
 
6
15
  /// Compiles and runs the README's examples as doctests.
7
- #[cfg(doctest)]
16
+ #[cfg(all(doctest, feature = "tokio"))]
8
17
  #[doc = include_str!("../README.md")]
9
18
  struct ReadmeDoctests;
10
19
 
11
- pub const NS_PER_SECOND: u64 = 1_000_000_000;
12
-
13
- #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
14
- pub struct Instant(pub u64);
15
-
16
- pub trait Clock {
17
- fn now_ns(&self) -> u64;
18
-
19
- fn now(&self) -> Instant {
20
- Instant(self.now_ns())
21
- }
22
- }
23
-
24
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25
- pub struct Deadline {
26
- expires_at: Option<Instant>,
27
- }
28
-
29
- impl Deadline {
30
- #[must_use]
31
- pub const fn never() -> Self {
32
- Self { expires_at: None }
33
- }
34
-
35
- #[must_use]
36
- pub const fn at(instant: Instant) -> Self {
37
- Self {
38
- expires_at: Some(instant),
39
- }
40
- }
41
-
42
- #[must_use]
43
- pub const fn after(now: Instant, timeout_ns: u64) -> Self {
44
- Self::at(Instant(now.0.saturating_add(timeout_ns)))
45
- }
46
-
47
- #[must_use]
48
- pub const fn expires_at(&self) -> Option<Instant> {
49
- self.expires_at
50
- }
51
-
52
- #[must_use]
53
- pub const fn remaining_ns(&self, now: Instant) -> Option<u64> {
54
- match self.expires_at {
55
- Some(expiry) => Some(expiry.0.saturating_sub(now.0)),
56
- None => None,
57
- }
58
- }
59
-
60
- #[must_use]
61
- pub const fn is_expired(&self, now: Instant) -> bool {
62
- matches!(self.remaining_ns(now), Some(0))
63
- }
64
-
65
- #[must_use]
66
- pub const fn derive(&self, now: Instant, timeout_ns: u64) -> Self {
67
- let candidate = Instant(now.0.saturating_add(timeout_ns));
68
- match self.expires_at {
69
- None => Self::at(candidate),
70
- Some(parent) if candidate.0 < parent.0 => Self::at(candidate),
71
- Some(parent) => Self::at(parent),
72
- }
73
- }
74
-
75
- #[must_use]
76
- pub const fn tighten(&self, other: Self) -> Self {
77
- match (self.expires_at, other.expires_at) {
78
- (None, any) | (any, None) => Self { expires_at: any },
79
- (Some(a), Some(b)) if a.0 < b.0 => Self::at(a),
80
- (Some(_), Some(b)) => Self::at(b),
81
- }
82
- }
83
-
84
- #[must_use]
85
- pub const fn clamp_sleep_ns(&self, now: Instant, requested_ns: u64) -> u64 {
86
- match self.remaining_ns(now) {
87
- Some(left) if left < requested_ns => left,
88
- _ => requested_ns,
89
- }
90
- }
91
- }
92
-
93
20
  #[cfg(feature = "alloc")]
94
- pub mod cancel {
95
- use alloc::sync::Arc;
96
- use core::sync::atomic::{AtomicBool, Ordering};
97
-
98
- #[derive(Debug)]
99
- struct Node {
100
- cancelled: AtomicBool,
101
- parent: Option<Arc<Self>>,
102
- }
103
-
104
- impl Node {
105
- fn is_cancelled(&self) -> bool {
106
- self.cancelled.load(Ordering::Acquire)
107
- || self
108
- .parent
109
- .as_ref()
110
- .is_some_and(|parent| parent.is_cancelled())
111
- }
112
- }
113
-
114
- #[derive(Debug, Clone)]
115
- pub struct CancelToken {
116
- node: Arc<Node>,
117
- }
118
-
119
- impl CancelToken {
120
- #[must_use]
121
- pub fn root() -> Self {
122
- Self {
123
- node: Arc::new(Node {
124
- cancelled: AtomicBool::new(false),
125
- parent: None,
126
- }),
127
- }
128
- }
129
-
130
- #[must_use]
131
- pub fn child(&self) -> Self {
132
- Self {
133
- node: Arc::new(Node {
134
- cancelled: AtomicBool::new(false),
135
- parent: Some(Arc::clone(&self.node)),
136
- }),
137
- }
138
- }
139
-
140
- pub fn cancel(&self) {
141
- self.node.cancelled.store(true, Ordering::Release);
142
- }
143
-
144
- #[must_use]
145
- pub fn is_cancelled(&self) -> bool {
146
- self.node.is_cancelled()
147
- }
148
- }
149
-
150
- impl Default for CancelToken {
151
- fn default() -> Self {
152
- Self::root()
153
- }
154
- }
155
- }
156
-
157
- /// Why a [`Scope`] stopped admitting work.
158
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
159
- pub enum Stopped {
160
- /// The budget ran out.
161
- Exceeded,
162
- /// Someone upstream gave up.
163
- Cancelled,
164
- }
165
-
166
- impl core::fmt::Display for Stopped {
167
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
168
- f.write_str(match self {
169
- Self::Exceeded => "deadline exceeded",
170
- Self::Cancelled => "deadline cancelled",
171
- })
172
- }
173
- }
174
-
175
- impl core::error::Error for Stopped {}
176
-
21
+ pub mod cancel;
22
+ mod deadline;
23
+ mod refusal;
177
24
  #[cfg(feature = "alloc")]
178
- mod scope {
179
- use super::{Deadline, Instant, Stopped, cancel::CancelToken};
180
-
181
- /// A budget and a cancellation handle as one value, which is what a retry
182
- /// policy or a circuit breaker actually needs to consult.
183
- ///
184
- /// ```
185
- /// use deadline_machines::{Deadline, Instant, Scope, Stopped};
186
- ///
187
- /// let now = Instant(0);
188
- /// let request = Scope::new(Deadline::after(now, 5_000));
189
- ///
190
- /// let attempt = request.derive(now, 9_000);
191
- /// assert_eq!(attempt.deadline(), request.deadline());
192
- ///
193
- /// request.cancel();
194
- /// assert_eq!(attempt.check(now), Err(Stopped::Cancelled));
195
- /// ```
196
- #[derive(Debug, Clone)]
197
- pub struct Scope {
198
- deadline: Deadline,
199
- token: CancelToken,
200
- }
201
-
202
- impl Scope {
203
- #[must_use]
204
- pub fn new(deadline: Deadline) -> Self {
205
- Self {
206
- deadline,
207
- token: CancelToken::root(),
208
- }
209
- }
210
-
211
- /// A scope with no time limit, cancellable only.
212
- #[must_use]
213
- pub fn never() -> Self {
214
- Self::new(Deadline::never())
215
- }
216
-
217
- #[must_use]
218
- pub const fn deadline(&self) -> Deadline {
219
- self.deadline
220
- }
221
-
222
- #[must_use]
223
- pub const fn remaining_ns(&self, now: Instant) -> Option<u64> {
224
- self.deadline.remaining_ns(now)
225
- }
226
-
227
- #[must_use]
228
- pub fn is_cancelled(&self) -> bool {
229
- self.token.is_cancelled()
230
- }
231
-
232
- #[must_use]
233
- pub const fn is_expired(&self, now: Instant) -> bool {
234
- self.deadline.is_expired(now)
235
- }
236
-
237
- #[must_use]
238
- pub fn is_done(&self, now: Instant) -> bool {
239
- self.is_cancelled() || self.is_expired(now)
240
- }
241
-
242
- /// Cancellation reaches every scope derived from this one, now or later.
243
- pub fn cancel(&self) {
244
- self.token.cancel();
245
- }
246
-
247
- /// The cooperative checkpoint.
248
- ///
249
- /// # Errors
250
- ///
251
- /// [`Stopped::Cancelled`] when this scope or an ancestor was cancelled,
252
- /// which outranks [`Stopped::Exceeded`] for a spent budget. Matches the
253
- /// precedence on the Ruby side.
254
- pub fn check(&self, now: Instant) -> Result<(), Stopped> {
255
- if self.is_cancelled() {
256
- return Err(Stopped::Cancelled);
257
- }
258
- if self.is_expired(now) {
259
- return Err(Stopped::Exceeded);
260
- }
261
- Ok(())
262
- }
263
-
264
- /// A child scope whose deadline is the tighter of this one and
265
- /// `timeout_ns` from `now`.
266
- #[must_use]
267
- pub fn derive(&self, now: Instant, timeout_ns: u64) -> Self {
268
- Self {
269
- deadline: self.deadline.derive(now, timeout_ns),
270
- token: self.token.child(),
271
- }
272
- }
273
-
274
- /// A child scope with the same deadline, cancellable on its own.
275
- #[must_use]
276
- pub fn child(&self) -> Self {
277
- Self {
278
- deadline: self.deadline,
279
- token: self.token.child(),
280
- }
281
- }
282
-
283
- /// The longest sleep that still fits the budget. A retry policy calls
284
- /// this before each backoff so it cannot outlive its caller.
285
- #[must_use]
286
- pub const fn clamp_sleep_ns(&self, now: Instant, requested_ns: u64) -> u64 {
287
- self.deadline.clamp_sleep_ns(now, requested_ns)
288
- }
289
- }
290
- }
25
+ mod scope;
26
+ #[cfg(feature = "tokio")]
27
+ pub mod tokio_support;
291
28
 
29
+ pub use deadline::Deadline;
30
+ pub use refusal::Refusal;
292
31
  #[cfg(feature = "alloc")]
293
32
  pub use scope::Scope;
294
-
295
- #[cfg(feature = "std")]
296
- mod system_clock {
297
- use super::Clock;
298
- use std::time::Instant as StdInstant;
299
-
300
- #[derive(Debug, Clone, Copy)]
301
- pub struct SystemClock {
302
- origin: StdInstant,
303
- }
304
-
305
- impl SystemClock {
306
- #[must_use]
307
- pub fn new() -> Self {
308
- Self {
309
- origin: StdInstant::now(),
310
- }
311
- }
312
- }
313
-
314
- impl Default for SystemClock {
315
- fn default() -> Self {
316
- Self::new()
317
- }
318
- }
319
-
320
- impl Clock for SystemClock {
321
- fn now_ns(&self) -> u64 {
322
- u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX)
323
- }
324
- }
325
- }
326
-
327
- #[cfg(feature = "std")]
328
- pub use system_clock::SystemClock;
329
-
330
- #[cfg(test)]
331
- mod tests;
@@ -0,0 +1,28 @@
1
+ //! Every reason a checkpoint refuses to admit more work.
2
+ use core::fmt;
3
+
4
+ /// Why a [`Deadline`](crate::Deadline) or [`Scope`](crate::Scope) stopped
5
+ /// admitting work.
6
+ ///
7
+ /// A refusal is an answer about the instant supplied, not a recorded fact:
8
+ /// nothing in this crate remembers it, and [`Exceeded`](Self::Exceeded) at
9
+ /// one `now` may be answered `Ok` for an earlier one.
10
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11
+ pub enum Refusal {
12
+ /// The budget ran out at the instant supplied.
13
+ Exceeded,
14
+ /// This scope or an ancestor was cancelled. Outranks
15
+ /// [`Exceeded`](Self::Exceeded) when both apply.
16
+ Cancelled,
17
+ }
18
+
19
+ impl fmt::Display for Refusal {
20
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21
+ f.write_str(match self {
22
+ Self::Exceeded => "deadline exceeded",
23
+ Self::Cancelled => "deadline cancelled",
24
+ })
25
+ }
26
+ }
27
+
28
+ impl core::error::Error for Refusal {}
@@ -0,0 +1,147 @@
1
+ //! A budget and a cancellation handle as one value.
2
+ use core::time::Duration;
3
+
4
+ use crate::Deadline;
5
+ use crate::Refusal;
6
+ use crate::cancel::{CancelToken, Cancellation};
7
+
8
+ /// A budget and a cancellation handle as one value, which is what a retry
9
+ /// policy or a circuit breaker actually needs to consult.
10
+ ///
11
+ /// Clones share cancellation; [`derive`](Self::derive) and
12
+ /// [`child`](Self::child) make a scope below this one.
13
+ ///
14
+ /// ```
15
+ /// use core::time::Duration;
16
+ /// use deadline_machines::{Deadline, Refusal, Scope};
17
+ ///
18
+ /// let now = Duration::ZERO;
19
+ /// let request = Scope::new(Deadline::after(now, Duration::from_secs(5)));
20
+ ///
21
+ /// let attempt = request.derive(now, Duration::from_secs(9));
22
+ /// assert_eq!(attempt.deadline(), request.deadline());
23
+ ///
24
+ /// request.cancel();
25
+ /// assert_eq!(attempt.check(now), Err(Refusal::Cancelled));
26
+ /// ```
27
+ #[derive(Debug, Clone)]
28
+ pub struct Scope {
29
+ deadline: Deadline,
30
+ token: CancelToken,
31
+ }
32
+
33
+ impl Scope {
34
+ /// A scope under `deadline` with a fresh root token.
35
+ #[must_use]
36
+ pub fn new(deadline: Deadline) -> Self {
37
+ Self::with_token(deadline, CancelToken::root())
38
+ }
39
+
40
+ /// A scope with no time limit, cancellable only.
41
+ #[must_use]
42
+ pub fn never() -> Self {
43
+ Self::new(Deadline::never())
44
+ }
45
+
46
+ /// A scope under `deadline` that shares `token`.
47
+ #[must_use]
48
+ pub const fn with_token(deadline: Deadline, token: CancelToken) -> Self {
49
+ Self { deadline, token }
50
+ }
51
+
52
+ /// The budget.
53
+ #[must_use]
54
+ pub const fn deadline(&self) -> Deadline {
55
+ self.deadline
56
+ }
57
+
58
+ /// The cancellation handle.
59
+ #[must_use]
60
+ pub const fn token(&self) -> &CancelToken {
61
+ &self.token
62
+ }
63
+
64
+ /// What is left at `now`; see [`Deadline::remaining`].
65
+ #[must_use]
66
+ pub const fn remaining(&self, now: Duration) -> Option<Duration> {
67
+ self.deadline.remaining(now)
68
+ }
69
+
70
+ /// Whether this scope or an ancestor was cancelled.
71
+ #[must_use]
72
+ pub fn is_cancelled(&self) -> bool {
73
+ self.token.is_cancelled()
74
+ }
75
+
76
+ /// Whether the budget is spent at `now`.
77
+ #[must_use]
78
+ pub const fn is_expired(&self, now: Duration) -> bool {
79
+ self.deadline.is_expired(now)
80
+ }
81
+
82
+ /// Whether [`check`](Self::check) would refuse at `now`.
83
+ #[must_use]
84
+ pub fn is_done(&self, now: Duration) -> bool {
85
+ self.is_cancelled() || self.is_expired(now)
86
+ }
87
+
88
+ /// Cancellation reaches every scope derived from this one, now or later.
89
+ /// See [`CancelToken::cancel`].
90
+ #[allow(
91
+ clippy::must_use_candidate,
92
+ reason = "cancelled for its effect; the outcome only says whether this call was first"
93
+ )]
94
+ pub fn cancel(&self) -> Cancellation {
95
+ self.token.cancel()
96
+ }
97
+
98
+ /// The cooperative checkpoint.
99
+ ///
100
+ /// # Errors
101
+ ///
102
+ /// [`Refusal::Cancelled`] when this scope or an ancestor was cancelled,
103
+ /// which outranks [`Refusal::Exceeded`] for a budget spent at `now`.
104
+ pub fn check(&self, now: Duration) -> Result<(), Refusal> {
105
+ if self.is_cancelled() {
106
+ return Err(Refusal::Cancelled);
107
+ }
108
+ self.deadline.check(now)
109
+ }
110
+
111
+ /// A child scope whose deadline is the tighter of this one and `timeout`
112
+ /// from `now`, cancellable on its own.
113
+ #[must_use]
114
+ pub fn derive(&self, now: Duration, timeout: Duration) -> Self {
115
+ Self::with_token(self.deadline.derive(now, timeout), self.token.child())
116
+ }
117
+
118
+ /// A child scope with the same deadline, cancellable on its own.
119
+ #[must_use]
120
+ pub fn child(&self) -> Self {
121
+ Self::with_token(self.deadline, self.token.child())
122
+ }
123
+
124
+ /// The same scope with the tighter of its deadline and `other`. Shares
125
+ /// cancellation with this one.
126
+ #[must_use]
127
+ pub fn tighten(&self, other: Deadline) -> Self {
128
+ Self::with_token(self.deadline.tighten(other), self.token.clone())
129
+ }
130
+
131
+ /// The same scope with its expiry pushed back by `by`. Shares
132
+ /// cancellation with this one.
133
+ #[must_use]
134
+ pub fn extend(&self, by: Duration) -> Self {
135
+ Self::with_token(self.deadline.extend(by), self.token.clone())
136
+ }
137
+
138
+ /// The longest sleep up to `requested` that still fits the budget at
139
+ /// `now`; see [`Deadline::clamp_sleep`].
140
+ #[must_use]
141
+ pub const fn clamp_sleep(&self, now: Duration, requested: Duration) -> Duration {
142
+ self.deadline.clamp_sleep(now, requested)
143
+ }
144
+ }
145
+
146
+ #[cfg(test)]
147
+ mod tests;
@@ -0,0 +1,107 @@
1
+ //! Tokio clock and timeout adapters.
2
+ //!
3
+ //! The one place this crate reads a clock: [`TokioClock`] follows Tokio's
4
+ //! time, paused test time included, so async applications use the same
5
+ //! [`Deadline`] for budget arithmetic and executor timeouts.
6
+ use core::future::{Future, poll_fn};
7
+ use core::pin::pin;
8
+ use core::task::Poll;
9
+ use core::time::Duration;
10
+
11
+ use tokio::time::Instant as TokioInstant;
12
+
13
+ use crate::{Deadline, Refusal, Scope};
14
+
15
+ /// A monotonic clock whose epoch is the moment it was built, in Tokio's time
16
+ /// domain.
17
+ #[derive(Debug, Clone, Copy)]
18
+ pub struct TokioClock {
19
+ origin: TokioInstant,
20
+ }
21
+
22
+ impl TokioClock {
23
+ /// Starts a time domain at Tokio's present. Also the [`Default`].
24
+ #[must_use]
25
+ pub fn new() -> Self {
26
+ Self {
27
+ origin: TokioInstant::now(),
28
+ }
29
+ }
30
+
31
+ /// Tokio's present as a `Duration` since this clock's epoch: the `now`
32
+ /// to hand [`Deadline`] and [`Scope`].
33
+ #[must_use]
34
+ pub fn now(&self) -> Duration {
35
+ TokioInstant::now().saturating_duration_since(self.origin)
36
+ }
37
+
38
+ /// The Tokio instant at which `deadline`, built on this clock, runs out.
39
+ ///
40
+ /// `None` when it never does: an unbounded deadline, or one past the
41
+ /// last instant Tokio can represent, which no timer would ever reach.
42
+ #[must_use]
43
+ pub fn to_tokio_instant(&self, deadline: Deadline) -> Option<TokioInstant> {
44
+ deadline
45
+ .expires_at()
46
+ .and_then(|at| self.origin.checked_add(at))
47
+ }
48
+ }
49
+
50
+ impl Default for TokioClock {
51
+ fn default() -> Self {
52
+ Self::new()
53
+ }
54
+ }
55
+
56
+ /// Runs `future` until it completes or `deadline`, built on `clock`, runs
57
+ /// out. A deadline that never runs out simply awaits the future.
58
+ ///
59
+ /// # Errors
60
+ ///
61
+ /// [`Refusal::Exceeded`] when the deadline passes first.
62
+ pub async fn timeout<F: Future>(
63
+ clock: &TokioClock,
64
+ deadline: Deadline,
65
+ future: F,
66
+ ) -> Result<F::Output, Refusal> {
67
+ match clock.to_tokio_instant(deadline) {
68
+ Some(at) => tokio::time::timeout_at(at, future)
69
+ .await
70
+ .map_err(|_| Refusal::Exceeded),
71
+ None => Ok(future.await),
72
+ }
73
+ }
74
+
75
+ impl Scope {
76
+ /// Resolves once this scope or any ancestor is cancelled. Cancel-safe.
77
+ pub async fn cancelled(&self) {
78
+ self.token().cancelled().await;
79
+ }
80
+
81
+ /// Runs `future` under this scope's remaining budget and cancellation,
82
+ /// in the time domain of `clock`.
83
+ ///
84
+ /// # Errors
85
+ ///
86
+ /// [`Refusal::Cancelled`] when the scope is cancelled, which outranks
87
+ /// [`Refusal::Exceeded`] for a spent budget.
88
+ pub async fn tokio_timeout<F: Future>(
89
+ &self,
90
+ clock: &TokioClock,
91
+ future: F,
92
+ ) -> Result<F::Output, Refusal> {
93
+ self.check(clock.now())?;
94
+ let mut future = pin!(future);
95
+ let mut cancelled = pin!(self.cancelled());
96
+ let guarded = poll_fn(|cx| {
97
+ if cancelled.as_mut().poll(cx).is_ready() {
98
+ return Poll::Ready(Err(Refusal::Cancelled));
99
+ }
100
+ future.as_mut().poll(cx).map(Ok)
101
+ });
102
+ timeout(clock, self.deadline(), guarded).await?
103
+ }
104
+ }
105
+
106
+ #[cfg(test)]
107
+ mod tests;
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,23 @@
1
+ [package]
2
+ name = "deadline_machines_native"
3
+ version = "0.1.4"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ authors = ["Abdelkader Boudih <oss@seuros.com>"]
8
+ description = "Ruby bindings for the deadline-machines budget arithmetic"
9
+ publish = false
10
+
11
+ [lib]
12
+ crate-type = ["cdylib"]
13
+ test = false
14
+ doctest = false
15
+
16
+ [dependencies]
17
+ deadline-machines.workspace = true
18
+ magnus.workspace = true
19
+ rb-sys.workspace = true
20
+ matryona-machines = { workspace = true, features = ["ruby"] }
21
+
22
+ [lints]
23
+ workspace = true
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+ require 'mkmf'
3
+ require 'pathname'
4
+ require 'rb_sys/mkmf'
5
+
6
+ create_rust_makefile('deadline_machines_native/deadline_machines_native') do |e|
7
+ e.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
8
+ e.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
9
+ end
10
+ makefile = File.join(Dir.pwd, 'Makefile')
11
+ File.write(makefile, File.read(makefile).gsub(
12
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
13
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
14
+ ))