Class: FiberScheduler::Timeouts

Inherits:
Object
  • Object
show all
Defined in:
lib/fiber_scheduler/timeouts.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimeouts

Returns a new instance of Timeouts.



7
8
9
10
# File 'lib/fiber_scheduler/timeouts.rb', line 7

def initialize
  # Array is sorted by Timeout#time
  @timeouts = []
end

Instance Attribute Details

#timeoutsObject (readonly)

Returns the value of attribute timeouts.



5
6
7
# File 'lib/fiber_scheduler/timeouts.rb', line 5

def timeouts
  @timeouts
end

Instance Method Details

#callObject



12
13
14
15
16
17
18
19
20
21
# File 'lib/fiber_scheduler/timeouts.rb', line 12

def call
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  while @timeouts.any? && @timeouts.first.time <= now
    timeout = @timeouts.shift
    unless timeout.disabled?
      timeout.call
    end
  end
end

#inspectObject



75
76
77
# File 'lib/fiber_scheduler/timeouts.rb', line 75

def inspect
  @timeouts.inspect
end

#intervalObject



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/fiber_scheduler/timeouts.rb', line 62

def interval
  # Prune disabled timeouts
  while @timeouts.first&.disabled?
    @timeouts.shift
  end

  return if @timeouts.empty?

  interval = @timeouts.first.interval

  interval >= 0 ? interval : 0
end

#timeout(duration, *args, method: :raise, fiber: Fiber.current, &block) ⇒ Object



23
24
25
26
27
28
29
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
55
56
57
58
59
60
# File 'lib/fiber_scheduler/timeouts.rb', line 23

def timeout(duration, *args, method: :raise, fiber: Fiber.current, &block)
  timeout = Timeout.new(duration, fiber, method, *args)

  if @timeouts.empty?
    @timeouts << timeout
  else
    # binary search
    min = 0
    max = @timeouts.size - 1
    while min <= max
      index = (min + max) / 2
      t = @timeouts[index]

      if t > timeout
        if index.zero? || @timeouts[index - 1] <= timeout
          # found it
          break
        else
          # @timeouts[index - 1] > timeout
          max = index - 1
        end
      else
        # t <= timeout
        index += 1
        min = index
      end
    end

    @timeouts.insert(index, timeout)
  end

  begin
    block.call
  ensure
    # Timeout is disabled if the block finishes earlier.
    timeout.disable
  end
end