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,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
- attr_accessor :now_ns
13
+ attr_reader :now_ns
12
14
 
13
- def initialize(now_ns: 0)
14
- @now_ns = now_ns
15
+ def initialize(now_ns = 0)
16
+ @now_ns = nanoseconds(now_ns)
15
17
  end
16
18
 
17
- def advance(seconds)
18
- @now_ns += (seconds.to_r * 1_000_000_000).round
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
@@ -1,22 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeadlineMachines
4
+ # What a checkpoint raises. Refusals as values are the symbols of
5
+ # {REFUSALS}; these exist so `check!` can unwind cooperative work.
4
6
  class Error < StandardError; end
5
7
 
8
+ # The budget of +scope+ ran out.
6
9
  class Exceeded < Error
7
- attr_reader :deadline
10
+ attr_reader :scope
8
11
 
9
- def initialize(deadline)
10
- @deadline = deadline
12
+ def initialize(scope)
13
+ @scope = scope
11
14
  super('deadline exceeded')
12
15
  end
13
16
  end
14
17
 
18
+ # +scope+ or an ancestor was cancelled, for +reason+.
15
19
  class Cancelled < Error
16
- attr_reader :deadline, :reason
20
+ attr_reader :scope, :reason
17
21
 
18
- def initialize(deadline, reason = nil)
19
- @deadline = deadline
22
+ def initialize(scope, reason = nil)
23
+ @scope = scope
20
24
  @reason = reason
21
25
  super(reason ? "deadline cancelled: #{reason}" : 'deadline cancelled')
22
26
  end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeadlineMachines
