active_record-async_connection_pool 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +349 -0
  4. data/Rakefile +11 -0
  5. data/lib/active_record/async_connection_pool/adapter_extension/attachment.rb +276 -0
  6. data/lib/active_record/async_connection_pool/adapter_extension/detection.rb +55 -0
  7. data/lib/active_record/async_connection_pool/adapter_extension.rb +343 -0
  8. data/lib/active_record/async_connection_pool/database_options.rb +80 -0
  9. data/lib/active_record/async_connection_pool/errors.rb +17 -0
  10. data/lib/active_record/async_connection_pool/handler.rb +183 -0
  11. data/lib/active_record/async_connection_pool/handlers/postgresql/adapter_methods.rb +216 -0
  12. data/lib/active_record/async_connection_pool/handlers/postgresql/pg_query_detector.rb +256 -0
  13. data/lib/active_record/async_connection_pool/handlers/postgresql.rb +347 -0
  14. data/lib/active_record/async_connection_pool/handlers/sqlite3/adapter_methods.rb +143 -0
  15. data/lib/active_record/async_connection_pool/handlers/sqlite3.rb +183 -0
  16. data/lib/active_record/async_connection_pool/handlers/trilogy/adapter_methods.rb +140 -0
  17. data/lib/active_record/async_connection_pool/handlers/trilogy.rb +159 -0
  18. data/lib/active_record/async_connection_pool/pool_extension.rb +201 -0
  19. data/lib/active_record/async_connection_pool/raw_entry.rb +80 -0
  20. data/lib/active_record/async_connection_pool/raw_pool.rb +336 -0
  21. data/lib/active_record/async_connection_pool/session_state.rb +223 -0
  22. data/lib/active_record/async_connection_pool/version.rb +8 -0
  23. data/lib/active_record/async_connection_pool.rb +86 -0
  24. metadata +86 -0
@@ -0,0 +1,140 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ class Trilogy < Handler
8
+ # Prepended to `TrilogyAdapter` after `AdapterExtension`. With a raw pool, the handler learns each raw
9
+ # connection's `sql_mode` when it is configured, advisory locks pin, and `disable_referential_integrity` pins
10
+ # for its block. Without one, every method defers to ActiveRecord.
11
+ module AdapterMethods
12
+ #: (*untyped args) -> void
13
+ def initialize(*args)
14
+ super
15
+ @async_trilogy_advisory_locks = 0
16
+ @async_trilogy_configured = nil #: [untyped, Symbol]?
17
+ end
18
+
19
+ # Pinned from the first lock taken until the last is released, or the lease ends.
20
+ #
21
+ #: (untyped lock_name, ?Integer timeout) -> bool
22
+ def get_advisory_lock(lock_name, timeout = 0)
23
+ return super unless async_raw_pool
24
+
25
+ lease_pin!(:advisory_lock)
26
+ acquired = false
27
+ begin
28
+ acquired = without_session_state_detection { super }
29
+ ensure
30
+ if acquired
31
+ @async_trilogy_advisory_locks += 1
32
+ elsif @async_trilogy_advisory_locks.zero?
33
+ release_lease_pin!(:advisory_lock)
34
+ end
35
+ end
36
+ acquired
37
+ end
38
+
39
+ #: (untyped lock_name) -> bool
40
+ def release_advisory_lock(lock_name)
41
+ return super unless async_raw_pool
42
+
43
+ released = without_session_state_detection { super }
44
+ if released && @async_trilogy_advisory_locks.positive?
45
+ @async_trilogy_advisory_locks -= 1
46
+ release_lease_pin!(:advisory_lock) if @async_trilogy_advisory_locks.zero?
47
+ end
48
+ released
49
+ end
50
+
51
+ # A lock still held when the lease ends taints the raw connection, so it is closed, which releases the lock.
52
+ #
53
+ #: () -> void
54
+ def release_lease_pins! # :nodoc:
55
+ if @async_trilogy_advisory_locks.positive?
56
+ @async_entry&.taint!
57
+ @async_trilogy_advisory_locks = 0
58
+ end
59
+ super
60
+ end
61
+
62
+ # Pinned for its block, since `FOREIGN_KEY_CHECKS` is set in the session. ActiveRecord sets and restores it
63
+ # itself, so that is not detected; the block's own statements are. If it may not have been restored, the raw
64
+ # connection is tainted.
65
+ #
66
+ #: [T] () { () -> T } -> T
67
+ def disable_referential_integrity(&block)
68
+ return super unless async_raw_pool
69
+
70
+ detection = @async_detection_disabled
71
+ failures = [] #: Array[Exception]
72
+ pin do
73
+ without_session_state_detection do
74
+ super() { async_trilogy_referential_block(detection, failures, &block) }
75
+ end
76
+ rescue Exception => error # rubocop:disable Lint/RescueException
77
+ @async_entry&.taint! unless failures.any? { |failure| failure.equal?(error) }
78
+ raise
79
+ end
80
+ end
81
+
82
+ # ActiveRecord's `SET TRANSACTION ISOLATION LEVEL` is spent by the `BEGIN` it sends right after, so it is not
83
+ # detected. If either fails, the setting may still be pending for the session's next transaction, so the raw
84
+ # connection is tainted before it can detach.
85
+ #
86
+ #: (untyped isolation) -> untyped
87
+ def begin_isolated_db_transaction(isolation)
88
+ return super unless async_raw_pool
89
+
90
+ with_raw_connection(materialize_transactions: false) do
91
+ without_session_state_detection { super }
92
+ rescue Exception # rubocop:disable Lint/RescueException
93
+ @async_entry&.taint!
94
+ raise
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ # Lets the handler read the `sql_mode` the session was configured with.
101
+ #
102
+ #: () -> void
103
+ def configure_connection
104
+ return super unless (raw_pool = async_raw_pool)
105
+
106
+ super
107
+ raw_pool.handler.configured(self, @async_entry)
108
+ end
109
+
110
+ # Runs the block of `disable_referential_integrity` with detection as it was outside, and records what it
111
+ # raises: any other error means `FOREIGN_KEY_CHECKS` may not have been restored.
112
+ #
113
+ #: [T] (bool detection, Array[Exception] failures) { () -> T } -> T
114
+ def async_trilogy_referential_block(detection, failures)
115
+ inner = @async_detection_disabled
116
+ @async_detection_disabled = detection
117
+ yield
118
+ rescue Exception => error # rubocop:disable Lint/RescueException
119
+ failures << error
120
+ raise
121
+ ensure
122
+ @async_detection_disabled = inner
123
+ end
124
+
125
+ # The advisory locks were the raw connection's, so they go with it.
126
+ #
127
+ #: (RawEntry entry) -> void
128
+ def async_forget(entry)
129
+ super
130
+ @async_trilogy_advisory_locks = 0
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
137
+
138
+ ActiveSupport.on_load(:active_record_trilogyadapter) do
139
+ prepend ActiveRecord::AsyncConnectionPool::Handlers::Trilogy::AdapterMethods
140
+ end
@@ -0,0 +1,159 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ # `trilogy` waits on its socket through the fiber scheduler, so queries yield. Trilogy cannot reset a session in
8
+ # place, so a raw connection left with session state is closed rather than reset. State kept per raw connection
9
+ # in `RawEntry#state`:
10
+ #
11
+ # - `:sql_dialect`: how the session lexes SQL, per the `sql_mode` it was configured with (see `sql_dialect_for`).
12
+ #
13
+ # `mysql2` is not registered: it blocks the thread for the whole query, so fibers sharing its connections would
14
+ # still wait on each other's queries.
15
+ class Trilogy < Handler
16
+ # Every pattern below needs one of these, so most statements skip lexing.
17
+ HINT = /set|lock|temporary|prepare|use|handler|call|@/i
18
+
19
+ # Every `SET`, `SET TRANSACTION` included: it applies to the session's next transaction, which may be another
20
+ # fiber's once the raw connection detaches. A procedure can do anything a statement can (and its OUT
21
+ # parameters assign user variables), so every `CALL` counts. A user variable assigned with `:=` or `INTO` lives
22
+ # in the session; one only read does not.
23
+ SESSION_STATE_CODE_PATTERNS = [
24
+ /\ASET\b/,
25
+ /\ACALL\b/,
26
+ /\bGET_LOCK\s*\(/,
27
+ /\ACREATE\s+TEMPORARY\s+TABLE\b/,
28
+ /\APREPARE\b/,
29
+ /\ALOCK\s+(?:TABLES?|INSTANCE)\b/,
30
+ /\AFLUSH\s+TABLES?\b.*\bWITH\s+READ\s+LOCK\b/m,
31
+ /\AUSE\b/,
32
+ /\AHANDLER\b/,
33
+ /@(?:[\p{Alnum}_$.]+|'')\s*:=/,
34
+ /\bINTO\s+@/,
35
+ ].freeze
36
+
37
+ SQL_MODE = 'SELECT @@SESSION.sql_mode'
38
+
39
+ # The `SessionState` dialect for a session in `sql_mode`, as `@@SESSION.sql_mode` reports it (combination
40
+ # modes such as `ANSI` are listed expanded): NO_BACKSLASH_ESCAPES makes a backslash plain text in strings, and
41
+ # ANSI_QUOTES makes `"` quote identifiers.
42
+ #
43
+ #: (String? sql_mode) -> Symbol
44
+ def self.sql_dialect_for(sql_mode)
45
+ modes = sql_mode.to_s.upcase.split(',').map(&:strip)
46
+ ansi_quotes = modes.include?('ANSI_QUOTES')
47
+ no_backslash_escapes = modes.include?('NO_BACKSLASH_ESCAPES')
48
+ return :mysql unless ansi_quotes || no_backslash_escapes
49
+
50
+ :"mysql#{'_ansi_quotes' if ansi_quotes}#{'_no_backslash_escapes' if no_backslash_escapes}"
51
+ end
52
+
53
+ # The default `sql_mode`'s. A raw connection is lexed per its own (`session_state_statement_on?`).
54
+ #
55
+ #: () -> Symbol
56
+ def sql_dialect
57
+ :mysql
58
+ end
59
+
60
+ #: () -> Array[Regexp | String]
61
+ def session_state_code_patterns
62
+ SESSION_STATE_CODE_PATTERNS
63
+ end
64
+
65
+ #: (String sql) -> bool
66
+ def session_state_statement?(sql)
67
+ session_state_in?(sql, sql_dialect)
68
+ end
69
+
70
+ #: (String sql, RawEntry entry) -> bool
71
+ def session_state_statement_on?(sql, entry)
72
+ session_state_in?(sql, entry.state.fetch(:sql_dialect, sql_dialect))
73
+ end
74
+
75
+ # Called by the adapter after `configure_connection` runs on its raw connection. Reads the `sql_mode` the
76
+ # session ended up with (`variables:` may set it), into the entry if the raw connection is attached already
77
+ # (`reconnect!`), or for `adopt` otherwise.
78
+ #
79
+ #: (untyped adapter, RawEntry? entry) -> void
80
+ def configured(adapter, entry) # :nodoc:
81
+ sql_mode = adapter.without_session_state_detection do
82
+ adapter.send(:query_value, SQL_MODE, 'SCHEMA', materialize_transactions: false)
83
+ end
84
+ dialect = self.class.sql_dialect_for(sql_mode)
85
+ if entry
86
+ entry.state[:sql_dialect] = dialect
87
+ else
88
+ raw = adapter.instance_variable_get(:@raw_connection)
89
+ adapter.instance_variable_set(:@async_trilogy_configured, [raw, dialect])
90
+ end
91
+ end
92
+
93
+ #: (untyped adapter, RawEntry entry) -> void
94
+ def adopt(adapter, entry)
95
+ raw, dialect = adapter.instance_variable_get(:@async_trilogy_configured)
96
+ return unless raw
97
+
98
+ adapter.instance_variable_set(:@async_trilogy_configured, nil)
99
+ entry.state[:sql_dialect] = dialect if raw.equal?(entry.raw)
100
+ end
101
+
102
+ #: (RawEntry entry) -> bool
103
+ def clean?(entry)
104
+ raw = entry.raw
105
+ !raw.closed? && !raw.in_transaction? && !in_flight?(raw)
106
+ end
107
+
108
+ #: (untyped raw) -> void
109
+ def close(raw)
110
+ raw.close unless raw.closed?
111
+ end
112
+
113
+ #: (untyped raw) -> bool
114
+ def healthy?(raw)
115
+ return false if raw.closed?
116
+
117
+ raw.ping
118
+ true
119
+ rescue StandardError
120
+ false
121
+ end
122
+
123
+ # Closes the socket without telling the server, so the child cannot end the parent's session.
124
+ #
125
+ #: (untyped raw) -> void
126
+ def discard(raw)
127
+ raw.discard!
128
+ rescue StandardError
129
+ nil
130
+ end
131
+
132
+ # Trilogy shuts its socket down when an exception interrupts a statement, so the statement's result is never
133
+ # read; the socket check (local, without a round trip) then fails. A server error leaves the socket usable.
134
+ #
135
+ #: (untyped raw) -> bool
136
+ def in_flight?(raw)
137
+ return false if raw.closed?
138
+
139
+ raw.check
140
+ false
141
+ rescue StandardError
142
+ true
143
+ end
144
+
145
+ private
146
+
147
+ #: (String sql, Symbol dialect) -> bool
148
+ def session_state_in?(sql, dialect)
149
+ sql.match?(HINT) && SessionState.code_matches?(sql, session_state_code_patterns, dialect:)
150
+ end
151
+ end
152
+ end
153
+
154
+ Handler.register('ActiveRecord::ConnectionAdapters::TrilogyAdapter', Handlers::Trilogy,
155
+ load_hook: :active_record_trilogyadapter)
156
+ end
157
+ end
158
+
159
+ require 'active_record/async_connection_pool/handlers/trilogy/adapter_methods'
@@ -0,0 +1,201 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ # Prepended to ActiveRecord's `ConnectionPool`. With `raw_pool` on, the pool hands out adapters as before and
7
+ # owns a raw pool of physical connections those adapters attach to. Without it, every method defers to
8
+ # ActiveRecord.
9
+ module PoolExtension
10
+ # Fails here, at boot, for an adapter without a handler, before ActiveRecord sets anything up.
11
+ #
12
+ #: (untyped pool_config) -> void
13
+ def initialize(pool_config)
14
+ db_config = pool_config.db_config
15
+ options = DatabaseOptions.new(db_config)
16
+ handler = Handler.for(db_config.adapter_class).new(db_config, options) if options.enabled?
17
+
18
+ super
19
+
20
+ @async_raw_pool = nil #: RawPool?
21
+ return unless handler
22
+
23
+ @max_connections = options.adapter_pool_size || @max_connections
24
+ @async_raw_pool = RawPool.new(handler:, size: handler.max_raw_connections(options.max_raw_connections),
25
+ checkout_timeout: @checkout_timeout, pool: self,
26
+ min_connections: @min_connections.to_i)
27
+ async_warn_small_adapter_pool
28
+ end
29
+
30
+ #: () -> RawPool?
31
+ def raw_pool
32
+ @async_raw_pool
33
+ end
34
+
35
+ # Yields a connection that keeps the same raw connection attached for the block.
36
+ #
37
+ #: [T] () { (untyped) -> T } -> T
38
+ def pin
39
+ with_connection do |conn|
40
+ raw_pool ? conn.pin { yield conn } : yield(conn)
41
+ end
42
+ end
43
+
44
+ # The lease is over, so its pins are released and the raw connection goes back.
45
+ #
46
+ #: (untyped conn) -> void
47
+ def checkin(conn)
48
+ if raw_pool && !@pinned_connection.equal?(conn)
49
+ begin
50
+ conn.release_lease_pins!
51
+ conn.detach!
52
+ ensure
53
+ super
54
+ end
55
+ else
56
+ super
57
+ end
58
+ end
59
+
60
+ # ActiveRecord removes an adapter without checking it in (eg. `reap` when its owner died and it is not
61
+ # active), so its raw connection, in an unknown state, is closed and its slot freed here.
62
+ #
63
+ #: (untyped conn) -> void
64
+ def remove(conn)
65
+ super
66
+ ensure
67
+ conn.drop_raw_connection! if raw_pool && conn.is_a?(AdapterExtension)
68
+ end
69
+
70
+ # Pinned until `unpin_connection!` releases the last pin: ActiveRecord then checks the connection in, which
71
+ # releases this lease pin with the others.
72
+ #
73
+ #: (bool lock_thread) -> untyped
74
+ def pin_connection!(lock_thread)
75
+ result = super
76
+ @pinned_connection.lease_pin!(:pin_connection) if raw_pool
77
+ result
78
+ end
79
+
80
+ #: () -> Hash[Symbol, untyped]
81
+ def stat
82
+ raw = raw_pool
83
+ raw ? super.merge(raw: raw.stat) : super
84
+ end
85
+
86
+ # After fork: the inherited raw connections belong to the parent, so they are dropped, not closed.
87
+ #
88
+ #: () -> void
89
+ def discard!
90
+ super
91
+ ensure
92
+ raw_pool&.discard!
93
+ end
94
+
95
+ #: (?bool raise_on_acquisition_timeout) -> void
96
+ def disconnect(raise_on_acquisition_timeout = true) # rubocop:disable Style/OptionalBooleanParameter
97
+ super
98
+ ensure
99
+ raw_pool&.disconnect!
100
+ end
101
+
102
+ # Marks the raw connections for replacement too: the adapters' own connection ages describe no raw connection.
103
+ # Idle ones are closed now, so, as with stock `recycle!` and `disconnect!`, a private in-memory SQLite database
104
+ # (whose only raw connection is idle between statements) is closed and its data lost.
105
+ #
106
+ #: () -> void
107
+ def recycle!
108
+ super
109
+ ensure
110
+ raw_pool&.recycle! unless discarded?
111
+ end
112
+
113
+ # Each maintenance hook applies its own limit to the raw pool, so a reaper tick checks health once.
114
+ #
115
+ #: (?Numeric? minimum_idle) -> void
116
+ def flush(minimum_idle = @idle_timeout)
117
+ super
118
+ ensure
119
+ async_maintain(idle_timeout: minimum_idle)
120
+ end
121
+
122
+ #: (?Numeric? threshold) -> void
123
+ def keep_alive(threshold = @keepalive)
124
+ super
125
+ ensure
126
+ async_maintain(keepalive: threshold)
127
+ end
128
+
129
+ #: (?Numeric? max_age) -> void
130
+ def retire_old_connections(max_age = @max_age)
131
+ super
132
+ ensure
133
+ async_maintain(max_age:)
134
+ end
135
+
136
+ # `min_connections` counts raw connections, which idle adapters do not hold, so the raw pool is warmed up to it
137
+ # as well (no further than its size).
138
+ #
139
+ #: () -> void
140
+ def preconnect
141
+ super
142
+ ensure
143
+ async_preconnect
144
+ end
145
+
146
+ private
147
+
148
+ # An adapter pool no larger than the raw pool caps fibers at its size, so the extra ones wait on ActiveRecord's
149
+ # queue rather than share raw connections. Rails' generated database.yml sets `max_connections` to
150
+ # RAILS_MAX_THREADS (5) under `default:`, which `raw_pool: true` alone does not change.
151
+ #
152
+ #: () -> void
153
+ def async_warn_small_adapter_pool
154
+ raw_size = @async_raw_pool&.size
155
+ return unless raw_size && @max_connections && @max_connections <= raw_size
156
+
157
+ ActiveRecord::Base.logger&.warn(
158
+ "active_record-async_connection_pool: #{db_config.env_name}/#{db_config.name} has an adapter pool of " \
159
+ "#{@max_connections} (max_connections), no larger than max_raw_connections (#{raw_size}), so at most " \
160
+ "#{@max_connections} fibers can hold a connection at once. Remove max_connections (or pool) from its " \
161
+ 'database.yml entry, or set it well above max_raw_connections.'
162
+ )
163
+ end
164
+
165
+ # Attaches scratch adapters until enough raw connections are open, then detaches them all, which leaves the raw
166
+ # connections idle. An attach takes an idle raw connection before it builds one, so the idle ones are held
167
+ # until the rest are built; there are never more attaches than the raw pool's size. Failures are swallowed, as
168
+ # ActiveRecord's preconnect does: the next checkout connects instead.
169
+ #
170
+ #: () -> void
171
+ def async_preconnect
172
+ return unless (raw = raw_pool)
173
+
174
+ target = [@min_connections, raw.size].min
175
+ adapters = [] #: Array[untyped]
176
+ begin
177
+ while raw.stat[:connections] < target && adapters.size < raw.size
178
+ adapter = new_connection
179
+ adapters << adapter
180
+ adapter.lease_pin!(:preconnect)
181
+ end
182
+ rescue StandardError
183
+ nil
184
+ ensure
185
+ adapters.each do |adapter|
186
+ adapter.release_lease_pins!
187
+ rescue StandardError
188
+ nil
189
+ end
190
+ end
191
+ end
192
+
193
+ #: (?idle_timeout: Numeric?, ?max_age: Numeric?, ?keepalive: Numeric?) -> void
194
+ def async_maintain(idle_timeout: nil, max_age: nil, keepalive: nil)
195
+ return unless idle_timeout || max_age || keepalive
196
+
197
+ raw_pool&.maintain(idle_timeout:, max_age:, keepalive:)
198
+ end
199
+ end
200
+ end
201
+ end
@@ -0,0 +1,80 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ # A physical driver connection and the bookkeeping the raw pool and adapters keep about it.
7
+ class RawEntry
8
+ #: untyped
9
+ attr_reader :raw
10
+
11
+ # The adapter currently attached to this connection, if any.
12
+ #
13
+ #: untyped
14
+ attr_accessor :owner
15
+
16
+ #: Float
17
+ attr_reader :created_at
18
+
19
+ #: Float
20
+ attr_accessor :last_used_at
21
+
22
+ # Whether the owning adapter has pinned this connection to its fiber.
23
+ #
24
+ #: bool
25
+ attr_accessor :pinned
26
+
27
+ # Scratch space for the handler (statement pool, applied session settings, configured timezone).
28
+ #
29
+ #: Hash[Symbol, untyped]
30
+ attr_reader :state
31
+
32
+ #: (untyped raw) -> void
33
+ def initialize(raw)
34
+ @raw = raw
35
+ @owner = nil
36
+ @created_at = @last_used_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
37
+ @pinned = false
38
+ @tainted = false
39
+ @retired = false
40
+ @state = {}
41
+ end
42
+
43
+ # A tainted connection is in an unknown state and is closed instead of reused.
44
+ #
45
+ #: () -> bool
46
+ attr_reader :tainted
47
+
48
+ #: () -> void
49
+ def taint!
50
+ @tainted = true
51
+ end
52
+
53
+ # A retired connection is closed when it is next checked in, as by `ConnectionPool#recycle!`.
54
+ #
55
+ #: () -> bool
56
+ attr_reader :retired
57
+
58
+ #: () -> void
59
+ def retire!
60
+ @retired = true
61
+ end
62
+
63
+ # For a handler that reset the connection to a known state.
64
+ #
65
+ #: () -> void
66
+ def clear_taint!
67
+ @tainted = false
68
+ end
69
+
70
+ # Whether, at monotonic time `now`, it has been idle past `idle_timeout` or open past `max_age`.
71
+ #
72
+ #: (Float now, Numeric? idle_timeout, Numeric? max_age) -> bool
73
+ def expired?(now, idle_timeout, max_age)
74
+ return true if idle_timeout && now - last_used_at > idle_timeout
75
+
76
+ max_age ? now - created_at > max_age : false
77
+ end
78
+ end
79
+ end
80
+ end