deadline_machines 0.1.3 → 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,644 +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
- /// Push the expiry back by `ns`, for a budget that paused and should not
76
- /// pay for the time it spent waiting. Never stays never.
77
- #[must_use]
78
- pub const fn extend(&self, ns: u64) -> Self {
79
- match self.expires_at {
80
- Some(expiry) => Self::at(Instant(expiry.0.saturating_add(ns))),
81
- None => Self::never(),
82
- }
83
- }
84
-
85
- #[must_use]
86
- pub const fn tighten(&self, other: Self) -> Self {
87
- match (self.expires_at, other.expires_at) {
88
- (None, any) | (any, None) => Self { expires_at: any },
89
- (Some(a), Some(b)) if a.0 < b.0 => Self::at(a),
90
- (Some(_), Some(b)) => Self::at(b),
91
- }
92
- }
93
-
94
- #[must_use]
95
- pub const fn clamp_sleep_ns(&self, now: Instant, requested_ns: u64) -> u64 {
96
- match self.remaining_ns(now) {
97
- Some(left) if left < requested_ns => left,
98
- _ => requested_ns,
99
- }
100
- }
101
- }
102
-
103
20
  #[cfg(feature = "alloc")]
104
- pub mod cancel {
105
- use alloc::sync::Arc;
106
- use core::sync::atomic::{AtomicBool, Ordering};
107
-
108
- #[derive(Debug)]
109
- struct Node {
110
- cancelled: AtomicBool,
111
- parent: Option<Arc<Self>>,
112
- #[cfg(feature = "tokio")]
113
- notify: tokio::sync::Notify,
114
- #[cfg(feature = "tokio-util")]
115
- mirror: tokio_util::sync::CancellationToken,
116
- }
117
-
118
- impl Node {
119
- fn new(
120
- parent: Option<Arc<Self>>,
121
- #[cfg(feature = "tokio-util")] mirror: tokio_util::sync::CancellationToken,
122
- ) -> Arc<Self> {
123
- Arc::new(Self {
124
- cancelled: AtomicBool::new(false),
125
- parent,
126
- #[cfg(feature = "tokio")]
127
- notify: tokio::sync::Notify::new(),
128
- #[cfg(feature = "tokio-util")]
129
- mirror,
130
- })
131
- }
132
-
133
- fn is_cancelled(&self) -> bool {
134
- if self.cancelled.load(Ordering::Acquire) {
135
- return true;
136
- }
137
- #[cfg(feature = "tokio-util")]
138
- if self.mirror.is_cancelled() {
139
- return true;
140
- }
141
- self.parent
142
- .as_ref()
143
- .is_some_and(|parent| parent.is_cancelled())
144
- }
145
- }
146
-
147
- #[derive(Debug, Clone)]
148
- pub struct CancelToken {
149
- node: Arc<Node>,
150
- }
151
-
152
- impl CancelToken {
153
- #[must_use]
154
- pub fn root() -> Self {
155
- Self {
156
- node: Node::new(
157
- None,
158
- #[cfg(feature = "tokio-util")]
159
- tokio_util::sync::CancellationToken::new(),
160
- ),
161
- }
162
- }
163
-
164
- #[must_use]
165
- pub fn child(&self) -> Self {
166
- Self {
167
- node: Node::new(
168
- Some(Arc::clone(&self.node)),
169
- #[cfg(feature = "tokio-util")]
170
- self.node.mirror.child_token(),
171
- ),
172
- }
173
- }
174
-
175
- pub fn cancel(&self) {
176
- self.node.cancelled.store(true, Ordering::Release);
177
- #[cfg(feature = "tokio")]
178
- self.node.notify.notify_waiters();
179
- #[cfg(feature = "tokio-util")]
180
- self.node.mirror.cancel();
181
- }
182
-
183
- #[must_use]
184
- pub fn is_cancelled(&self) -> bool {
185
- self.node.is_cancelled()
186
- }
187
-
188
- /// Resolves once this token or any ancestor is cancelled. Cancel-safe:
189
- /// dropping the future and awaiting again loses nothing.
190
- #[cfg(feature = "tokio")]
191
- pub async fn cancelled(&self) {
192
- use core::future::{Future, poll_fn};
193
- use core::task::Poll;
194
-
195
- let mut waits = alloc::vec::Vec::new();
196
- let mut node = Some(&*self.node);
197
- while let Some(current) = node {
198
- waits.push(alloc::boxed::Box::pin(current.notify.notified()));
199
- node = current.parent.as_deref();
200
- }
201
- for wait in &mut waits {
202
- wait.as_mut().enable();
203
- }
204
- #[cfg(feature = "tokio-util")]
205
- let mut mirror = alloc::boxed::Box::pin(self.node.mirror.clone().cancelled_owned());
206
- if self.is_cancelled() {
207
- return;
208
- }
209
- poll_fn(|cx| {
210
- #[cfg(feature = "tokio-util")]
211
- if mirror.as_mut().poll(cx).is_ready() {
212
- return Poll::Ready(());
213
- }
214
- if waits
215
- .iter_mut()
216
- .any(|wait| wait.as_mut().poll(cx).is_ready())
217
- {
218
- Poll::Ready(())
219
- } else {
220
- Poll::Pending
221
- }
222
- })
223
- .await;
224
- }
225
-
226
- /// A root token that is cancelled whenever `token` is, so a scope can
227
- /// sit under an existing `tokio_util` cancellation tree.
228
- #[cfg(feature = "tokio-util")]
229
- #[must_use]
230
- pub fn linked_to(token: &tokio_util::sync::CancellationToken) -> Self {
231
- Self {
232
- node: Node::new(None, token.child_token()),
233
- }
234
- }
235
-
236
- /// A `tokio_util` token that is cancelled whenever this one (or an
237
- /// ancestor) is. Cancelling it cancels this token too.
238
- #[cfg(feature = "tokio-util")]
239
- #[must_use]
240
- pub fn to_cancellation_token(&self) -> tokio_util::sync::CancellationToken {
241
- self.node.mirror.clone()
242
- }
243
- }
244
-
245
- impl Default for CancelToken {
246
- fn default() -> Self {
247
- Self::root()
248
- }
249
- }
250
- }
251
-
252
- /// Why a [`Scope`] stopped admitting work.
253
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
254
- pub enum Stopped {
255
- /// The budget ran out.
256
- Exceeded,
257
- /// Someone upstream gave up.
258
- Cancelled,
259
- }
260
-
261
- impl core::fmt::Display for Stopped {
262
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
263
- f.write_str(match self {
264
- Self::Exceeded => "deadline exceeded",
265
- Self::Cancelled => "deadline cancelled",
266
- })
267
- }
268
- }
269
-
270
- impl core::error::Error for Stopped {}
271
-
21
+ pub mod cancel;
22
+ mod deadline;
23
+ mod refusal;
272
24
  #[cfg(feature = "alloc")]
273
- mod scope {
274
- use super::{Deadline, Instant, Stopped, cancel::CancelToken};
275
-
276
- /// A budget and a cancellation handle as one value, which is what a retry
277
- /// policy or a circuit breaker actually needs to consult.
278
- ///
279
- /// ```
280
- /// use deadline_machines::{Deadline, Instant, Scope, Stopped};
281
- ///
282
- /// let now = Instant(0);
283
- /// let request = Scope::new(Deadline::after(now, 5_000));
284
- ///
285
- /// let attempt = request.derive(now, 9_000);
286
- /// assert_eq!(attempt.deadline(), request.deadline());
287
- ///
288
- /// request.cancel();
289
- /// assert_eq!(attempt.check(now), Err(Stopped::Cancelled));
290
- /// ```
291
- #[derive(Debug, Clone)]
292
- pub struct Scope {
293
- deadline: Deadline,
294
- token: CancelToken,
295
- }
296
-
297
- impl Scope {
298
- #[must_use]
299
- pub fn new(deadline: Deadline) -> Self {
300
- Self {
301
- deadline,
302
- token: CancelToken::root(),
303
- }
304
- }
305
-
306
- /// A scope with no time limit, cancellable only.
307
- #[must_use]
308
- pub fn never() -> Self {
309
- Self::new(Deadline::never())
310
- }
311
-
312
- #[must_use]
313
- pub const fn with_token(deadline: Deadline, token: CancelToken) -> Self {
314
- Self { deadline, token }
315
- }
316
-
317
- #[must_use]
318
- pub const fn deadline(&self) -> Deadline {
319
- self.deadline
320
- }
321
-
322
- #[must_use]
323
- pub const fn token(&self) -> &CancelToken {
324
- &self.token
325
- }
326
-
327
- #[must_use]
328
- pub const fn remaining_ns(&self, now: Instant) -> Option<u64> {
329
- self.deadline.remaining_ns(now)
330
- }
331
-
332
- #[must_use]
333
- pub fn is_cancelled(&self) -> bool {
334
- self.token.is_cancelled()
335
- }
336
-
337
- #[must_use]
338
- pub const fn is_expired(&self, now: Instant) -> bool {
339
- self.deadline.is_expired(now)
340
- }
341
-
342
- #[must_use]
343
- pub fn is_done(&self, now: Instant) -> bool {
344
- self.is_cancelled() || self.is_expired(now)
345
- }
346
-
347
- /// Cancellation reaches every scope derived from this one, now or later.
348
- pub fn cancel(&self) {
349
- self.token.cancel();
350
- }
351
-
352
- /// The cooperative checkpoint.
353
- ///
354
- /// # Errors
355
- ///
356
- /// [`Stopped::Cancelled`] when this scope or an ancestor was cancelled,
357
- /// which outranks [`Stopped::Exceeded`] for a spent budget. Matches the
358
- /// precedence on the Ruby side.
359
- pub fn check(&self, now: Instant) -> Result<(), Stopped> {
360
- if self.is_cancelled() {
361
- return Err(Stopped::Cancelled);
362
- }
363
- if self.is_expired(now) {
364
- return Err(Stopped::Exceeded);
365
- }
366
- Ok(())
367
- }
368
-
369
- /// A child scope whose deadline is the tighter of this one and
370
- /// `timeout_ns` from `now`.
371
- #[must_use]
372
- pub fn derive(&self, now: Instant, timeout_ns: u64) -> Self {
373
- Self {
374
- deadline: self.deadline.derive(now, timeout_ns),
375
- token: self.token.child(),
376
- }
377
- }
378
-
379
- /// A child scope with the same deadline, cancellable on its own.
380
- #[must_use]
381
- pub fn child(&self) -> Self {
382
- Self {
383
- deadline: self.deadline,
384
- token: self.token.child(),
385
- }
386
- }
387
-
388
- /// The same scope with the tighter of its deadline and `other`.
389
- /// Shares cancellation with this one.
390
- #[must_use]
391
- pub fn tighten(&self, other: Deadline) -> Self {
392
- Self {
393
- deadline: self.deadline.tighten(other),
394
- token: self.token.clone(),
395
- }
396
- }
397
-
398
- /// The same scope with its expiry pushed back by `ns`. Shares
399
- /// cancellation with this one.
400
- #[must_use]
401
- pub fn extend(&self, ns: u64) -> Self {
402
- Self {
403
- deadline: self.deadline.extend(ns),
404
- token: self.token.clone(),
405
- }
406
- }
407
-
408
- /// The longest sleep that still fits the budget. A retry policy calls
409
- /// this before each backoff so it cannot outlive its caller.
410
- #[must_use]
411
- pub const fn clamp_sleep_ns(&self, now: Instant, requested_ns: u64) -> u64 {
412
- self.deadline.clamp_sleep_ns(now, requested_ns)
413
- }
414
- }
415
- }
25
+ mod scope;
26
+ #[cfg(feature = "tokio")]
27
+ pub mod tokio_support;
416
28
 