4
+ # A {Deadline} and a {CancelToken} as one value, the runtime peer of the
5
+ # core's `Scope`. Where the core takes `now`, a scope reads its clock
6
+ # (`clock` keyword, {DeadlineMachines.clock} by default): that clock and
7
+ # the token's Ruby observers are what this runtime adds on top of the core.
8
+ # Frozen; scopes sharing a token share cancellation.
9
+ class Scope
10
+ attr_reader :deadline, :token, :clock
11
+
12
+ class << self
13
+ # A scope under +deadline+ with a fresh root token.
14
+ def new(deadline, clock: DeadlineMachines.clock)
15
+ with_token(deadline, CancelToken.root, clock: clock)
16
+ end
17
+
18
+ # A scope with no time limit, cancellable only.
19
+ def never(clock: DeadlineMachines.clock)
20
+ new(Deadline.never, clock: clock)
21
+ end
22
+
23
+ # A scope under +deadline+ that shares +token+. The deadline is read
24
+ # natively, as every Deadline operation reads one, and the scope keeps
25
+ # the value rebuilt from it. The token and the clock are this runtime's
26
+ # own Ruby objects and are checked here.
27
+ def with_token(deadline, token, clock: DeadlineMachines.clock)
28
+ deadline = DeadlineMachines.__send__(:__deadline_of, deadline)
29
+ raise TypeError, 'token must be a DeadlineMachines::CancelToken' unless token.instance_of?(CancelToken)
30
+ raise TypeError, 'clock must respond to now_ns' unless clock.respond_to?(:now_ns)
31
+
32
+ scope = allocate
33
+ scope.__send__(:initialize, deadline, token, clock)
34
+ scope
35
+ end
36
+ end
37
+
38
+ def initialize(deadline, token, clock)
39
+ @deadline = deadline
40
+ @token = token
41
+ @clock = clock
42
+ freeze
43
+ end
44
+
45
+ # Nanoseconds left, zero once spent, nil when there is no limit.
46
+ def remaining
47
+ @deadline.remaining(now)
48
+ end
49
+
50
+ def expired?
51
+ @deadline.expired?(now)
52
+ end
53
+
54
+ def cancelled?
55
+ @token.cancelled?
56
+ end
57
+
58
+ def done?
59
+ cancelled? || expired?
60
+ end
61
+
62
+ # Why this scope or the nearest cancelled ancestor was cancelled.
63
+ def reason
64
+ @token.reason
65
+ end
66
+
67
+ # The checkpoint as a value: nil, or the refusal symbol. :cancelled
68
+ # outranks :exceeded.
69
+ def check
70
+ return :cancelled if cancelled?
71
+
72
+ @deadline.check(now)
73
+ end
74
+
75
+ # The cooperative checkpoint: raises Cancelled (which outranks) or
76
+ # Exceeded, else returns self.
77
+ def check!
78
+ raise Cancelled.new(self, reason) if cancelled?
79
+ raise Exceeded, self if expired?
80
+
81
+ self
82
+ end
83
+
84
+ # The longest sleep up to +requested+ nanoseconds that still fits.
85
+ def clamp_sleep(requested)
86
+ @deadline.clamp_sleep(now, requested)
87
+ end
88
+
89
+ # See {CancelToken#cancel}: :propagated or :already_cancelled.
90
+ def cancel(reason = nil)
91
+ @token.cancel(reason)
92
+ end
93
+
94
+ # Calls the block with this scope once it is cancelled, at once if it
95
+ # already is.
96
+ def on_cancel
97
+ @token.on_cancel { yield self }
98
+ self
99
+ end
100
+
101
+ # A child scope whose deadline is the tighter of this one and +timeout+
102
+ # nanoseconds from now, cancellable on its own. With a block, the child
103
+ # is yielded and unlinked when the block exits; the block's value is
104
+ # returned.
105
+ def derive(timeout, &)
106
+ below(@deadline.derive(now, timeout), &)
107
+ end
108
+
109
+ # A child scope with the same deadline, cancellable on its own; the block
110
+ # form as {#derive}.
111
+ def child(&)
112
+ below(@deadline, &)
113
+ end
114
+
115
+ # This scope with the tighter of its deadline and +other+, sharing its
116
+ # cancellation.
117
+ def tighten(other)
118
+ Scope.with_token(@deadline.tighten(other), @token, clock: @clock)
119
+ end
120
+
121
+ # This scope with its expiry pushed back by +by+ nanoseconds, sharing its
122
+ # cancellation.
123
+ def extend_by(by)
124
+ Scope.with_token(@deadline.extend_by(by), @token, clock: @clock)
125
+ end
126
+
127
+ def inspect
128
+ "#<#{self.class} #{state}>"
129
+ end
130
+
131
+ private
132
+
133
+ def now
134
+ @clock.now_ns
135
+ end
136
+
137
+ def below(deadline)
138
+ return Scope.with_token(deadline, @token.child, clock: @clock) unless block_given?
139
+
140
+ @token.child { |token| yield Scope.with_token(deadline, token, clock: @clock) }
141
+ end
142
+
143
+ def state
144
+ return 'cancelled' if cancelled?
145
+
146
+ left = remaining
147
+ return 'unbounded' if left.nil?
148
+
149
+ left.zero? ? 'expired' : "#{left}ns left"
150
+ end
151
+ end
152
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeadlineMachines
4
- VERSION = '0.1.1'
4
+ VERSION = '0.2.0'
5
5
  end
@@ -1,56 +1,110 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'deadline_machines/version'
4
+
5
+ # Every instant and span in this gem is Integer nanoseconds: `now` as read
6
+ # from `Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)`, and
7
+ # every timeout, extension, remaining budget and sleep. They reach the core
8
+ # as a `Duration`, so each is in 0..Duration::MAX nanoseconds; TypeError for
9
+ # anything but an Integer, RangeError outside that range.
10
+ module DeadlineMachines
11
+ # When a budget runs out: `expires_at` is an instant in Integer
12
+ # nanoseconds, or nil for never. A frozen value, validated through the core
13
+ # whether the gem built it or the caller did. `never`, `at`, `after` and
14
+ # every operation below are native and mirror the core's `Deadline`;
15
+ # `extend_by` is the core's `extend`, renamed so it does not shadow
16
+ # `Object#extend`.
17
+ Deadline = Data.define(:expires_at) do
18
+ def initialize(expires_at:)
19
+ DeadlineMachines.__send__(:__deadline, expires_at)
20
+ super
21
+ end
22
+ end
23
+ end
24
+
25
+ # Native is required: no algorithm fallback. It validates and builds the
26
+ # Deadline above and adds its arithmetic, so the class must exist first.
27
+ require 'deadline_machines_native/deadline_machines_native'
28
+
29
+ module DeadlineMachines
30
+ private_class_method :__deadline, :__deadline_of
31
+
32
+ # The value is sealed. `initialize` is where it validates, and a subclass
33
+ # could override it, or `allocate` build an instance that never ran it:
34
+ # subclassing raises TypeError and `allocate` is gone. Sealing stops
35
+ # accidents, not reflection (`Marshal.load` skips `initialize`), so the
36
+ # native side is the authority: a Deadline it reads must be exactly that
37
+ # class, and its expiry is checked again.
38
+ Deadline.singleton_class.undef_method(:allocate)
39
+ Deadline.define_singleton_method(:inherited) { |_| raise TypeError, "#{Deadline} cannot be subclassed" }
40
+ end
41
+
4
42
  require_relative 'deadline_machines/errors'
