Class: Async::WebDriver::Bridge::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/async/webdriver/bridge/pool.rb

Overview

A pool of sessions.

“‘ ruby begin bridge = Async::WebDriver::Bridge::Pool.start(Async::WebDriver::Bridge::Chrome.new) session = bridge.session ensure bridge&.close end “`

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bridge, capabilities: bridge.default_capabilities, minimum: 2) ⇒ Pool

Initialize the session pool.



34
35
36
37
38
39
40
41
42
43
# File 'lib/async/webdriver/bridge/pool.rb', line 34

def initialize(bridge, capabilities: bridge.default_capabilities, minimum: 2)
  @bridge = bridge
  @capabilities = capabilities
  @minimum = minimum
  
  @thread = nil
  
  @waiting = Thread::Queue.new
  @sessions = Thread::Queue.new
end

Class Method Details

.start(bridge, **options) ⇒ Object

Create a new session pool and start it.



24
25
26
27
28
# File 'lib/async/webdriver/bridge/pool.rb', line 24

def self.start(bridge, **options)
  self.new(bridge, **options).tap do |pool|
    pool.start
  end
end

Instance Method Details

#closeObject

Close the session pool.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/async/webdriver/bridge/pool.rb', line 46

def close
  if @waiting
    @waiting.close
  end
  
  if @thread
    @thread.join
    @thread = nil
  end
  
  if @sessions
    @sessions.close
  end
end

#reuse(session) ⇒ Object



109
110
111
112
113
# File 'lib/async/webdriver/bridge/pool.rb', line 109

def reuse(session)
  session.reset!
  
  @sessions << {"sessionId" => session.id, "capabilities" => session.capabilities}
end

#session(&block) ⇒ Object

Open a session.



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/async/webdriver/bridge/pool.rb', line 89

def session(&block)
  @waiting << true
  
  reply = @sessions.pop
  
  session = Session.open(@bridge.endpoint, reply["sessionId"], reply["capabilities"])
  
  return session unless block_given?
  
  begin
    yield session
    
    # Try to reuse the session for extreme performance:
    reuse(session)
    session = nil
  ensure
    session&.close
  end
end

#startObject

Start the session pool.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/async/webdriver/bridge/pool.rb', line 66

def start
  @thread ||= Thread.new do
    Sync do
      @bridge.start
      
      client = Client.open(@bridge.endpoint)
      
      @minimum.times do
        @waiting << true
      end
      
      while @waiting.pop
        session = prepare_session(client)
        @sessions << session
      end
    ensure
      client&.close
      @bridge.close
    end
  end
end