Class: RSMP::Completion

Inherits:
Object
  • Object
show all
Defined in:
lib/rsmp/completion.rb

Overview

A resolve-once Async completion. Expected failures resolve to Result::Failure; unexpected exceptions reject the promise and retain their original backtrace.

Instance Method Summary collapse

Constructor Details

#initializeCompletion

Returns a new instance of Completion.



5
6
7
# File 'lib/rsmp/completion.rb', line 5

def initialize
  @promise = Async::Promise.new
end

Instance Method Details

#crash(exception) ⇒ Object



26
27
28
# File 'lib/rsmp/completion.rb', line 26

def crash(exception)
  @promise.reject(exception)
end

#fail(failure = nil) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/rsmp/completion.rb', line 17

def fail(failure = nil, **)
  result = if failure.is_a?(RSMP::Failure)
             Result.failure(failure: failure)
           else
             Result.failure(failure, **)
           end
  @promise.resolve(result)
end

#resolved?Boolean

Returns:



9
10
11
# File 'lib/rsmp/completion.rb', line 9

def resolved?
  @promise.resolved?
end

#succeed(value = nil) ⇒ Object



13
14
15
# File 'lib/rsmp/completion.rb', line 13

def succeed(value = nil)
  @promise.resolve(Result.success(value))
end

#wait(timeout: nil) ⇒ Object

A wait timeout bounds this caller's wait; it does not resolve or cancel the underlying operation.



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rsmp/completion.rb', line 32

def wait(timeout: nil)
  @promise.wait(timeout: timeout)
rescue Async::TimeoutError => e
  return @promise.wait if @promise.resolved?

  Result.failure(
    :timeout,
    message: "Operation did not complete within #{timeout}s",
    source: :timeout,
    cause: e
  )
end

#wait!(timeout: nil) ⇒ Object



45
46
47
# File 'lib/rsmp/completion.rb', line 45

def wait!(timeout: nil)
  wait(timeout: timeout).value!
end