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.
@@ -0,0 +1,105 @@
1
+ # deadline-machines
2
+
3
+ Monotonic deadline arithmetic and cooperative cancellation trees. `no_std`;
4
+ `Deadline` is allocation-free and has zero dependencies.
5
+
6
+ Every instant is a `core::time::Duration` since an epoch the caller picks, and
7
+ every span is a `Duration`. `Deadline` holds no clock: the caller reads its
8
+ own and passes `now` in.
9
+
10
+ ```rust
11
+ use core::time::Duration;
12
+ use deadline_machines::{Deadline, Refusal};
13
+
14
+ let now = Duration::ZERO;
15
+ let request = Deadline::after(now, Duration::from_secs(5));
16
+
17
+ // A child never outlives its parent.
18
+ let attempt = request.derive(now, Duration::from_secs(9));
19
+ assert_eq!(attempt, request);
20
+
21
+ // A backoff that cannot overrun the budget.
22
+ let later = Duration::from_secs(4);
23
+ assert_eq!(request.clamp_sleep(later, Duration::from_secs(3)), Duration::from_secs(1));
24
+
25
+ // The checkpoint. A refusal records nothing: it answers for that instant.
26
+ assert_eq!(request.check(Duration::from_secs(5)), Err(Refusal::Exceeded));
27
+ assert_eq!(request.check(later), Ok(()));
28
+ ```
29
+
30
+ With the `alloc` feature, `CancelToken` is a cancellation tree that flows down
31
+ and never up, and `Scope` pairs a deadline with a token, which is what a retry
32
+ policy or a circuit breaker actually consults:
33
+
34
+ ```rust
35
+ use core::time::Duration;
36
+ use deadline_machines::cancel::Cancellation;
37
+ use deadline_machines::{Deadline, Refusal, Scope};
38
+
39
+ let now = Duration::ZERO;
40
+ let request = Scope::new(Deadline::after(now, Duration::from_secs(5)));
41
+ let attempt = request.derive(now, Duration::from_secs(9));
42
+
43
+ // A child cannot outlive its parent.
44
+ assert_eq!(attempt.deadline(), request.deadline());
45
+
46
+ assert_eq!(request.cancel(), Cancellation::Propagated);
47
+ assert_eq!(request.cancel(), Cancellation::AlreadyCancelled);
48
+ assert_eq!(attempt.check(now), Err(Refusal::Cancelled));
49
+
50
+ // A budget that paused should not pay for the wait.
51
+ let resumed = attempt.extend(Duration::from_secs(2));
52
+ assert_eq!(resumed.deadline().expires_at(), Some(Duration::from_secs(7)));
53
+ ```
54
+
55
+ `Deadline` builds on bare metal with no features; `CancelToken` and `Scope`
56
+ need `alloc`.
57
+
58
+ The `tokio` feature adds `TokioClock`, the one clock this crate reads. It
59
+ follows Tokio's time, paused test time included, so one deadline drives both
60
+ the arithmetic and the executor's timer:
61
+
62
+ ```rust
63
+ use core::time::Duration;
64
+ use deadline_machines::tokio_support::{TokioClock, timeout};
65
+ use deadline_machines::{Deadline, Refusal};
66
+
67
+ # async fn example() -> Result<(), Refusal> {
68
+ let clock = TokioClock::new();
69
+ let deadline = Deadline::after(clock.now(), Duration::from_secs(2));
70
+ timeout(&clock, deadline, async { do_work().await }).await?;
71
+ # Ok(())
72
+ # }
73
+ # async fn do_work() {}
74
+ ```
75
+
76
+ A `Scope` runs a future under its remaining budget and its cancellation at
77
+ once, and `cancelled()` is a cancel-safe future for `select!`:
78
+
79
+ ```rust
80
+ use core::time::Duration;
81
+ use deadline_machines::tokio_support::TokioClock;
82
+ use deadline_machines::{Deadline, Refusal, Scope};
83
+
84
+ # async fn example() -> Result<(), Refusal> {
85
+ let clock = TokioClock::new();
86
+ let request = Scope::new(Deadline::after(clock.now(), Duration::from_secs(2)));
87
+ let attempt = request.child();
88
+
89
+ let output = attempt.tokio_timeout(&clock, async { do_work().await }).await?;
90
+ # let () = output;
91
+ # Ok(())
92
+ # }
93
+ # async fn do_work() {}
94
+ ```
95
+
96
+ A deadline past the last instant Tokio can represent starts no timer: no
97
+ timer would ever reach it.
98
+
99
+ The `tokio-util` feature bridges both ways with `tokio_util::CancellationToken`:
100
+ `CancelToken::linked_to(&token)` is cancelled whenever `token` is, and
101
+ `to_cancellation_token()` hands out one that follows this tree.
102
+
103
+ This crate is the time contract the rest of the machines family builds on:
104
+ `chrono-machines` clamps its backoff to it, `breaker-machines` fails fast when it
105
+ is already spent.
@@ -0,0 +1,175 @@
1
+ //! Cooperative cancellation that flows down a tree and never up.
2
+ use alloc::sync::Arc;
3
+ use core::sync::atomic::{AtomicBool, Ordering};
4
+
5
+ /// What [`CancelToken::cancel`] did. Both answers are honoured: the token is
6
+ /// cancelled afterwards either way.
7
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8
+ pub enum Cancellation {
9
+ /// This call cancelled the token and woke what waits on it.
10
+ Propagated,
11
+ /// The token, or an ancestor, was already cancelled; nothing changed.
12
+ AlreadyCancelled,
13
+ }
14
+
15
+ #[derive(Debug)]
16
+ struct Node {
17
+ cancelled: AtomicBool,
18
+ parent: Option<Arc<Self>>,
19
+ #[cfg(feature = "tokio")]
20
+ notify: tokio::sync::Notify,
21
+ #[cfg(feature = "tokio-util")]
22
+ mirror: tokio_util::sync::CancellationToken,
23
+ }
24
+
25
+ impl Node {
26
+ fn new(
27
+ parent: Option<Arc<Self>>,
28
+ #[cfg(feature = "tokio-util")] mirror: tokio_util::sync::CancellationToken,
29
+ ) -> Arc<Self> {
30
+ Arc::new(Self {
31
+ cancelled: AtomicBool::new(false),
32
+ parent,
33
+ #[cfg(feature = "tokio")]
34
+ notify: tokio::sync::Notify::new(),
35
+ #[cfg(feature = "tokio-util")]
36
+ mirror,
37
+ })
38
+ }
39
+
40
+ fn is_cancelled(&self) -> bool {
41
+ if self.cancelled.load(Ordering::Acquire) {
42
+ return true;
43
+ }
44
+ #[cfg(feature = "tokio-util")]
45
+ if self.mirror.is_cancelled() {
46
+ return true;
47
+ }
48
+ self.parent
49
+ .as_ref()
50
+ .is_some_and(|parent| parent.is_cancelled())
51
+ }
52
+ }
53
+
54
+ /// A node in a cancellation tree. Clones share the node; [`child`](Self::child)
55
+ /// makes a new one below it.
56
+ #[derive(Debug, Clone)]
57
+ pub struct CancelToken {
58
+ node: Arc<Node>,
59
+ }
60
+
61
+ impl CancelToken {
62
+ /// A token with no parent. Also the [`Default`].
63
+ #[must_use]
64
+ pub fn root() -> Self {
65
+ Self {
66
+ node: Node::new(
67
+ None,
68
+ #[cfg(feature = "tokio-util")]
69
+ tokio_util::sync::CancellationToken::new(),
70
+ ),
71
+ }
72
+ }
73
+
74
+ /// A token cancelled whenever this one is, which can be cancelled on its
75
+ /// own. A child of a cancelled token is born cancelled.
76
+ #[must_use]
77
+ pub fn child(&self) -> Self {
78
+ Self {
79
+ node: Node::new(
80
+ Some(Arc::clone(&self.node)),
81
+ #[cfg(feature = "tokio-util")]
82
+ self.node.mirror.child_token(),
83
+ ),
84
+ }
85
+ }
86
+
87
+ /// Cancels this token and, through it, every descendant, now or later.
88
+ /// A repeat, or a token whose ancestor is already cancelled, answers
89
+ /// [`Cancellation::AlreadyCancelled`] and changes nothing.
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
+ if self.is_cancelled() || self.node.cancelled.swap(true, Ordering::AcqRel) {
96
+ return Cancellation::AlreadyCancelled;
97
+ }
98
+ #[cfg(feature = "tokio")]
99
+ self.node.notify.notify_waiters();
100
+ #[cfg(feature = "tokio-util")]
101
+ self.node.mirror.cancel();
102
+ Cancellation::Propagated
103
+ }
104
+
105
+ /// Whether this token or an ancestor was cancelled.
106
+ #[must_use]
107
+ pub fn is_cancelled(&self) -> bool {
108
+ self.node.is_cancelled()
109
+ }
110
+
111
+ /// Resolves once this token or any ancestor is cancelled. Cancel-safe:
112
+ /// dropping the future and awaiting again loses nothing.
113
+ #[cfg(feature = "tokio")]
114
+ pub async fn cancelled(&self) {
115
+ use core::future::{Future, poll_fn};
116
+ use core::task::Poll;
117
+
118
+ let mut waits = alloc::vec::Vec::new();
119
+ let mut node = Some(&*self.node);
120
+ while let Some(current) = node {
121
+ waits.push(alloc::boxed::Box::pin(current.notify.notified()));
122
+ node = current.parent.as_deref();
123
+ }
124
+ for wait in &mut waits {
125
+ wait.as_mut().enable();
126
+ }
127
+ #[cfg(feature = "tokio-util")]
128
+ let mut mirror = alloc::boxed::Box::pin(self.node.mirror.clone().cancelled_owned());
129
+ if self.is_cancelled() {
130
+ return;
131
+ }
132
+ poll_fn(|cx| {
133
+ #[cfg(feature = "tokio-util")]
134
+ if mirror.as_mut().poll(cx).is_ready() {
135
+ return Poll::Ready(());
136
+ }
137
+ if waits
138
+ .iter_mut()
139
+ .any(|wait| wait.as_mut().poll(cx).is_ready())
140
+ {
141
+ Poll::Ready(())
142
+ } else {
143
+ Poll::Pending
144
+ }
145
+ })
146
+ .await;
147
+ }
148
+
149
+ /// A root token that is cancelled whenever `token` is, so a scope can
150
+ /// sit under an existing `tokio_util` cancellation tree.
151
+ #[cfg(feature = "tokio-util")]
152
+ #[must_use]
153
+ pub fn linked_to(token: &tokio_util::sync::CancellationToken) -> Self {
154
+ Self {
155
+ node: Node::new(None, token.child_token()),
156
+ }
157
+ }
158
+
159
+ /// A `tokio_util` token that is cancelled whenever this one (or an
160
+ /// ancestor) is. Cancelling it cancels this token too.
161
+ #[cfg(feature = "tokio-util")]
162
+ #[must_use]
163
+ pub fn to_cancellation_token(&self) -> tokio_util::sync::CancellationToken {
164
+ self.node.mirror.clone()
165
+ }
166
+ }
167
+
168
+ impl Default for CancelToken {
169
+ fn default() -> Self {
170
+ Self::root()
171
+ }
172
+ }
173
+
174
+ #[cfg(test)]
175
+ mod tests;
@@ -0,0 +1,141 @@
1
+ //! The budget itself: an expiry instant, or none.
2
+ use core::time::Duration;
3
+
4
+ use crate::Refusal;
5
+
6
+ /// When a budget runs out, as an instant on the caller's monotonic clock, or
7
+ /// never.
8
+ ///
9
+ /// Every instant is a [`Duration`] since an epoch the caller picks, and every
10
+ /// span is a `Duration`. Sums saturate at [`Duration::MAX`] instead of
11
+ /// wrapping, so a deadline past the end of time is simply very late.
12
+ ///
13
+ /// ```
14
+ /// use core::time::Duration;
15
+ /// use deadline_machines::{Deadline, Refusal};
16
+ ///
17
+ /// let now = Duration::ZERO;
18
+ /// let request = Deadline::after(now, Duration::from_secs(5));
19
+ ///
20
+ /// // A child never outlives its parent.
21
+ /// assert_eq!(request.derive(now, Duration::from_secs(9)), request);
22
+ ///
23
+ /// // A backoff that cannot overrun the budget.
24
+ /// let later = Duration::from_secs(4);
25
+ /// assert_eq!(request.clamp_sleep(later, Duration::from_secs(3)), Duration::from_secs(1));
26
+ /// assert_eq!(request.check(Duration::from_secs(5)), Err(Refusal::Exceeded));
27
+ /// ```
28
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
29
+ pub struct Deadline {
30
+ expires_at: Option<Duration>,
31
+ }
32
+
33
+ /// The earlier of two instants.
34
+ const fn earlier(a: Duration, b: Duration) -> Duration {
35
+ let (a_secs, b_secs) = (a.as_secs(), b.as_secs());
36
+ if a_secs < b_secs || (a_secs == b_secs && a.subsec_nanos() < b.subsec_nanos()) {
37
+ a
38
+ } else {
39
+ b
40
+ }
41
+ }
42
+
43
+ impl Deadline {
44
+ /// A budget that never runs out. Also the [`Default`].
45
+ #[must_use]
46
+ pub const fn never() -> Self {
47
+ Self { expires_at: None }
48
+ }
49
+
50
+ /// A budget that runs out at `instant`.
51
+ #[must_use]
52
+ pub const fn at(instant: Duration) -> Self {
53
+ Self {
54
+ expires_at: Some(instant),
55
+ }
56
+ }
57
+
58
+ /// A budget that runs out `timeout` after `now`.
59
+ #[must_use]
60
+ pub const fn after(now: Duration, timeout: Duration) -> Self {
61
+ Self::at(now.saturating_add(timeout))
62
+ }
63
+
64
+ /// The instant the budget runs out, `None` for [`never`](Self::never).
65
+ #[must_use]
66
+ pub const fn expires_at(&self) -> Option<Duration> {
67
+ self.expires_at
68
+ }
69
+
70
+ /// What is left at `now`, zero once spent, `None` when there is no limit.
71
+ #[must_use]
72
+ pub const fn remaining(&self, now: Duration) -> Option<Duration> {
73
+ match self.expires_at {
74
+ Some(expiry) => Some(expiry.saturating_sub(now)),
75
+ None => None,
76
+ }
77
+ }
78
+
79
+ /// Whether nothing is left at `now`. The expiry instant itself is spent.
80
+ #[must_use]
81
+ pub const fn is_expired(&self, now: Duration) -> bool {
82
+ match self.remaining(now) {
83
+ Some(left) => left.is_zero(),
84
+ None => false,
85
+ }
86
+ }
87
+
88
+ /// The checkpoint without a cancellation tree.
89
+ ///
90
+ /// # Errors
91
+ ///
92
+ /// [`Refusal::Exceeded`] when the budget is spent at `now`.
93
+ pub const fn check(&self, now: Duration) -> Result<(), Refusal> {
94
+ if self.is_expired(now) {
95
+ Err(Refusal::Exceeded)
96
+ } else {
97
+ Ok(())
98
+ }
99
+ }
100
+
101
+ /// A child budget: the tighter of this one and `timeout` from `now`.
102
+ #[must_use]
103
+ pub const fn derive(&self, now: Duration, timeout: Duration) -> Self {
104
+ self.tighten(Self::after(now, timeout))
105
+ }
106
+
107
+ /// The expiry pushed back by `by`, for a budget that paused and should
108
+ /// not pay for the time it spent waiting. Never stays never.
109
+ #[must_use]
110
+ pub const fn extend(&self, by: Duration) -> Self {
111
+ match self.expires_at {
112
+ Some(expiry) => Self::at(expiry.saturating_add(by)),
113
+ None => Self::never(),
114
+ }
115
+ }
116
+
117
+ /// The tighter of this budget and `other`. Commutative; never is the
118
+ /// identity.
119
+ #[must_use]
120
+ pub const fn tighten(&self, other: Self) -> Self {
121
+ match (self.expires_at, other.expires_at) {
122
+ (None, None) => Self::never(),
123
+ (Some(only), None) | (None, Some(only)) => Self::at(only),
124
+ (Some(a), Some(b)) => Self::at(earlier(a, b)),
125
+ }
126
+ }
127
+
128
+ /// The longest sleep up to `requested` that still fits the budget at
129
+ /// `now`. A retry policy calls this before each backoff so it cannot
130
+ /// outlive its caller.
131
+ #[must_use]
132
+ pub const fn clamp_sleep(&self, now: Duration, requested: Duration) -> Duration {
133
+ match self.remaining(now) {
134
+ Some(left) => earlier(left, requested),
135
+ None => requested,
136
+ }
137
+ }
138
+ }
139
+
140
+ #[cfg(test)]
141
+ mod tests;