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

max_size[R]

The maximum number of connections this pool will create per shard.

Public Class Methods

new(db, opts = OPTS) click to toggle source

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.

Calls superclass method 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

add_servers(servers) click to toggle source

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
all_connections() { |conn| ... } click to toggle source

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 = available(queue, server)) && !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
disconnect(opts=OPTS) click to toggle source

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 connections 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     nconns = 0
 99     while conn = available(queue, server)
100       nconns += 1
101       disconnect_pool_connection(conn, server)
102     end
103     fill_queue(server, nconns)
104   end
105   nil
106 end
hold(server=:default) { |conn| ... } click to toggle source

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
121 def hold(server=:default)
122   server = pick_server(server)
123   t = Sequel.current
124   if conn = owned_connection(t, server)
125     return yield(conn)
126   end
127 
128   begin
129     conn = acquire(t, server)
130     yield conn
131   rescue Sequel::DatabaseDisconnectError, *@error_classes => e
132     if disconnect_error?(e)
133       oconn = conn
134       conn = nil
135       disconnect_pool_connection(oconn, server) if oconn
136       sync{@allocated[server].delete(t)}
137       fill_queue(server, 1)
138     end
139     raise
140   ensure
141     release(t, conn, server) if conn
142   end
143 end
num_waiting(server=:default) click to toggle source

The number of threads waiting to check out a connection for the given server.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
147 def num_waiting(server=:default)
148   @queues[pick_server(server)].num_waiting
149 end
pool_type() click to toggle source
    # File lib/sequel/connection_pool/sharded_timed_queue.rb
198 def pool_type
199   :sharded_timed_queue
200 end
remove_servers(servers) click to toggle source

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
162 def remove_servers(servers)
163   conns = []
164   raise(Sequel::Error, "cannot remove default server") if servers.include?(:default)
165 
166   sync do
167     servers.each do |server|
168       next unless @servers.has_key?(server)
169 
170       queue = @queues[server]
171 
172       while conn = available(queue, server)
173         @sizes[server] -= 1
174         conns << conn
175       end
176 
177       unless @sizes[server] == 0
178         raise Sequel::Error, "cannot remove server #{server} as it has allocated connections"
179       end
180 
181       @servers.delete(server)
182       @sizes.delete(server)
183       @queues.delete(server)
184       @allocated.delete(server)
185     end
186   end
187 
188   nil
189 ensure
190   disconnect_connections(conns)
191 end
servers() click to toggle source

Return an array of symbols for servers in the connection pool.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
194 def servers
195   sync{@servers.keys}
196 end
size(server=:default) click to toggle source

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
152 def size(server=:default)
153   sync{@sizes[server]}
154 end

Private Instance Methods

acquire(thread, server) click to toggle source

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
324 def acquire(thread, server)
325   queue = sync{@queues[server]}
326   if conn = available(queue, server) || try_make_new(server) || wait_until_available(queue, server)
327     sync{@allocated[server][thread] = conn}
328   else
329     name = db.opts[:name]
330     raise ::Sequel::PoolTimeout, "timeout: #{@timeout}, server: #{server}#{", database name: #{name}" if name}"
331   end
332 end
available(queue, _server) click to toggle source

Return the next connection in the pool if there is one available. Returns nil if no connection is currently available.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
336 def available(queue, _server)
337   queue.pop(timeout: 0)
338 end
can_make_new?(server, current_size) click to toggle source

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
277 def can_make_new?(server, current_size)
278   if @max_size > current_size
279     @sizes[server] += 1
280   end
281 end
checkin_connection(conn, server) click to toggle source

Adds a connection to the queue of available connections, returns the connection.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
394 def checkin_connection(conn, server)
395   sync{@queues[server]}.push(conn)
396   conn
397 end
disconnect_acquired_connection(conn, _, server) click to toggle source

Only for use by extension that need to disconnect a connection inside acquire. Takes the connection and any arguments accepted by acquire.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
232 def disconnect_acquired_connection(conn, _, server)
233   disconnect_pool_connection(conn, server)
234 end
disconnect_connections(conns) click to toggle source

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
226 def disconnect_connections(conns)
227   conns.each{|conn| disconnect_connection(conn)}
228 end
disconnect_pool_connection(conn, server) click to toggle source

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
239 def disconnect_pool_connection(conn, server)
240   sync{@sizes[server] -= 1}
241   disconnect_connection(conn)
242 end
fill_queue(server, nconns) click to toggle source

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.

nconns specifies the maximum number of connections to add, which should be the number of connections that were disconnected.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
258 def fill_queue(server, nconns)
259   queue = sync{@queues[server]}
260   if nconns > 0 && queue.num_waiting > 0
261     Thread.new do
262       while nconns > 0 && queue.num_waiting > 0 && (conn = try_make_new(server))
263         nconns -= 1
264         queue.push(conn)
265       end
266     end
267   end
268 end
owned_connection(thread, server) click to toggle source

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
349 def owned_connection(thread, server)
350   sync{@allocated[server][thread]}
351 end
pick_server(server) click to toggle source

If the server given is in the hash, return it, otherwise, return the default server.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
354 def pick_server(server)
355   sync{@servers[server]}
356 end
preallocated_make_new(server) click to toggle source

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
216 def preallocated_make_new(server)
217   make_new(server)
218 rescue Exception
219   sync{@sizes[server] -= 1}
220   raise
221 end
preconnect(concurrent = false) click to toggle source

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
362 def preconnect(concurrent = false)
363   conn_servers = sync{@servers.keys}.map!{|s| Array.new(@max_size - @sizes[s], s)}.flatten!
364 
365   if concurrent
366     conn_servers.map! do |server|
367       queue = sync{@queues[server]}
368       Thread.new do 
369         if conn = try_make_new(server)
370           queue.push(conn)
371         end
372       end
373     end.each(&:value)
374   else
375     conn_servers.each do |server|
376       if conn = try_make_new(server)
377         sync{@queues[server]}.push(conn)
378       end
379     end
380   end
381 
382   nil
383 end
release(thread, _, server) click to toggle source

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
388 def release(thread, _, server)
389   checkin_connection(sync{@allocated[server].delete(thread)}, server)
390   nil
391 end
sync() { || ... } click to toggle source

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
402 def sync
403   @mutex.synchronize{yield}
404 end
try_make_new(server) click to toggle source

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
288 def try_make_new(server)
289   return preallocated_make_new(server) if sync{can_make_new?(server, @sizes[server])}
290 
291   to_disconnect = nil
292   do_make_new = false
293 
294   sync do
295     current_size = @sizes[server]
296     alloc = @allocated[server]
297     alloc.keys.each do |t|
298       unless t.alive?
299         (to_disconnect ||= []) << alloc.delete(t)
300         current_size -= 1
301       end
302     end
303   
304     do_make_new = true if can_make_new?(server, current_size)
305   end
306 
307   begin
308     preallocated_make_new(server) if do_make_new
309   ensure
310     if to_disconnect
311       to_disconnect.each{|conn| disconnect_pool_connection(conn, server)}
312       fill_queue(server, to_disconnect.size)
313     end
314   end
315 end
wait_until_available(queue, _server) click to toggle source

Return the next connection in the pool if there is one available. If not, wait until the timeout for a connection to become available. If there is still no available connection, return nil.

    # File lib/sequel/connection_pool/sharded_timed_queue.rb
343 def wait_until_available(queue, _server)
344   queue.pop(timeout: @timeout)
345 end