Class: EventMachine::Synchrony::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/em-synchrony/connection_pool.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts, &block) ⇒ ConnectionPool


7
8
9
10
11
12
13
14
15
# File 'lib/em-synchrony/connection_pool.rb', line 7

def initialize(opts, &block)
  @reserved  = {}   # map of in-progress connections
  @available = []   # pool of free connections
  @pending   = []   # pending reservations (FIFO)

  opts[:size].times do
    @available.push(block.call) if block_given?
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &blk) ⇒ Object (private)

Allow the pool to behave as the underlying connection

If the requesting method begins with “a” prefix, then hijack the callbacks and errbacks to fire a connection pool release whenever the request is complete. Otherwise yield the connection within execute method and release once it is complete (assumption: fiber will yield until data is available, or request is complete)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/em-synchrony/connection_pool.rb', line 66

def method_missing(method, *args, &blk)
  async = (method[0,1] == "a")

  execute(async) do |conn|
    df = conn.__send__(method, *args, &blk)

    if async
      fiber = Fiber.current
      df.callback { release(fiber) }
      df.errback { release(fiber) }
    end

    df
  end
end

Instance Method Details

#execute(async) ⇒ Object

Choose first available connection and pass it to the supplied block. This will block indefinitely until there is an available connection to service the request.


20
21
22
23
24
25
26
27
28
29
# File 'lib/em-synchrony/connection_pool.rb', line 20

def execute(async)
  f = Fiber.current

  begin
    conn = acquire(f)
    yield conn
  ensure
    release(f) if not async
  end
end