Class: Freddy::SyncResponseContainer

Inherits:
Object
  • Object
show all
Defined in:
lib/freddy/sync_response_container.rb

Instance Method Summary collapse

Constructor Details

#initialize(on_timeout) ⇒ SyncResponseContainer

Returns a new instance of SyncResponseContainer.



6
7
8
9
10
# File 'lib/freddy/sync_response_container.rb', line 6

def initialize(on_timeout)
  @mutex = Mutex.new
  @resource = ConditionVariable.new
  @on_timeout = on_timeout
end

Instance Method Details

#call(response, delivery) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/freddy/sync_response_container.rb', line 12

def call(response, delivery)
  if response.nil?
    raise StandardError, 'unexpected nil value for response'
  end

  @response = response
  @delivery = delivery
  @mutex.synchronize { @resource.signal }
end

#wait_for_response(timeout) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/freddy/sync_response_container.rb', line 22

def wait_for_response(timeout)
  @mutex.synchronize { @response || @resource.wait(@mutex, timeout) }

  if !@response
    @on_timeout.call
    raise TimeoutError.new(
      error: 'RequestTimeout',
      message: 'Timed out waiting for response'
    )
  elsif !@delivery || @delivery.type == 'error'
    raise InvalidRequestError.new(@response)
  else
    @response
  end
end