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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +11 -0
- data/Cargo.lock +371 -0
- data/Cargo.toml +12 -1
- data/README.md +52 -25
- data/ext/deadline_machines_native/core/CHANGELOG.md +44 -0
- data/ext/deadline_machines_native/core/Cargo.toml +10 -7
- data/ext/deadline_machines_native/core/README.md +105 -0
- data/ext/deadline_machines_native/core/src/cancel.rs +175 -0
- data/ext/deadline_machines_native/core/src/deadline.rs +141 -0
- data/ext/deadline_machines_native/core/src/lib.rs +19 -631
- data/ext/deadline_machines_native/core/src/refusal.rs +28 -0
- data/ext/deadline_machines_native/core/src/scope.rs +147 -0
- data/ext/deadline_machines_native/core/src/tokio_support.rs +107 -0
- data/ext/deadline_machines_native/extconf.rb +2 -0
- data/ext/deadline_machines_native/ffi/Cargo.toml +23 -0
- data/ext/deadline_machines_native/ffi/extconf.rb +14 -0
- data/ext/deadline_machines_native/ffi/src/init.rs +31 -0
- data/ext/deadline_machines_native/ffi/src/lib.rs +146 -0
- data/lib/deadline_machines/cancel_token.rb +152 -0
- data/lib/deadline_machines/clock.rb +22 -5
- data/lib/deadline_machines/errors.rb +10 -6
- data/lib/deadline_machines/scope.rb +152 -0
- data/lib/deadline_machines/version.rb +1 -1
- data/lib/deadline_machines.rb +70 -16
- data/sig/deadline_machines.rbs +116 -35
- metadata +46 -8
- data/lib/deadline_machines/deadline.rb +0 -183
|
@@ -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,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
|
+
))
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//! Private native entry point.
|
|
2
|
+
use magnus::{Error, IntoValue, RModule, Ruby, function, method, prelude::*};
|
|
3
|
+
use matryona_machines::ruby::Class;
|
|
4
|
+
|
|
5
|
+
use crate::{
|
|
6
|
+
DEADLINE, after, at, check, clamp_sleep, derive, extend_by, held, is_expired, never, refusals,
|
|
7
|
+
remaining, tighten, validate,
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
#[magnus::init]
|
|
11
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
12
|
+
let module: RModule = ruby.define_module("DeadlineMachines")?;
|
|
13
|
+
let deadline = Class::resolve(ruby, module, "Deadline")?;
|
|
14
|
+
DEADLINE.set(ruby, deadline)?;
|
|
15
|
+
module.const_set("REFUSALS", refusals(ruby)?.into_value_with(ruby))?;
|
|
16
|
+
// The validation hook for the Data value; lib/ makes it private.
|
|
17
|
+
module.define_singleton_method("__deadline", function!(validate, 1))?;
|
|
18
|
+
module.define_singleton_method("__deadline_of", function!(held, 1))?;
|
|
19
|
+
let class = deadline.get(ruby);
|
|
20
|
+
class.define_singleton_method("never", function!(never, 0))?;
|
|
21
|
+
class.define_singleton_method("at", function!(at, 1))?;
|
|
22
|
+
class.define_singleton_method("after", function!(after, 2))?;
|
|
23
|
+
class.define_method("remaining", method!(remaining, 1))?;
|
|
24
|
+
class.define_method("expired?", method!(is_expired, 1))?;
|
|
25
|
+
class.define_method("check", method!(check, 1))?;
|
|
26
|
+
class.define_method("derive", method!(derive, 2))?;
|
|
27
|
+
class.define_method("extend_by", method!(extend_by, 1))?;
|
|
28
|
+
class.define_method("tighten", method!(tighten, 1))?;
|
|
29
|
+
class.define_method("clamp_sleep", method!(clamp_sleep, 2))?;
|
|
30
|
+
Ok(())
|
|
31
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
//! Thin binding to the `deadline-machines` budget arithmetic.
|
|
2
|
+
//!
|
|
3
|
+
//! `DeadlineMachines::Deadline` is a `Data` value defined in Ruby; every
|
|
4
|
+
//! operation on it lives here and goes through the core. The cancellation
|
|
5
|
+
//! tree, the ambient scope and the clock stay in Ruby: they hold Ruby
|
|
6
|
+
//! callbacks and fiber storage, which the core's `Arc` tree cannot.
|
|
7
|
+
mod init;
|
|
8
|
+
|
|
9
|
+
use core::time::Duration;
|
|
10
|
+
|
|
11
|
+
use deadline_machines::{Deadline, Refusal};
|
|
12
|
+
use magnus::{Error, RArray, RClass, RStruct, Ruby, TryConvert, Value, prelude::*};
|
|
13
|
+
use matryona_machines::ruby::{
|
|
14
|
+
Class, Registry, Symbols, class_name, exact_fields_with, instant, nanoseconds,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
matryona_machines::symbols! {
|
|
18
|
+
/// A refusal as its Symbol: the snake case of the core variant.
|
|
19
|
+
Refusals for Refusal as "refusal" {
|
|
20
|
+
Exceeded => "exceeded",
|
|
21
|
+
Cancelled => "cancelled",
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// The gem's one `Data` class, resolved once at init and pinned.
|
|
26
|
+
static DEADLINE: Registry<Class> = Registry::new("deadline_machines");
|
|
27
|
+
|
|
28
|
+
fn class(ruby: &Ruby) -> Result<RClass, Error> {
|
|
29
|
+
DEADLINE.get(ruby).map(|class| class.get(ruby))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/// `nil` for never, else an instant over the whole `Duration` range.
|
|
33
|
+
fn expiry(value: Value) -> Result<Option<Duration>, Error> {
|
|
34
|
+
if value.is_nil() {
|
|
35
|
+
Ok(None)
|
|
36
|
+
} else {
|
|
37
|
+
instant(value, "expires_at").map(Some)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// A `DeadlineMachines::Deadline`: exactly that class, its expiry read from
|
|
42
|
+
/// the struct (no reader runs) and checked again, since `Marshal.load` skips
|
|
43
|
+
/// `initialize`.
|
|
44
|
+
fn read(ruby: &Ruby, value: Value) -> Result<Deadline, Error> {
|
|
45
|
+
let [expires_at] = exact_fields_with(ruby, value, class(ruby)?, || {
|
|
46
|
+
format!(
|
|
47
|
+
"expected a DeadlineMachines::Deadline, not {}",
|
|
48
|
+
class_name(value)
|
|
49
|
+
)
|
|
50
|
+
})?;
|
|
51
|
+
Ok(expiry(expires_at)?.map_or_else(Deadline::never, Deadline::at))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// `__deadline_of`: the `Deadline` a `Scope` holds, read as every operation
|
|
55
|
+
/// reads one (exact class, the expiry from the struct, checked again) and
|
|
56
|
+
/// rebuilt from what was read, so neither a redefined `instance_of?` nor a
|
|
57
|
+
/// Marshal-edited value gets into a scope.
|
|
58
|
+
fn held(ruby: &Ruby, value: Value) -> Result<Value, Error> {
|
|
59
|
+
build(ruby, read(ruby, value)?)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// A frozen `Deadline` holding what the core answered. No Ruby code runs:
|
|
63
|
+
/// allocate, fill the member, freeze, which is all `Data#initialize` does
|
|
64
|
+
/// past the check, and the core's own answers need none.
|
|
65
|
+
fn build(ruby: &Ruby, deadline: Deadline) -> Result<Value, Error> {
|
|
66
|
+
let instance = RStruct::try_convert(class(ruby)?.obj_alloc()?)?;
|
|
67
|
+
let expires_at = deadline.expires_at().map_or_else(
|
|
68
|
+
|| ruby.qnil().as_value(),
|
|
69
|
+
|at| nanoseconds(ruby, at).as_value(),
|
|
70
|
+
);
|
|
71
|
+
instance.aset(0, expires_at)?;
|
|
72
|
+
instance.freeze();
|
|
73
|
+
Ok(instance.as_value())
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// `__deadline`: what a `Deadline` may hold, `nil` or an instant.
|
|
77
|
+
fn validate(value: Value) -> Result<(), Error> {
|
|
78
|
+
expiry(value).map(drop)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
fn never(ruby: &Ruby) -> Result<Value, Error> {
|
|
82
|
+
build(ruby, Deadline::never())
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
fn at(ruby: &Ruby, instant_at: Value) -> Result<Value, Error> {
|
|
86
|
+
let at = instant(instant_at, "instant")?;
|
|
87
|
+
build(ruby, Deadline::at(at))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
fn after(ruby: &Ruby, now: Value, timeout: Value) -> Result<Value, Error> {
|
|
91
|
+
let (now, timeout) = (instant(now, "now")?, instant(timeout, "timeout")?);
|
|
92
|
+
build(ruby, Deadline::after(now, timeout))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
fn remaining(ruby: &Ruby, this: Value, now: Value) -> Result<Value, Error> {
|
|
96
|
+
let deadline = read(ruby, this)?;
|
|
97
|
+
let left = deadline.remaining(instant(now, "now")?);
|
|
98
|
+
Ok(left.map_or_else(
|
|
99
|
+
|| ruby.qnil().as_value(),
|
|
100
|
+
|left| nanoseconds(ruby, left).as_value(),
|
|
101
|
+
))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
fn is_expired(ruby: &Ruby, this: Value, now: Value) -> Result<bool, Error> {
|
|
105
|
+
let deadline = read(ruby, this)?;
|
|
106
|
+
Ok(deadline.is_expired(instant(now, "now")?))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
fn check(ruby: &Ruby, this: Value, now: Value) -> Result<Value, Error> {
|
|
110
|
+
let deadline = read(ruby, this)?;
|
|
111
|
+
Ok(match deadline.check(instant(now, "now")?) {
|
|
112
|
+
Ok(()) => ruby.qnil().as_value(),
|
|
113
|
+
Err(refused) => Refusals::symbol(ruby, refused).as_value(),
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
fn derive(ruby: &Ruby, this: Value, now: Value, timeout: Value) -> Result<Value, Error> {
|
|
118
|
+
let deadline = read(ruby, this)?;
|
|
119
|
+
let (now, timeout) = (instant(now, "now")?, instant(timeout, "timeout")?);
|
|
120
|
+
build(ruby, deadline.derive(now, timeout))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
fn extend_by(ruby: &Ruby, this: Value, by: Value) -> Result<Value, Error> {
|
|
124
|
+
let deadline = read(ruby, this)?;
|
|
125
|
+
build(ruby, deadline.extend(instant(by, "by")?))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
fn tighten(ruby: &Ruby, this: Value, other: Value) -> Result<Value, Error> {
|
|
129
|
+
let (deadline, other) = (read(ruby, this)?, read(ruby, other)?);
|
|
130
|
+
build(ruby, deadline.tighten(other))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
fn clamp_sleep(ruby: &Ruby, this: Value, now: Value, requested: Value) -> Result<Value, Error> {
|
|
134
|
+
let deadline = read(ruby, this)?;
|
|
135
|
+
let (now, requested) = (instant(now, "now")?, instant(requested, "requested")?);
|
|
136
|
+
Ok(nanoseconds(ruby, deadline.clamp_sleep(now, requested)).as_value())
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
fn refusals(ruby: &Ruby) -> Result<RArray, Error> {
|
|
140
|
+
let names = ruby.ary_new_capa(Refusals::ALL.len());
|
|
141
|
+
for refused in Refusals::ALL {
|
|
142
|
+
names.push(Refusals::symbol(ruby, *refused))?;
|
|
143
|
+
}
|
|
144
|
+
names.freeze();
|
|
145
|
+
Ok(names)
|
|
146
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module DeadlineMachines
|
|
4
|
+
# A node in a cancellation tree, the runtime peer of the core's
|
|
5
|
+
# `CancelToken`: cancellation flows down and never up, a child of a
|
|
6
|
+
# cancelled token is born cancelled, and observers registered with
|
|
7
|
+
# {#on_cancel} fire once. Pure Ruby, because it holds Ruby callbacks.
|
|
8
|
+
class CancelToken
|
|
9
|
+
class << self
|
|
10
|
+
# A token with no parent.
|
|
11
|
+
def root
|
|
12
|
+
new(nil)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
private :new
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def initialize(parent)
|
|
19
|
+
@parent = parent
|
|
20
|
+
@cancelled = false
|
|
21
|
+
@detached = false
|
|
22
|
+
@reason = nil
|
|
23
|
+
@children = ObjectSpace::WeakMap.new
|
|
24
|
+
@retained = {}
|
|
25
|
+
@callbacks = []
|
|
26
|
+
@mutex = parent ? parent.mutex : Mutex.new
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Whether this token or an ancestor was cancelled.
|
|
30
|
+
def cancelled?
|
|
31
|
+
@cancelled || !!@parent&.cancelled?
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Why this token, or the nearest cancelled ancestor, was cancelled.
|
|
35
|
+
def reason
|
|
36
|
+
@reason || @parent&.reason
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Cancels this token and every descendant, now or later, then tells every
|
|
40
|
+
# observer. Answers :propagated, or :already_cancelled when this token or
|
|
41
|
+
# an ancestor already was: that repeat changes nothing, +reason+ included
|
|
42
|
+
# (read {#reason} for the one that stands). When observers raise, all of
|
|
43
|
+
# them still run and the first error is raised afterwards.
|
|
44
|
+
def cancel(reason = nil)
|
|
45
|
+
propagate(reason, true) ? :propagated : :already_cancelled
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Calls the block with this token once it is cancelled, at once if it
|
|
49
|
+
# already is.
|
|
50
|
+
def on_cancel(&block)
|
|
51
|
+
already = @mutex.synchronize do
|
|
52
|
+
settled = cancelled?
|
|
53
|
+
unless settled
|
|
54
|
+
@callbacks << block
|
|
55
|
+
@parent&.hold(self) unless @detached
|
|
56
|
+
end
|
|
57
|
+
settled
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
block.call(self) if already
|
|
61
|
+
self
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# A token cancelled whenever this one is, cancellable on its own. With a
|
|
65
|
+
# block, the child is yielded and unlinked from this token's bookkeeping
|
|
66
|
+
# when the block exits; the block's value is returned.
|
|
67
|
+
def child
|
|
68
|
+
token = CancelToken.__send__(:new, self)
|
|
69
|
+
@mutex.synchronize { @children[token] = true }
|
|
70
|
+
return token unless block_given?
|
|
71
|
+
|
|
72
|
+
begin
|
|
73
|
+
yield token
|
|
74
|
+
ensure
|
|
75
|
+
@mutex.synchronize { detach(token) }
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def inspect
|
|
80
|
+
"#<#{self.class} #{cancelled? ? 'cancelled' : 'live'}>"
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
protected
|
|
84
|
+
|
|
85
|
+
attr_reader :mutex
|
|
86
|
+
attr_writer :detached
|
|
87
|
+
|
|
88
|
+
# Sets this token's own flag and cascades. False when it was already set
|
|
89
|
+
# (a racing cancel got there first) or, for a cancel called on this token
|
|
90
|
+
# (+inherited+), when an ancestor already was: decided under the tree's
|
|
91
|
+
# one lock, so the answer and the effect agree.
|
|
92
|
+
def propagate(reason, inherited)
|
|
93
|
+
callbacks, children = @mutex.synchronize do
|
|
94
|
+
return false if @cancelled || (inherited && @parent&.cancelled?)
|
|
95
|
+
|
|
96
|
+
@cancelled = true
|
|
97
|
+
@reason = reason
|
|
98
|
+
@parent&.drop(self)
|
|
99
|
+
[@callbacks.dup, @children.keys]
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
failures = []
|
|
103
|
+
children.each { |token| notify(failures) { token.propagate(reason, false) } }
|
|
104
|
+
callbacks.each { |callback| notify(failures) { callback.call(self) } }
|
|
105
|
+
raise failures.first unless failures.empty?
|
|
106
|
+
|
|
107
|
+
true
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# A child token is the caller's to keep, so the parent follows it weakly.
|
|
111
|
+
# Something to deliver is the exception, and it has to be held all the
|
|
112
|
+
# way to the root: an intermediate token nobody else references is the
|
|
113
|
+
# one link whose collection would strand the delivery below it.
|
|
114
|
+
#
|
|
115
|
+
# Holding and dropping walk the chain, so they cannot be made atomic out
|
|
116
|
+
# of one lock per link: every token in a tree shares the root's lock, and
|
|
117
|
+
# both run inside a section the caller already holds.
|
|
118
|
+
def hold(token)
|
|
119
|
+
@retained[token] = true
|
|
120
|
+
@parent.hold(self) if @parent && !@detached
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def drop(token)
|
|
124
|
+
@retained.delete(token)
|
|
125
|
+
@parent.drop(self) if @parent && !pending?
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# A block that has ended owns its child outright: the tree will not reach
|
|
129
|
+
# it again, so the parent holds nothing for it and an observer registered
|
|
130
|
+
# afterwards is the caller's own to keep alive.
|
|
131
|
+
def detach(token)
|
|
132
|
+
@children.delete(token)
|
|
133
|
+
token.detached = true
|
|
134
|
+
drop(token)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# Whether anything is still owed through this token.
|
|
138
|
+
def pending?
|
|
139
|
+
!@cancelled && !(@callbacks.empty? && @retained.empty?)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
private
|
|
143
|
+
|
|
144
|
+
# Every observer and descendant is told, then the first failure is raised.
|
|
145
|
+
# One raising observer must not silence its peers.
|
|
146
|
+
def notify(failures)
|
|
147
|
+
yield
|
|
148
|
+
rescue StandardError => e
|
|
149
|
+
failures << e
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
@@ -1,22 +1,39 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module DeadlineMachines
|
|
4
|
+
# The process's monotonic clock, in Integer nanoseconds.
|
|
4
5
|
module MonotonicClock
|
|
5
6
|
def self.now_ns
|
|
6
7
|
Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
|
|
7
8
|
end
|
|
8
9
|
end
|
|
9
10
|
|
|
11
|
+
# A clock that moves only when told to, for deterministic tests.
|
|
10
12
|
class TestClock
|
|
11
|
-
|
|
13
|
+
attr_reader :now_ns
|
|
12
14
|
|
|
13
|
-
def initialize(now_ns
|
|
14
|
-
@now_ns = now_ns
|
|
15
|
+
def initialize(now_ns = 0)
|
|
16
|
+
@now_ns = nanoseconds(now_ns)
|
|
15
17
|
end
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
# Sets the clock to +now_ns+.
|
|
20
|
+
def now_ns=(now_ns)
|
|
21
|
+
@now_ns = nanoseconds(now_ns)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Moves the clock forward by +nanos+.
|
|
25
|
+
def advance(nanos)
|
|
26
|
+
@now_ns += nanoseconds(nanos)
|
|
19
27
|
self
|
|
20
28
|
end
|
|
29
|
+
|
|
30
|
+
private
|
|
31
|
+
|
|
32
|
+
def nanoseconds(value)
|
|
33
|
+
raise TypeError, 'a TestClock reads Integer nanoseconds' unless value.is_a?(Integer)
|
|
34
|
+
raise RangeError, 'a TestClock reads no negative nanoseconds' if value.negative?
|
|
35
|
+
|
|
36
|
+
value
|
|
37
|
+
end
|
|
21
38
|
end
|
|
22
39
|
end
|