29
+ pub use deadline::Deadline;
30
+ pub use refusal::Refusal;
417
31
  #[cfg(feature = "alloc")]
418
32
  pub use scope::Scope;
419
-
420
- #[cfg(feature = "std")]
421
- mod system_clock {
422
- use super::Clock;
423
- use std::time::Instant as StdInstant;
424
-
425
- #[derive(Debug, Clone, Copy)]
426
- pub struct SystemClock {
427
- origin: StdInstant,
428
- }
429
-
430
- impl SystemClock {
431
- #[must_use]
432
- pub fn new() -> Self {
433
- Self {
434
- origin: StdInstant::now(),
435
- }
436
- }
437
- }
438
-
439
- impl Default for SystemClock {
440
- fn default() -> Self {
441
- Self::new()
442
- }
443
- }
444
-
445
- impl Clock for SystemClock {
446
- fn now_ns(&self) -> u64 {
447
- u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX)
448
- }
449
- }
450
- }
451
-
452
- #[cfg(feature = "std")]
453
- pub use system_clock::SystemClock;
454
-
455
- /// Tokio clock and timeout adapters.
456
- ///
457
- /// This feature keeps Tokio out of the core crate while allowing async
458
- /// applications to use the same deadline value for budget arithmetic and
459
- /// executor timeouts.
460
- #[cfg(feature = "tokio")]
461
- pub mod tokio_support {
462
- use super::{Clock, Deadline, Scope, Stopped};
463
- use core::future::{Future, poll_fn};
464
- use core::pin::pin;
465
- use core::task::Poll;
466
- use std::time::Duration;
467
- use tokio::time::Instant as TokioInstant;
468
-
469
- /// Why a [`Scope`] stopped a future short.
470
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
471
- pub enum ScopeError {
472
- /// The budget ran out before the future completed.
473
- Exceeded,
474
- /// The scope or an ancestor was cancelled.
475
- Cancelled,
476
- /// The deadline exceeded Tokio's representable instant range.
477
- OutOfRange,
478
- }
479
-
480
- impl From<Stopped> for ScopeError {
481
- fn from(stopped: Stopped) -> Self {
482
- match stopped {
483
- Stopped::Exceeded => Self::Exceeded,
484
- Stopped::Cancelled => Self::Cancelled,
485
- }
486
- }
487
- }
488
-
489
- impl From<TimeoutError> for ScopeError {
490
- fn from(error: TimeoutError) -> Self {
491
- match error {
492
- TimeoutError::Elapsed => Self::Exceeded,
493
- TimeoutError::OutOfRange => Self::OutOfRange,
494
- }
495
- }
496
- }
497
-
498
- impl core::fmt::Display for ScopeError {
499
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
500
- f.write_str(match self {
501
- Self::Exceeded => "deadline exceeded",
502
- Self::Cancelled => "deadline cancelled",
503
- Self::OutOfRange => "deadline out of range",
504
- })
505
- }
506
- }
507
-
508
- impl core::error::Error for ScopeError {}
509
-
510
- impl Scope {
511
- /// Resolves once this scope or any ancestor is cancelled. Cancel-safe.
512
- pub async fn cancelled(&self) {
513
- self.token().cancelled().await;
514
- }
515
-
516
- /// Run `future` under this scope's remaining budget and cancellation,
517
- /// in the time domain of `clock`.
518
- ///
519
- /// # Errors
520
- ///
521
- /// [`ScopeError::Cancelled`] when the scope is cancelled, which
522
- /// outranks [`ScopeError::Exceeded`] for a spent budget;
523
- /// [`ScopeError::OutOfRange`] if Tokio cannot represent the deadline.
524
- pub async fn tokio_timeout<F: Future>(
525
- &self,
526
- clock: &TokioClock,
527
- future: F,
528
- ) -> Result<F::Output, ScopeError> {
529
- let at = clock.to_tokio_instant(self.deadline())?;
530
- self.check(clock.now())?;
531
- let mut future = pin!(future);
532
- let mut cancelled = pin!(self.cancelled());
533
- let guarded = poll_fn(|cx| {
534
- if cancelled.as_mut().poll(cx).is_ready() {
535
- return Poll::Ready(Err(ScopeError::Cancelled));
536
- }
537
- future.as_mut().poll(cx).map(Ok)
538
- });
539
- match at {
540
- Some(at) => tokio::time::timeout_at(at, guarded)
541
- .await
542
- .map_err(|_| ScopeError::Exceeded)?,
543
- None => guarded.await,
544
- }
545
- }
546
- }
547
-
548
- /// Why a Tokio deadline could not be enforced.
549
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
550
- pub enum TimeoutError {
551
- /// The deadline exceeded Tokio's representable instant range.
552
- OutOfRange,
553
- /// The deadline elapsed before the future completed.
554
- Elapsed,
555
- }
556
-
557
- /// A clock whose time domain follows Tokio, including paused test time.
558
- #[derive(Debug, Clone, Copy)]
559
- pub struct TokioClock {
560
- origin: TokioInstant,
561
- }
562
-
563
- impl TokioClock {
564
- /// Start a Tokio-relative monotonic time domain.
565
- #[must_use]
566
- pub fn new() -> Self {
567
- Self {
568
- origin: TokioInstant::now(),
569
- }
570
- }
571
-
572
- /// Convert a deadline created from this clock into Tokio's time domain.
573
- ///
574
- /// `None` means the deadline is unbounded. A deadline must be converted
575
- /// with the same clock that was used to create it.
576
- ///
577
- /// # Errors
578
- ///
579
- /// Returns [`TimeoutError::OutOfRange`] if Tokio cannot represent the
580
- /// corresponding instant.
581
- pub fn to_tokio_instant(
582
- &self,
583
- deadline: Deadline,
584
- ) -> Result<Option<TokioInstant>, TimeoutError> {
585
- deadline
586
- .expires_at()
587
- .map(|at| {
588
- self.origin
589
- .checked_add(Duration::from_nanos(at.0))
590
- .ok_or(TimeoutError::OutOfRange)
591
- })
592
- .transpose()
593
- }
594
- }
595
-
596
- impl Default for TokioClock {
597
- fn default() -> Self {
598
- Self::new()
599
- }
600
- }
601
-
602
- impl Clock for TokioClock {
603
- fn now_ns(&self) -> u64 {
604
- u64::try_from(
605
- TokioInstant::now()
606
- .saturating_duration_since(self.origin)
607
- .as_nanos(),
608
- )
609
- .unwrap_or(u64::MAX)
610
- }
611
- }
612
-
613
- /// Enforce a deadline around a future using Tokio's clock and timer.
614
- ///
615
- /// Use the same [`TokioClock`] to construct `deadline` and enforce it.
616
- /// An unbounded deadline simply awaits the future.
617
- ///
618
- /// # Errors
619
- ///
620
- /// Returns [`TimeoutError::Elapsed`] when the deadline expires, or
621
- /// [`TimeoutError::OutOfRange`] if Tokio cannot represent the deadline.
622
- pub async fn timeout<F: Future>(
623
- clock: &TokioClock,
624
- deadline: Deadline,
625
- future: F,
626
- ) -> Result<F::Output, TimeoutError> {
627
- match clock.to_tokio_instant(deadline)? {
628
- Some(at) => tokio::time::timeout_at(at, future)
629
- .await
630
- .map_err(|_| TimeoutError::Elapsed),
631
- None => Ok(future.await),
632
- }
633
- }
634
-
635
- /// Create a deadline relative to this clock.
636
- #[must_use]
637
- pub fn deadline_after(clock: &TokioClock, timeout: Duration) -> Deadline {
638
- let timeout_ns = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
639
- Deadline::after(clock.now(), timeout_ns)
640
- }
641
- }
642
-
643
- #[cfg(test)]
644
- 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 {}