Class: PiAgent::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/pi_agent/future.rb

Overview

Thread-safe single-shot promise. Used to correlate RPC requests with their responses across the transport’s stdout reader thread and the caller’s thread.

Instance Method Summary collapse

Constructor Details

#initializeFuture

Returns a new instance of Future.



10
11
12
13
14
15
16
# File 'lib/pi_agent/future.rb', line 10

def initialize
  @mon = Monitor.new
  @cond = @mon.new_cond
  @resolved = false
  @value = nil
  @error = nil
end

Instance Method Details

#reject(error) ⇒ Object

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pi_agent/future.rb', line 28

def reject(error)
  raise ArgumentError, "error must be an Exception" unless error.is_a?(Exception)

  @mon.synchronize do
    return if @resolved

    @error = error
    @resolved = true
    @cond.broadcast
  end
end

#resolve(value) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/pi_agent/future.rb', line 18

def resolve(value)
  @mon.synchronize do
    return if @resolved

    @value = value
    @resolved = true
    @cond.broadcast
  end
end

#resolved?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/pi_agent/future.rb', line 52

def resolved?
  @mon.synchronize { @resolved }
end

#value!(timeout: nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pi_agent/future.rb', line 40

def value!(timeout: nil)
  @mon.synchronize do
    unless @resolved
      @cond.wait(timeout)
      raise PiAgent::TimeoutError, "Future timed out after #{timeout}s" unless @resolved
    end
    raise @error if @error

    @value
  end
end