class Sequel::ShardedTimedQueueConnectionPool
A connection pool allowing multi-threaded access to a sharded pool of connections, using a timed queue (only available in Ruby 3.2+).
Attributes
The maximum number of connections this pool will create per shard.
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)
- :servers
-
A hash of servers to use. Keys should be symbols. If not present, will use a single :default server.
- :servers_hash
-
The base hash to use for the servers. By default,
Sequel
uses Hash.new(:default). You can use a hash with a default proc that raises an error if you want to catch all cases where a nonexistent server is used.
Sequel::ConnectionPool::new
# File lib/sequel/connection_pool/sharded_timed_queue.rb 24 def initialize(db, opts = OPTS) 25 super 26 27 @max_size = Integer(opts[:max_connections] || 4) 28 raise(Sequel::Error, ':max_connections must be positive') if @max_size < 1 29 @mutex = Mutex.new 30 @timeout = Float(opts[:pool_timeout] || 5) 31 32 @allocated = {} 33 @sizes = {} 34 @queues = {} 35 @servers = opts.fetch(:servers_hash, Hash.new(:default)) 36 37 add_servers([:default]) 38 add_servers(opts[:servers].keys) if opts[:servers] 39 end
Public Instance Methods
Adds new servers to the connection pool. Allows for dynamic expansion of the potential replicas/shards at runtime. servers
argument should be an array of symbols.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 43 def add_servers(servers) 44 sync do 45 servers.each do |server| 46 next if @servers.has_key?(server) 47 48 @servers[server] = server 49 @sizes[server] = 0 50 @queues[server] = Queue.new 51 (@allocated[server] = {}).compare_by_identity 52 end 53 end 54 nil 55 end
Yield all of the available connections, and the one currently allocated to this thread (if one is allocated). This will not yield connections currently allocated to other threads, as it is not safe to operate on them.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 60 def all_connections 61 thread = Sequel.current 62 sync{@queues.to_a}.each do |server, queue| 63 if conn = owned_connection(thread, server) 64 yield conn 65 end 66 67 # Use a hash to record all connections already seen. As soon as we 68 # come across a connection we've already seen, we stop the loop. 69 conns = {} 70 conns.compare_by_identity 71 while true 72 conn = nil 73 begin 74 break unless (conn = queue.pop(timeout: 0)) && !conns[conn] 75 conns[conn] = true 76 yield conn 77 ensure 78 queue.push(conn) if conn 79 end 80 end 81 end 82 83 nil 84 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.
If the :server option is provided, it should be a symbol or array of symbols, and then the method will only disconnect connectsion from those specified shards.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 95 def disconnect(opts=OPTS) 96 (opts[:server] ? Array(opts[:server]) : sync{@servers.keys}).each do |server| 97 raise Sequel::Error, "invalid server" unless queue = sync{@queues[server]} 98 while conn = queue.pop(timeout: 0) 99 disconnect_pool_connection(conn, server) 100 end 101 fill_queue(server) 102 end 103 nil 104 end
Chooses the first available connection for the given server, or if none are available, creates a new connection. Passes the connection to the supplied block:
pool.hold(:server1) {|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/sharded_timed_queue.rb 119 def hold(server=:default) 120 server = pick_server(server) 121 t = Sequel.current 122 if conn = owned_connection(t, server) 123 return yield(conn) 124 end 125 126 begin 127 conn = acquire(t, server) 128 yield conn 129 rescue Sequel::DatabaseDisconnectError, *@error_classes => e 130 if disconnect_error?(e) 131 oconn = conn 132 conn = nil 133 disconnect_pool_connection(oconn, server) if oconn 134 sync{@allocated[server].delete(t)} 135 fill_queue(server) 136 end 137 raise 138 ensure 139 release(t, conn, server) if conn 140 end 141 end
# File lib/sequel/connection_pool/sharded_timed_queue.rb 190 def pool_type 191 :sharded_timed_queue 192 end
Remove servers from the connection pool. Similar to disconnecting from all given servers, except that after it is used, future requests for the servers will use the :default server instead.
Note that an error will be raised if there are any connections currently checked out for the given servers.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 154 def remove_servers(servers) 155 conns = [] 156 raise(Sequel::Error, "cannot remove default server") if servers.include?(:default) 157 158 sync do 159 servers.each do |server| 160 next unless @servers.has_key?(server) 161 162 queue = @queues[server] 163 164 while conn = queue.pop(timeout: 0) 165 @sizes[server] -= 1 166 conns << conn 167 end 168 169 unless @sizes[server] == 0 170 raise Sequel::Error, "cannot remove server #{server} as it has allocated connections" 171 end 172 173 @servers.delete(server) 174 @sizes.delete(server) 175 @queues.delete(server) 176 @allocated.delete(server) 177 end 178 end 179 180 nil 181 ensure 182 disconnect_connections(conns) 183 end
Return an array of symbols for servers in the connection pool.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 186 def servers 187 sync{@servers.keys} 188 end
The total number of connections in the pool. Using a non-existant server will return nil.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 144 def size(server=:default) 145 sync{@sizes[server]} 146 end
Private Instance Methods
Assigns a connection to the supplied thread, if one is available.
This should return a connection if 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/sharded_timed_queue.rb 306 def acquire(thread, server) 307 queue = sync{@queues[server]} 308 if conn = queue.pop(timeout: 0) || try_make_new(server) || queue.pop(timeout: @timeout) 309 sync{@allocated[server][thread] = conn} 310 else 311 name = db.opts[:name] 312 raise ::Sequel::PoolTimeout, "timeout: #{@timeout}, server: #{server}#{", database name: #{name}" if name}" 313 end 314 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/sharded_timed_queue.rb 259 def can_make_new?(server, current_size) 260 if @max_size > current_size 261 @sizes[server] += 1 262 end 263 end
Adds a connection to the queue of available connections, returns the connection.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 363 def checkin_connection(conn, server) 364 sync{@queues[server]}.push(conn) 365 conn 366 end
Disconnect all available connections immediately, and schedule currently allocated connections for disconnection as soon as they are returned to the pool. The calling code should NOT have the mutex before calling this.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 218 def disconnect_connections(conns) 219 conns.each{|conn| disconnect_connection(conn)} 220 end
Decrement the current size of the pool for the server when disconnecting connections.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 225 def disconnect_pool_connection(conn, server) 226 sync{@sizes[server] -= 1} 227 disconnect_connection(conn) 228 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/sharded_timed_queue.rb 241 def fill_queue(server) 242 queue = sync{@queues[server]} 243 if queue.num_waiting > 0 244 Thread.new do 245 while queue.num_waiting > 0 && (conn = try_make_new(server)) 246 queue.push(conn) 247 end 248 end 249 end 250 end
Returns the connection owned by the supplied thread for the given server, if any. The calling code should NOT already have the mutex before calling this.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 318 def owned_connection(thread, server) 319 sync{@allocated[server][thread]} 320 end
If the server given is in the hash, return it, otherwise, return the default server.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 323 def pick_server(server) 324 sync{@servers[server]} 325 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/sharded_timed_queue.rb 208 def preallocated_make_new(server) 209 make_new(server) 210 rescue Exception 211 sync{@sizes[server] -= 1} 212 raise 213 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/sharded_timed_queue.rb 331 def preconnect(concurrent = false) 332 conn_servers = sync{@servers.keys}.map!{|s| Array.new(@max_size - @sizes[s], s)}.flatten! 333 334 if concurrent 335 conn_servers.map! do |server| 336 queue = sync{@queues[server]} 337 Thread.new do 338 if conn = try_make_new(server) 339 queue.push(conn) 340 end 341 end 342 end.each(&:value) 343 else 344 conn_servers.each do |server| 345 if conn = try_make_new(server) 346 sync{@queues[server]}.push(conn) 347 end 348 end 349 end 350 351 nil 352 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/sharded_timed_queue.rb 357 def release(thread, _, server) 358 checkin_connection(sync{@allocated[server].delete(thread)}, server) 359 nil 360 end
Yield to the block while inside the mutex.
Calling code should not have the mutex when calling this.
# File lib/sequel/connection_pool/sharded_timed_queue.rb 371 def sync 372 @mutex.synchronize{yield} 373 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/sharded_timed_queue.rb 270 def try_make_new(server) 271 return preallocated_make_new(server) if sync{can_make_new?(server, @sizes[server])} 272 273 to_disconnect = nil 274 do_make_new = false 275 276 sync do 277 current_size = @sizes[server] 278 alloc = @allocated[server] 279 alloc.keys.each do |t| 280 unless t.alive? 281 (to_disconnect ||= []) << alloc.delete(t) 282 current_size -= 1 283 end 284 end 285 286 do_make_new = true if can_make_new?(server, current_size) 287 end 288 289 begin 290 preallocated_make_new(server) if do_make_new 291 ensure 292 if to_disconnect 293 to_disconnect.each{|conn| disconnect_pool_connection(conn, server)} 294 fill_queue(server) 295 end 296 end 297 end