5
43
  require_relative 'deadline_machines/clock'
6
- require_relative 'deadline_machines/deadline'
44
+ require_relative 'deadline_machines/cancel_token'
45
+ require_relative 'deadline_machines/scope'
7
46
 
47
+ # The ambient scope: a runtime layered on the core, bound per fiber.
8
48
  module DeadlineMachines
9
- FIBER_KEY = :deadline_machines_deadline
49
+ FIBER_KEY = :deadline_machines_scope
10
50
 
11
51
  class << self
12
52
  attr_writer :clock
13
53
 
54
+ # What every scope built without an explicit clock reads.
14
55
  def clock
15
56
  @clock ||= MonotonicClock
16
57
  end
17
58
 
59
+ # The scope bound to this fiber, or nil.
18
60
  def current
19
61
  Fiber[FIBER_KEY]
20
62
  end
21
63
 
22
- def with_deadline(seconds = nil, &block)
64
+ # Runs the block under a scope bound to this fiber, and returns its value.
65
+ # Under an ambient scope it is a child of that one, tightened to
66
+ # +timeout+ nanoseconds when given; otherwise a root scope that runs out
67
+ # +timeout+ nanoseconds from now, or never.
68
+ def with_deadline(timeout = nil, &)
23
69
  ambient = current
24
- return ambient.derive(seconds) { |child| bind(child, &block) } if ambient
25
- return bind(Deadline.after(seconds, clock: clock), &block) if seconds
70
+ if ambient
71
+ return ambient.child { |scope| bind(scope, &) } if timeout.nil?
26
72
 
27
- bind(Deadline.never(clock: clock), &block)
73
+ return ambient.derive(timeout) { |scope| bind(scope, &) }
74
+ end
75
+ deadline = timeout.nil? ? Deadline.never : Deadline.after(clock.now_ns, timeout)
76
+ bind(Scope.new(deadline), &)
28
77
  end
29
78
 
30
- def bind(deadline)
79
+ # Binds +scope+ to this fiber for the block, restoring the previous one.
80
+ def bind(scope)
81
+ raise TypeError, 'scope must be a DeadlineMachines::Scope' unless scope.instance_of?(Scope)
82
+
31
83
  previous = Fiber[FIBER_KEY]
32
- Fiber[FIBER_KEY] = deadline
84
+ Fiber[FIBER_KEY] = scope
33
85
  begin
34
- yield deadline
86
+ yield scope
35
87
  ensure
36
88
  Fiber[FIBER_KEY] = previous
37
89
  end
38
90
  end
39
91
 
92
+ # The ambient checkpoint: raises Cancelled or Exceeded, else returns the
93
+ # scope, or nil outside one.
40
94
  def check!
41
95
  current&.check!
42
96
  end
43
97
 
98
+ # Nanoseconds left in the ambient scope, nil when there is no limit.
44
99
  def remaining
45
- current&.remaining || Float::INFINITY
46
- end
47
-
48
- def clamp_sleep(seconds)
49
- current ? current.clamp_sleep(seconds) : seconds
100
+ current&.remaining
50
101
  end
51
102
 
52
- def deadline?(object)
53
- object.respond_to?(:remaining) && object.respond_to?(:done?) && object.respond_to?(:check!)
103
+ # The longest sleep up to +requested+ nanoseconds that fits the ambient
104
+ # budget; +requested+ itself outside a scope.
105
+ def clamp_sleep(requested)
106
+ scope = current
107
+ scope ? scope.clamp_sleep(requested) : Deadline.never.clamp_sleep(0, requested)
54
108
  end
55
109
  end
56
110
  end