deadline_machines 0.1.1 → 0.1.3

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c025a93a7c8b92aac8ca2e2ff49e11642a4a2f340e6d53db262234d66fa793c7
4
- data.tar.gz: d2e0aa5a9c97eb1dfcfd7ed8177ffa92b1d4c2591a7c415cdfb3bd1ab667933d
3
+ metadata.gz: 97980106bc90405643484bc25918b3112e157c708534e2d18df98f0b80b877b9
4
+ data.tar.gz: 7c33368aac315e3f8c08e694c43dfc147791e2b4d60ac3cf520020a111dfac45
5
5
  SHA512:
6
- metadata.gz: 0a6c0eeeb3c2fe88f63f9298aa5d669a1f2fab1e2c736513df7b4cbdae272a492d3c1df6b9d7eb6927b37561721aef6dbc657f13e3114bf4f54b70926188ec61
7
- data.tar.gz: b5303a52f3a0e5c82c7eae24d6cc43180803491cae205e1b11f742430e4fdc0ec8385ff329a31ccb259ecc6ceb39241c78b3bf83c6a2bdd99f29a37e78c2e9ae
6
+ metadata.gz: 99efe524c4df263c52e0b68fa31894c11129487f79cf9a95cf148762f894b599b4a1d8b3590d5d1ad98b04b9e391998a83ebfc62adb9198ec7a08bd8eacd9231
7
+ data.tar.gz: 511e87168f39c303f785f393e2edfbb92a18d73f3fed198f06d5395da7fe48eb4b1ae682ea2ef77bb8d9e2284e8af51c3252ac0c8bbb02984bd505610d6f6df7
data/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.3](https://github.com/seuros/deadline_machines/compare/deadline_machines/v0.1.2...deadline_machines/v0.1.3) (2026-11-06)
4
+
5
+
6
+ ### Features
7
+
8
+ * await cancellation and bridge to tokio-util tokens ([72118dc](https://github.com/seuros/deadline_machines/commit/72118dc316a4281f9fbcbb82c536e72b35cac0c2))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * keep test modules out of the packaged crate ([2719800](https://github.com/seuros/deadline_machines/commit/27198003e6883be4eab975c15cd0a3e14614d808))
14
+
15
+ ## [0.1.2](https://github.com/seuros/deadline_machines/compare/deadline_machines/v0.1.1...deadline_machines/v0.1.2) (2026-11-03)
16
+
17
+
18
+ ### Features
19
+
20
+ * add optional Tokio deadline adapter ([6a36628](https://github.com/seuros/deadline_machines/commit/6a366288d4738f99affc172c62e6c49ca5caae37))
21
+ * pass a rubygems OTP through the environment ([d21d1b1](https://github.com/seuros/deadline_machines/commit/d21d1b13e22172eed51081e971342bd70f99f437))
22
+
23
+
24
+ ### Bug Fixes
25
+
26
+ * a republished platform gem is skipped, not fatal ([7e12525](https://github.com/seuros/deadline_machines/commit/7e12525bfebb0d708b83784b2cb8a9e60404794b))
27
+ * collect the built gems whatever depth the download puts them at ([d5330ad](https://github.com/seuros/deadline_machines/commit/d5330ad2c7789ab810b73e1acb5ea2aa749c9a7c))
28
+ * the release tag carries the gem name, and the gate uses the aggregate output ([a4e0f34](https://github.com/seuros/deadline_machines/commit/a4e0f34ac239c046ed6fb1edb0ab6b6027fcf48c))
29
+
3
30
  ## [0.1.1](https://github.com/seuros/deadline_machines/compare/deadline_machines-v0.1.0...deadline_machines/v0.1.1) (2026-11-01)
4
31
 
5
32
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "deadline-machines"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  authors = ["Abdelkader Boudih <oss@seuros.com>"]
@@ -10,7 +10,7 @@ repository = "https://github.com/seuros/deadline_machines"
10
10
  keywords = ["deadline", "timeout", "cancellation", "resilience", "no-std"]
11
11
  categories = ["no-std", "concurrency"]
12
12
  readme = "README.md"
13
-
13
+ exclude = ["src/**/tests.rs", "tests/"]
14
14
  [lib]
15
15
  name = "deadline_machines"
16
16
  crate-type = ["lib"]
@@ -19,6 +19,15 @@ crate-type = ["lib"]
19
19
  default = ["std"]
20
20
  std = ["alloc"]
21
21
  alloc = []
22
+ tokio = ["std", "dep:tokio"]
23
+ tokio-util = ["tokio", "dep:tokio-util"]
24
+
25
+ [dependencies]
26
+ tokio = { version = "1", optional = true, default-features = false, features = ["sync", "time"] }
27
+ tokio-util = { version = "0.7", optional = true, default-features = false }
28
+
29
+ [dev-dependencies]
30
+ tokio = { version = "1", features = ["macros", "rt", "test-util", "time"] }
22
31
 
23
32
  [lints]
24
33
  workspace = true
@@ -72,6 +72,16 @@ impl Deadline {
72
72
  }
73
73
  }
74
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
+
75
85
  #[must_use]
76
86
  pub const fn tighten(&self, other: Self) -> Self {
77
87
  match (self.expires_at, other.expires_at) {
@@ -99,15 +109,38 @@ pub mod cancel {
99
109
  struct Node {
100
110
  cancelled: AtomicBool,
101
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,
102
116
  }
103
117
 
104
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
+
105
133
  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())
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())
111
144
  }
112
145
  }
113
146
 
@@ -120,31 +153,93 @@ pub mod cancel {
120
153
  #[must_use]
121
154
  pub fn root() -> Self {
122
155
  Self {
123
- node: Arc::new(Node {
124
- cancelled: AtomicBool::new(false),
125
- parent: None,
126
- }),
156
+ node: Node::new(
157
+ None,
158
+ #[cfg(feature = "tokio-util")]
159
+ tokio_util::sync::CancellationToken::new(),
160
+ ),
127
161
  }
128
162
  }
129
163
 
130
164
  #[must_use]
131
165
  pub fn child(&self) -> Self {
132
166
  Self {
133
- node: Arc::new(Node {
134
- cancelled: AtomicBool::new(false),
135
- parent: Some(Arc::clone(&self.node)),
136
- }),
167
+ node: Node::new(
168
+ Some(Arc::clone(&self.node)),
169
+ #[cfg(feature = "tokio-util")]
170
+ self.node.mirror.child_token(),
171
+ ),
137
172
  }
138
173
  }
139
174
 
140
175
  pub fn cancel(&self) {
141
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();
142
181
  }
143
182
 
144
183
  #[must_use]
145
184
  pub fn is_cancelled(&self) -> bool {
146
185
  self.node.is_cancelled()
147
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
+ }
148
243
  }
149
244
 
150
245
  impl Default for CancelToken {
@@ -214,11 +309,21 @@ mod scope {
214
309
  Self::new(Deadline::never())
215
310
  }
216
311
 
312
+ #[must_use]
313
+ pub const fn with_token(deadline: Deadline, token: CancelToken) -> Self {
314
+ Self { deadline, token }
315
+ }
316
+
217
317
  #[must_use]
218
318
  pub const fn deadline(&self) -> Deadline {
219
319
  self.deadline
220
320
  }
221
321
 
322
+ #[must_use]
323
+ pub const fn token(&self) -> &CancelToken {
324
+ &self.token
325
+ }
326
+
222
327
  #[must_use]
223
328
  pub const fn remaining_ns(&self, now: Instant) -> Option<u64> {
224
329
  self.deadline.remaining_ns(now)
@@ -280,6 +385,26 @@ mod scope {
280
385
  }
281
386
  }
282
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
+
283
408
  /// The longest sleep that still fits the budget. A retry policy calls
284
409
  /// this before each backoff so it cannot outlive its caller.
285
410
  #[must_use]
@@ -327,5 +452,193 @@ mod system_clock {
327
452
  #[cfg(feature = "std")]
328
453
  pub use system_clock::SystemClock;
329
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
+
330
643
  #[cfg(test)]
331
644
  mod tests;
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeadlineMachines
4
- VERSION = '0.1.1'
4
+ VERSION = '0.1.3'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: deadline_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih