Module: Solana::Ruby::Kit::Promises

Extended by:
T::Sig
Defined in:
lib/solana/ruby/kit/promises.rb

Class Method Summary collapse

Class Method Details

.make_abort_signal(secs) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/solana/ruby/kit/promises.rb', line 77

def make_abort_signal(secs)
  start = T.let(Time.now, Time)
  Kernel.lambda do
    elapsed = Time.now - start
    Kernel.raise Timeout::Error, "Aborted after #{elapsed.round(2)}s" if elapsed >= secs
  end
end

.safe_race(callables, timeout_secs: nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/solana/ruby/kit/promises.rb', line 30

def safe_race(callables, timeout_secs: nil)
  result_q   = Queue.new
  threads    = callables.map do |callable|
    Thread.new do
      value = callable.call
      result_q.push([:ok, value])
    rescue StandardError => e
      result_q.push([:err, e])
    end
  end

  begin
    kind, payload = if timeout_secs
                     Timeout.timeout(timeout_secs) { result_q.pop }
                   else
                     result_q.pop
                   end
  ensure
    threads.each(&:kill)
  end

  Kernel.raise payload if kind == :err

  payload
end

.with_timeout(secs, &block) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/solana/ruby/kit/promises.rb', line 66

def with_timeout(secs, &block)
  if secs
    Timeout.timeout(secs) { block.call }
  else
    yield
  end
end