class Sequel::TimedQueueConnectionPool
A connection pool allowing multi-threaded access to a pool of connections, using a timed queue (only available in Ruby 3.2+).
Attributes
The maximum number of connections this pool will create.
Public Class Methods
The following additional options are respected:
- :max_connections
-
The maximum number of connections the connection pool will open (default 4)
- :pool_timeout
-
The amount of seconds to wait to acquire a connection before raising a PoolTimeout (default 5)
Sequel::ConnectionPool::new
# File lib/sequel/connection_pool/timed_queue.rb 18 def initialize(db, opts = OPTS) 19 super 20 @max_size = Integer(opts[:max_connections] || 4) 21 raise(Sequel::Error, ':max_connections must be positive') if @max_size < 1 22 @mutex = Mutex.new 23 # Size inside array so this still works while the pool is frozen. 24 @size = [0] 25 @allocated = {} 26 @allocated.compare_by_identity 27 @timeout = Float(opts[:pool_timeout] || 5) 28 @queue = Queue.new 29 end
Public Instance Methods
Yield all of the available connections, and the one currently allocated to this thread. This will not yield connections currently allocated to other threads, as it is not safe to operate on them.
# File lib/sequel/connection_pool/timed_queue.rb 34 def all_connections 35 hold do |conn| 36 yield conn 37 38 # Use a hash to record all connections already seen. As soon as we 39 # come across a connection we've already seen, we stop the loop. 40 conns = {} 41 conns.compare_by_identity 42 while true 43 conn = nil 44 begin 45 break unless (conn = @queue.pop(timeout: 0)) && !conns[conn] 46 conns[conn] = true 47 yield conn 48 ensure 49 @queue.push(conn) if conn 50 end 51 end 52 end 53 end
Removes all connections currently in the pool’s queue. This method has the effect of disconnecting from the database, assuming that no connections are currently being used.
Once a connection is requested using hold
, the connection pool creates new connections to the database.
# File lib/sequel/connection_pool/timed_queue.rb 61 def disconnect(opts=OPTS) 62 while conn = @queue.pop(timeout: 0) 63 disconnect_connection(conn) 64 end 65 fill_queue 66 nil 67 end
Chooses the first available connection, or if none are available, creates a new connection. Passes the connection to the supplied block:
pool.hold {|conn| conn.execute('DROP TABLE posts')}
Pool#hold is re-entrant, meaning it can be called recursively in the same thread without blocking.
If no connection is immediately available and the pool is already using the maximum number of connections, Pool#hold will block until a connection is available or the timeout expires. If the timeout expires before a connection can be acquired, a Sequel::PoolTimeout is raised.
# File lib/sequel/connection_pool/timed_queue.rb 82 def hold(server=nil) 83 t = Sequel.current 84 if conn = owned_connection(t) 85 return yield(conn) 86 end 87 88 begin 89 conn = acquire(t) 90 yield conn 91 rescue Sequel::DatabaseDisconnectError, *@error_classes => e 92 if disconnect_error?(e) 93 oconn = conn 94 conn = nil 95 disconnect_connection(oconn) if oconn 96 sync{@allocated.delete(t)} 97 fill_queue 98 end 99 raise 100 ensure 101 release(t) if conn 102 end 103 end
# File lib/sequel/connection_pool/timed_queue.rb 105 def pool_type 106 :timed_queue 107 end
The total number of connections in the pool.
# File lib/sequel/connection_pool/timed_queue.rb 110 def size 111 sync{@size[0]} 112 end
Private Instance Methods
Assigns a connection to the supplied thread, if one is available.
This should return a connection is one is available within the timeout, or raise PoolTimeout if a connection could not be acquired within the timeout.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 217 def acquire(thread) 218 if conn = @queue.pop(timeout: 0) || try_make_new || @queue.pop(timeout: @timeout) 219 sync{@allocated[thread] = conn} 220 else 221 name = db.opts[:name] 222 raise ::Sequel::PoolTimeout, "timeout: #{@timeout}#{", database name: #{name}" if name}" 223 end 224 end
Whether the given size is less than the maximum size of the pool. In that case, the pool’s current size is incremented. If this method returns true, space in the pool for the connection is preallocated, and preallocated_make_new
should be called to create the connection.
Calling code should have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 171 def can_make_new?(current_size) 172 if @max_size > current_size 173 @size[0] += 1 174 end 175 end
Adds a connection to the queue of available connections, returns the connection.
# File lib/sequel/connection_pool/timed_queue.rb 259 def checkin_connection(conn) 260 @queue.push(conn) 261 conn 262 end
Decrement the current size of the pool when disconnecting connections.
Calling code should not have the mutex when calling this.
Sequel::ConnectionPool#disconnect_connection
# File lib/sequel/connection_pool/timed_queue.rb 138 def disconnect_connection(conn) 139 sync{@size[0] -= 1} 140 super 141 end
If there are any threads waiting on the queue, try to create new connections in a separate thread if the pool is not yet at the maximum size.
The reason for this method is to handle cases where acquire could not retrieve a connection immediately, and the pool was already at the maximum size. In that case, the acquire will wait on the queue until the timeout. This method is called after disconnecting to potentially add new connections to the pool, so the threads that are currently waiting for connections do not timeout after the pool is no longer full.
# File lib/sequel/connection_pool/timed_queue.rb 154 def fill_queue 155 if @queue.num_waiting > 0 156 Thread.new do 157 while @queue.num_waiting > 0 && (conn = try_make_new) 158 @queue.push(conn) 159 end 160 end 161 end 162 end
Returns the connection owned by the supplied thread, if any. The calling code should NOT already have the mutex before calling this.
# File lib/sequel/connection_pool/timed_queue.rb 228 def owned_connection(thread) 229 sync{@allocated[thread]} 230 end
Create a new connection, after the pool’s current size has already been updated to account for the new connection. If there is an exception when creating the connection, decrement the current size.
This should only be called after can_make_new?. If there is an exception between when can_make_new? is called and when preallocated_make_new
is called, it has the effect of reducing the maximum size of the connection pool by 1, since the current size of the pool will show a higher number than the number of connections allocated or in the queue.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 128 def preallocated_make_new 129 make_new(:default) 130 rescue Exception 131 sync{@size[0] -= 1} 132 raise 133 end
Create the maximum number of connections immediately. This should not be called with a true argument unless no code is currently operating on the database.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 236 def preconnect(concurrent = false) 237 if concurrent 238 if times = sync{@max_size > (size = @size[0]) ? @max_size - size : false} 239 times.times.map{Thread.new{if conn = try_make_new; @queue.push(conn) end}}.map(&:value) 240 end 241 else 242 while conn = try_make_new 243 @queue.push(conn) 244 end 245 end 246 247 nil 248 end
Releases the connection assigned to the supplied thread back to the pool.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 253 def release(thread) 254 checkin_connection(sync{@allocated.delete(thread)}) 255 nil 256 end
Yield to the block while inside the mutex.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 267 def sync 268 @mutex.synchronize{yield} 269 end
Try to make a new connection if there is space in the pool. If the pool is already full, look for dead threads/fibers and disconnect the related connections.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/timed_queue.rb 182 def try_make_new 183 return preallocated_make_new if sync{can_make_new?(@size[0])} 184 185 to_disconnect = nil 186 do_make_new = false 187 188 sync do 189 current_size = @size[0] 190 @allocated.keys.each do |t| 191 unless t.alive? 192 (to_disconnect ||= []) << @allocated.delete(t) 193 current_size -= 1 194 end 195 end 196 197 do_make_new = true if can_make_new?(current_size) 198 end 199 200 begin 201 preallocated_make_new if do_make_new 202 ensure 203 if to_disconnect 204 to_disconnect.each{|conn| disconnect_connection(conn)} 205 fill_queue 206 end 207 end 208 end