Class: Phronomy::Concurrency::CancellationToken

Inherits:
Object
  • Object
show all
Defined in:
lib/phronomy/engine/concurrency/cancellation_token.rb

Overview

Cooperative cancellation token for Agent/Tool work.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(monotonic_deadline: nil) ⇒ CancellationToken

Returns a new instance of CancellationToken.

Parameters:

  • monotonic_deadline (Float, nil) (defaults to: nil)

    internal monotonic timestamp.



16
17
18
19
20
21
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 16

def initialize(monotonic_deadline: nil)
  @cancelled = false
  @monotonic_deadline = monotonic_deadline
  @mutex = Mutex.new
  @cancel_callbacks = []
end

Class Method Details

.timeout_after(seconds) ⇒ Object

Creates a token that expires after seconds measured with the monotonic clock.



9
10
11
12
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 9

def self.timeout_after(seconds)
  monotonic_deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
  new(monotonic_deadline: monotonic_deadline)
end

Instance Method Details

#cancel!Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 46

def cancel!
  callbacks = @mutex.synchronize do
    return self if @cancelled

    @cancelled = true
    @cancel_callbacks.dup
  end
  callbacks.each(&:call)
  self
end

#cancelled?Boolean

Returns:

  • (Boolean)


58
59
60
61
62
63
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 58

def cancelled?
  return true if @mutex.synchronize { @cancelled }

  !@monotonic_deadline.nil? &&
    Process.clock_gettime(Process::CLOCK_MONOTONIC) >= @monotonic_deadline
end

#on_cancel(&block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 32

def on_cancel(&block)
  already_cancelled = @mutex.synchronize do
    if @cancelled
      true
    else
      @cancel_callbacks << block
      false
    end
  end
  block.call if already_cancelled
  self
end

#raise_if_cancelled!(message = "invocation cancelled") ⇒ Object



66
67
68
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 66

def raise_if_cancelled!(message = "invocation cancelled")
  raise Phronomy::CancellationError, message if cancelled?
end

#remaining_monotonic_secondsObject



24
25
26
27
28
29
# File 'lib/phronomy/engine/concurrency/cancellation_token.rb', line 24

def remaining_monotonic_seconds
  return nil if @monotonic_deadline.nil?

  remaining = @monotonic_deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
  [remaining, 0.0].max
end