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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7d0c8964254966b30d5e8b90bea9161bcf3362d113890629178203be86fbc1e8
4
+ data.tar.gz: b5d200377de39c612a30e730d239314775723b344ea2b25f92b3610f84a6e701
5
+ SHA512:
6
+ metadata.gz: a71d5b48a70d96498abda155ceb55ccdd8d2cfd0a662c34849d97c690d415d785550afb21ca67096092e2a8c02f3965cc7d1269088a2e8cb1da31f2eeca4dfcc
7
+ data.tar.gz: 355efbfe602f2acf99942c96c4f53033510a8bbdc8365f0a4732bfb23a494dbdd0c453962252fb1b79bb45ac282d4330e1d6e5be2dcf2f683b847bc772348e65
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2026 Minty Fresh
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,349 @@
1
+ # ActiveRecord::AsyncConnectionPool
2
+
3
+ Lets fibers share a small pool of physical database connections, so the number of connections doesn't grow with the
4
+ number of concurrent fibers. For Rails apps on fiber servers (Falcon) and fiber job runners.
5
+
6
+ Requires Ruby >= 3.3 and ActiveRecord 8.1 (>= 8.1, < 8.2).
7
+
8
+ ## Why?
9
+
10
+ With `config.active_support.isolation_level = :fiber`, ActiveRecord gives every fiber its own lease in the connection
11
+ pool. Once any code takes a sticky lease (`lease_connection`, `.connection`, both used widely by Rails and gems), the
12
+ fiber holds that physical connection until the request or job ends. A fiber waiting on an HTTP call, a sleep, or an
13
+ idle stream (SSE, MCP, websockets) keeps its connection while doing nothing, so concurrency is capped by the pool size,
14
+ which is capped by what the database accepts.
15
+
16
+ With `raw_pool: true`, ActiveRecord still hands every fiber its own adapter (the pool of adapters is large by default),
17
+ but adapters don't own a physical connection. Physical ("raw") connections live in a small shared raw pool, and an
18
+ adapter attaches one only while it:
19
+
20
+ - runs a statement,
21
+ - has a transaction open (from `BEGIN` to `COMMIT` or `ROLLBACK`), or
22
+ - is pinned (explicitly with `pin { }`, or because it changed session state, see below).
23
+
24
+ Otherwise the raw connection goes back to the pool for other fibers.
25
+
26
+ ## Installation
27
+
28
+ Add this line to your application's Gemfile:
29
+
30
+ ```ruby
31
+ gem 'active_record-async_connection_pool'
32
+ ```
33
+
34
+ And then execute:
35
+
36
+ ```bash
37
+ $ bundle
38
+ ```
39
+
40
+ Enable it per database in `config/database.yml`, and set the isolation level to `:fiber`:
41
+
42
+ ```yaml
43
+ production:
44
+ adapter: postgresql
45
+ database: app_production
46
+ raw_pool: true
47
+ max_raw_connections: 10
48
+ ```
49
+
50
+ ```ruby
51
+ # config/application.rb
52
+ config.active_support.isolation_level = :fiber
53
+ ```
54
+
55
+ Without `raw_pool: true` a database behaves exactly as stock ActiveRecord.
56
+
57
+ Rails' generated `database.yml` sets `max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>` under `default:`,
58
+ which every environment inherits. That caps the adapter pool at 5, so the sixth fiber waits on ActiveRecord's queue
59
+ even when raw connections are free. Remove `max_connections` (and `pool`) from databases with `raw_pool: true`, or set
60
+ it well above `max_raw_connections`. A warning is logged at boot when the adapter pool is no larger than the raw pool.
61
+
62
+ ### Configuration
63
+
64
+ These keys go in the database's `database.yml` entry:
65
+
66
+ | Key | Default | Meaning |
67
+ |-----------------------|----------------------------------------------------------------|---------------------------------------------------------|
68
+ | `raw_pool` | off | Enables the gem for this database |
69
+ | `max_raw_connections` | 5 | Physical connections the raw pool opens at most |
70
+ | `session_state` | `ActiveRecord::AsyncConnectionPool.session_state` (`:pin`) | `:pin` or `:raise`, see [Session state](#session-state) |
71
+ | `reset_on_checkin` | `ActiveRecord::AsyncConnectionPool.reset_on_checkin` (`false`) | Reset every raw connection when it returns to the pool |
72
+
73
+ The adapter pool, which limits fibers holding an adapter, is sized by `max_connections` (or `pool`) when set. When
74
+ neither is set it is raised to 1024, since the raw pool is what limits real connections.
75
+
76
+ The defaults for `session_state` and `reset_on_checkin` can be changed globally, for example in an initializer:
77
+
78
+ ```ruby
79
+ ActiveRecord::AsyncConnectionPool.session_state = :raise
80
+ ActiveRecord::AsyncConnectionPool.reset_on_checkin = true
81
+ ```
82
+
83
+ A database's own key overrides them. When `raw_pool` is on, `session_state` and `max_raw_connections` are validated:
84
+ `ArgumentError` unless `session_state` is `pin` or `raise` and `max_raw_connections` is a positive integer. The keys
85
+ can also be given in a database URL (`?raw_pool=true&max_raw_connections=10`), where `false`, `0`, `off` and an empty
86
+ value are false.
87
+
88
+ A waiter for a raw connection waits up to the pool's `checkout_timeout`, then raises
89
+ `ActiveRecord::ConnectionTimeoutError`.
90
+
91
+ ### Falcon
92
+
93
+ ```ruby
94
+ # config/application.rb
95
+ config.active_support.isolation_level = :fiber
96
+ ```
97
+
98
+ ```yaml
99
+ # config/database.yml
100
+ production:
101
+ adapter: postgresql
102
+ url: <%= ENV['DATABASE_URL'] %>
103
+ raw_pool: true
104
+ max_raw_connections: 5
105
+ ```
106
+
107
+ A Falcon process can then hold thousands of open streams and in-flight requests on 5 database connections. Use
108
+ `max_raw_connections` per process, as you would the pool size.
109
+
110
+ ### Supported adapters
111
+
112
+ | Adapter | Supported | Queries yield to other fibers |
113
+ |--------------|-----------|----------------------------------------------------|
114
+ | `postgresql` | yes | yes |
115
+ | `trilogy` | yes | yes |
116
+ | `sqlite3` | yes | no, a query blocks the thread (it runs in-process) |
117
+ | `mysql2` | no | no, its C calls block the reactor |
118
+
119
+ Subclasses of a supported adapter class inherit its support, except CockroachDB's adapter, which is refused. An
120
+ unsupported adapter with `raw_pool: true` raises `ActiveRecord::AsyncConnectionPool::UnsupportedAdapterError` at boot.
121
+
122
+ ## Pinning
123
+
124
+ `pin` keeps the same raw connection attached for the block. Use it for anything that lives in the database session:
125
+ `SET`, `LISTEN`, temp tables, session advisory locks, and so on. It's available on the connection and on the pool:
126
+
127
+ ```ruby
128
+ ActiveRecord::Base.connection_pool.pin do |connection|
129
+ connection.execute('SET statement_timeout = 5000')
130
+ connection.execute('LISTEN events')
131
+ # ...
132
+ end
133
+
134
+ ActiveRecord::Base.with_connection do |connection|
135
+ connection.pin do
136
+ connection.execute('CREATE TEMPORARY TABLE ids (id bigint)')
137
+ # ...
138
+ end
139
+ end
140
+ ```
141
+
142
+ The pool form leases a connection, pins it for the block and yields it. Without `raw_pool`, `pin` just yields.
143
+ `connection.raw_pinned?` tells whether the raw connection is pinned now (ActiveRecord's own `pinned` flag is
144
+ unrelated: it marks a connection pinned with `pin_connection!`).
145
+
146
+ `connection.raw_connection` (the driver's connection) pins the raw connection until the lease ends and taints it, as its
147
+ session state is unknown afterwards. The `get_advisory_lock` and `release_advisory_lock` adapter methods (PostgreSQL and
148
+ trilogy) pin from the first lock until the last is released.
149
+
150
+ ## Session state
151
+
152
+ Session state (a `SET`, a `LISTEN`, a temp table) belongs to a raw connection, which other fibers will use next. The
153
+ gem reads each statement's SQL, and when one leaves state in the session:
154
+
155
+ - inside a `pin { }`, the raw connection is tainted: when the pin ends it is reset or closed instead of being shared as
156
+ is;
157
+ - outside a pin, the policy in `session_state` applies:
158
+ - `:pin` (the default) pins the adapter's raw connection until the lease ends (the request or job), taints it, logs a
159
+ warning (with the calling line) and instruments `session_state`;
160
+ - `:raise` raises `ActiveRecord::AsyncConnectionPool::UnpinnedSessionStateError`, so such statements are found in
161
+ development and tests.
162
+
163
+ ```ruby
164
+ connection.execute('SET statement_timeout = 5000')
165
+ # :pin => the connection stays pinned until the lease ends, with a warning
166
+ # :raise => raises UnpinnedSessionStateError
167
+
168
+ connection.pin { connection.execute('SET statement_timeout = 5000') } # fine under both
169
+ ```
170
+
171
+ Statements run by Rails or the gem themselves (`configure_connection`, resets) aren't checked.
172
+
173
+ ### What is detected
174
+
175
+ Statements are split and lexed the way the database does, so quoted text and comments are ignored.
176
+
177
+ PostgreSQL statements are read by one of two detectors, chosen with
178
+ `ActiveRecord::AsyncConnectionPool.postgresql_detector` (in an initializer) or the
179
+ `ASYNC_CONNECTION_POOL_POSTGRESQL_DETECTOR` environment variable:
180
+
181
+ - `:auto` (the default): `:pg_query` when the [pg_query](https://github.com/pganalyze/pg_query) gem can be loaded,
182
+ `:lexer` otherwise
183
+ - `:pg_query`: PostgreSQL's own parser, through pg_query. If the gem can't be loaded, setting it or setting up a pool
184
+ raises `ActiveRecord::AsyncConnectionPool::DetectorUnavailableError`
185
+ - `:lexer`: the gem's own lexer, with no dependency
186
+
187
+ pg_query isn't a dependency of this gem: add `gem 'pg_query'` to your Gemfile to use it. Both detectors detect the forms
188
+ below, but pg_query reads names from the parse tree, so quoted ones (`"pg_advisory_lock"(1)`, `"pg_temp".t`) are
189
+ detected too. SQL pg_query can't parse (syntax newer than its parser) is treated as changing session state, and
190
+ instruments `parse_error`, as does any error reading the parse tree. Results are cached per SQL string (the last 1,000).
191
+
192
+ PostgreSQL:
193
+
194
+ - `SET` (but not `SET LOCAL`, `SET TRANSACTION`, `SET CONSTRAINTS`), `RESET`, `set_config(..., false)` (anything but a
195
+ literal `true` third argument)
196
+ - `LISTEN`, `PREPARE` (but not `PREPARE TRANSACTION`), `LOAD`
197
+ - `CREATE TEMP` objects and objects created in `pg_temp` (a table with `ON COMMIT DROP` is not state), and
198
+ `SELECT/WITH ... INTO TEMP` or `INTO pg_temp.name`
199
+ - `DECLARE ... WITH HOLD`
200
+ - `pg_advisory_lock`, `pg_advisory_lock_shared` and the `pg_try_` forms (not the transaction-scoped `xact` forms)
201
+ - `DO` and `CALL`, whatever they contain
202
+ - `DISCARD ALL` and `DEALLOCATE`, which leave the gem's records of the session (prepared statements, settings)
203
+ stale until the raw connection is reset; not `UNLISTEN`, the other `DISCARD`s or `NOTIFY`
204
+
205
+ SQLite:
206
+
207
+ - `PRAGMA name = value` and `PRAGMA name(value)` (reading pragmas and `table_info` and the like are not)
208
+ - `ATTACH`, `DETACH`, `load_extension()`
209
+ - `CREATE TEMP ...` objects, and objects created in the `temp` schema
210
+
211
+ MySQL (trilogy):
212
+
213
+ - every `SET`, including `SET TRANSACTION`, and `CALL`
214
+ - user variables assigned with `:=` or `INTO @var`
215
+ - `GET_LOCK()`, `CREATE TEMPORARY TABLE`, `PREPARE`
216
+ - `LOCK TABLES`, `LOCK INSTANCE`, `FLUSH TABLES ... WITH READ LOCK`, `USE`, `HANDLER`
217
+ - lexing follows the session's `sql_mode` (`NO_BACKSLASH_ESCAPES`, `ANSI_QUOTES`)
218
+
219
+ ### Reset
220
+
221
+ A tainted raw connection is made clean before another fiber gets it, when it's detached (`reset_on_checkin: true` does
222
+ this for every raw connection):
223
+
224
+ - PostgreSQL runs `DISCARD ALL` and configures the connection again
225
+ - SQLite and MySQL can't reset a session in place, so the raw connection is closed (a new one is opened when needed)
226
+
227
+ A connection that can't be reset, or is in a transaction or broken, is closed.
228
+
229
+ ### Limitations
230
+
231
+ - Detection reads SQL text only, with either PostgreSQL detector. Functions, triggers, stored procedures and dynamic
232
+ SQL can change session state invisibly (`SELECT my_function()` that runs a `SET`). Wrap such calls in `pin { }`, or
233
+ set `reset_on_checkin: true`. PostgreSQL's `DO` and `CALL` and MySQL's `CALL` are always treated as changing state.
234
+ - PostgreSQL SQL is only inspected, by either detector, when it contains one of the words the detected forms need
235
+ (`set`, `listen`, `temp`, `advisory`, ...). A name spelled without them, such as the Unicode-escaped identifier in
236
+ `SELECT U&"pg_\0061dvisory_lock"(1)`, is not detected.
237
+ - Private in-memory SQLite databases (`:memory:`, `mode=memory` without `cache=shared`) have a single raw connection,
238
+ shared by every fiber. Closing it would delete the database, so a tainted one is kept, and a warning is logged once
239
+ that session state carries over.
240
+ - `recycle!` and `disconnect!` close idle raw connections, so, as in stock ActiveRecord, they close a private
241
+ in-memory SQLite database and its data is lost.
242
+ - Only `:memory:` and `file:` URIs with `:memory:` or `mode=memory` count as private in-memory SQLite databases.
243
+ Other in-memory forms, such as `file:x?vfs=memdb`, are treated as files, so their connections may be closed and
244
+ reopened empty.
245
+ - SQLite blocks the thread during a query, so pooling there frees idle fibers' connections but queries don't overlap.
246
+ Trilogy yields during a query. `mysql2` isn't supported.
247
+ - The PostgreSQL lexer matches function calls by their unquoted name: `SELECT "pg_advisory_lock"(1)` (a quoted
248
+ identifier) and objects created in a quoted `"pg_temp"` schema are not detected. pg_query detects both.
249
+ - On MySQL, Rails' `quote_string` borrows a raw connection (it escapes through the driver).
250
+ - MariaDB's `/*M!...*/` executable comments are lexed as code, as MySQL's `/*!...*/` are. On MySQL proper, `/*M!...*/`
251
+ is an ordinary comment, so detection can read a statement hidden in one as a real statement and a crafted statement
252
+ can slip past it there. Don't rely on detection as a security boundary.
253
+ - Schema changes made by another process surface as `ActiveRecord::PreparedStatementCacheExpired` inside
254
+ transactions, exactly as in stock Rails.
255
+
256
+ ## Notifications
257
+
258
+ Instrumented with `ActiveSupport::Notifications`:
259
+
260
+ | Name | Payload | When |
261
+ |-----------------------------------------------------|--------------------------|------------------------------------------------------------------|
262
+ | `attach.active_record_async_connection_pool` | `connection` | An adapter attaches a raw connection (a block) |
263
+ | `detach.active_record_async_connection_pool` | `connection`, `closed` | An adapter gives it back; `closed` if closed instead of returned |
264
+ | `pin.active_record_async_connection_pool` | `reason` | A pin starts (for `pin { }`, a block spanning the pin) |
265
+ | `unpin.active_record_async_connection_pool` | `reason`, `connection` | A lease pin ends |
266
+ | `wait.active_record_async_connection_pool` | `wait_time` | A fiber waits for a raw connection (a block) |
267
+ | `session_state.active_record_async_connection_pool` | `sql`, `policy` (`:pin`) | A statement was pinned under `session_state: :pin` |
268
+ | `parse_error.active_record_async_connection_pool` | `sql`, `error` | pg_query couldn't parse or read SQL: it counts as session state |
269
+
270
+ `reason` is `:explicit` for `pin { }`, and for lease pins `:session_state`, `:raw_connection`, `:advisory_lock`,
271
+ `:pin_connection` (a pinned connection, as in transactional tests) or `:preconnect`.
272
+
273
+ A `pin { }` is one `pin` event whose start and finish are the pin's, so its duration is how long the raw connection
274
+ was pinned. A lease pin has no block to span: it fires `pin` (an instant event) when it starts and `unpin`, with the
275
+ same `reason`, when it ends, which is when the lease ends, the last advisory lock is released, or the adapter is
276
+ disconnected.
277
+
278
+ ```ruby
279
+ ActiveSupport::Notifications.subscribe('wait.active_record_async_connection_pool') do |event|
280
+ Rails.logger.warn("raw pool wait: #{event.payload[:wait_time]}s")
281
+ end
282
+ ```
283
+
284
+ ## Pool stats
285
+
286
+ `connection_pool.stat` gains a `raw` key:
287
+
288
+ ```ruby
289
+ ActiveRecord::Base.connection_pool.stat[:raw]
290
+ # => { size: 5, connections: 3, busy: 1, idle: 2, waiting: 0, pinned: 1 }
291
+ ```
292
+
293
+ - `size`: the limit (`max_raw_connections`)
294
+ - `connections`: raw connections open now (busy + idle)
295
+ - `busy`, `idle`: those attached to an adapter, and those waiting in the pool
296
+ - `waiting`: fibers waiting for a raw connection
297
+ - `pinned`: busy connections that are pinned
298
+
299
+ ## Pool maintenance
300
+
301
+ ActiveRecord's pool maintenance applies to the raw connections as well:
302
+
303
+ | ActiveRecord | Raw pool |
304
+ |--------------------------------------|--------------------------------------------------------------------------------|
305
+ | `idle_timeout` (`flush`) | closes idle raw connections unused for longer |
306
+ | `max_age` (`retire_old_connections`) | retires idle raw connections older than that |
307
+ | `keepalive` (`keep_alive`) | health checks idle raw connections unused for longer, closing unhealthy ones |
308
+ | `min_connections` (`preconnect`) | opens raw connections up to the minimum, no further than `max_raw_connections` |
309
+ | `recycle!` | marks the raw connections for replacement (closes idle ones now) |
310
+ | `disconnect`, `discard!` (fork) | closes the raw connections, or drops them without closing after fork |
311
+
312
+ Each hook applies only its own limit, so a reaper run health checks each idle raw connection at most once.
313
+ `idle_timeout` and `max_age` close the longest idle raw connections first and leave `min_connections` open (except
314
+ `flush!`, which closes every idle one, as ActiveRecord's does); a failed health check closes one regardless. A private
315
+ in-memory SQLite database's only connection is never closed by `idle_timeout` or `max_age`. Busy raw connections are
316
+ never touched.
317
+
318
+ ## Development
319
+
320
+ ```bash
321
+ $ mise install # Ruby, plus the PostgreSQL client and sqlite3 CLI
322
+ $ docker compose up -d --wait # PostgreSQL (port 5435) and MySQL (port 3307)
323
+ $ bin/rspec # SQLite
324
+ $ bin/rubocop
325
+ ```
326
+
327
+ The specs run against a dummy Rails application in `spec/dummy`. The adapter is selected with `DATABASE_ADAPTER`
328
+ (`sqlite3`, `postgresql`, `trilogy`), and the server with `DATABASE_HOST`, `DATABASE_PORT`, `DATABASE_USERNAME` and
329
+ `DATABASE_PASSWORD`:
330
+
331
+ ```bash
332
+ $ DATABASE_ADAPTER=postgresql DATABASE=async_connection_pool_test DATABASE_HOST=127.0.0.1 DATABASE_PORT=5435 \
333
+ DATABASE_USERNAME=async_connection_pool DATABASE_PASSWORD=async_connection_pool bin/rspec
334
+ $ DATABASE_ADAPTER=trilogy DATABASE=async_connection_pool_test DATABASE_HOST=127.0.0.1 DATABASE_PORT=3307 \
335
+ DATABASE_USERNAME=async_connection_pool DATABASE_PASSWORD=async_connection_pool bin/rspec
336
+ ```
337
+
338
+ The PostgreSQL specs run under `:auto` (pg_query, which is in the Gemfile's test group); set
339
+ `ASYNC_CONNECTION_POOL_POSTGRESQL_DETECTOR=lexer` to run them under the lexer. The detector specs run both regardless.
340
+
341
+ `bin/rspec spec/falcon` runs the gem under a real Falcon server, with 100 open SSE streams and bursts of requests
342
+ sharing two raw connections, then plain Rails and GraphQL endpoints (with and without graphql-ruby's
343
+ AsyncDataloader) whose queries sleep in the database, on a second server with ten raw connections.
344
+ `bin/rails-adapter-tests sqlite3|postgresql|trilogy` runs ActiveRecord's own test suite for an adapter with
345
+ `raw_pool` forced on (`trilogy` against the MySQL server above).
346
+
347
+ ## License
348
+
349
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/setup'
4
+ require 'bundler/gem_tasks'
5
+ require 'rspec/core/rake_task'
6
+ require 'rubocop/rake_task'
7
+
8
+ RSpec::Core::RakeTask.new(:spec)
9
+ RuboCop::RakeTask.new
10
+
11
+ task default: %i[spec rubocop]
@@ -0,0 +1,276 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module AdapterExtension
7
+ # Moving a raw connection into and out of an adapter, with the bookkeeping that describes the physical
8
+ # connection (`@verified`, `@last_activity`, `@connected_since`) moving with it.
9
+ module Attachment
10
+ # Releases one lease pin before the lease ends, eg. once the last advisory lock is released.
11
+ #
12
+ #: (Symbol reason) -> void
13
+ def release_lease_pin!(reason) # :nodoc:
14
+ return unless @async_lease_pins.delete(reason)
15
+
16
+ async_instrument_unpin(reason)
17
+ async_sync_pinned
18
+ async_detach_if_idle
19
+ end
20
+
21
+ # Drops the attached raw connection, whatever its state, without taking the adapter lock: the pool removed the
22
+ # adapter (eg. its owner died), so nothing else will give the raw connection back.
23
+ #
24
+ #: () -> void
25
+ def drop_raw_connection! # :nodoc:
26
+ async_clear_lease_pins
27
+ return unless (entry = @async_entry)
28
+
29
+ async_drop(entry)
30
+ end
31
+
32
+ private
33
+
34
+ # Lease pins end with an `unpin` event each, as they started with a `pin` event.
35
+ #
36
+ #: () -> void
37
+ def async_clear_lease_pins
38
+ reasons = @async_lease_pins.dup
39
+ @async_lease_pins.clear
40
+ reasons.each { |reason| async_instrument_unpin(reason) }
41
+ end
42
+
43
+ #: (Symbol reason) -> void
44
+ def async_instrument_unpin(reason)
45
+ ActiveSupport::Notifications.instrument(UNPIN, reason:, connection: self)
46
+ end
47
+
48
+ #: () -> void
49
+ def async_sync_pinned
50
+ @async_entry&.pinned = raw_pinned?
51
+ end
52
+
53
+ #: (?configure: bool) -> void
54
+ def async_attach!(configure: true)
55
+ raw_pool = async_raw_pool
56
+ ActiveSupport::Notifications.instrument(ATTACH, connection: self) do
57
+ entry = raw_pool.checkout { async_build_raw_connection(configure:) }
58
+ begin
59
+ async_adopt(raw_pool, entry)
60
+ rescue Exception # rubocop:disable Lint/RescueException
61
+ async_forget(entry)
62
+ async_remove_quietly(entry)
63
+ raise
64
+ end
65
+ end
66
+ end
67
+
68
+ # A connection built just now is verified. A reused one is not, as after ActiveRecord's checkout, so
69
+ # ActiveRecord verifies it unless it was used within `verify_timeout`. Statements the handler runs to adopt the
70
+ # connection count as in flight, so finishing one does not detach it.
71
+ #
72
+ #: (RawPool raw_pool, RawEntry entry) -> void
73
+ def async_adopt(raw_pool, entry)
74
+ entry.owner = self
75
+ @async_entry = entry
76
+ @raw_connection = entry.raw
77
+ @verified = !entry.state.key?(:last_activity)
78
+ @last_activity = entry.state.fetch(:last_activity, entry.last_used_at)
79
+ @connected_since = entry.created_at
80
+ async_sync_pinned
81
+ @async_depth += 1
82
+ begin
83
+ raw_pool.handler.adopt(self, entry)
84
+ ensure
85
+ @async_depth -= 1
86
+ end
87
+ end
88
+
89
+ # Builds a raw connection through the adapter's own `connect` and `configure_connection`, so every
90
+ # driver-specific setting Rails applies runs, then hands it over.
91
+ #
92
+ #: (configure: bool) -> untyped
93
+ def async_build_raw_connection(configure:)
94
+ @async_building = true
95
+ @raw_connection = nil
96
+ connect
97
+ async_configure if configure
98
+ @raw_connection
99
+ rescue Exception # rubocop:disable Lint/RescueException
100
+ raw = @raw_connection
101
+ @raw_connection = nil
102
+ begin
103
+ async_raw_pool&.handler&.close(raw) if raw
104
+ rescue StandardError
105
+ nil
106
+ end
107
+ raise
108
+ ensure
109
+ @async_building = false
110
+ end
111
+
112
+ # As in `reconnect!`, configuration runs with no transaction state in the way: a lazy transaction must not
113
+ # materialize on a connection that is not configured yet. It materializes once attached.
114
+ #
115
+ #: () -> void
116
+ def async_configure
117
+ transactions = @transaction_manager
118
+ @transaction_manager = ConnectionAdapters::TransactionManager.new(self)
119
+ @verified = true
120
+ @last_activity = Process.clock_gettime(Process::CLOCK_MONOTONIC)
121
+ configure_connection
122
+ ensure
123
+ @transaction_manager = transactions
124
+ end
125
+
126
+ # Returns the entry to the pool if the handler finds it clean, after a reset if it is tainted or
127
+ # `reset_on_checkin` is set, and closes it otherwise. A handler error counts as not clean.
128
+ #
129
+ #: (RawEntry entry) -> void
130
+ def async_detach(entry)
131
+ raw_pool = async_raw_pool
132
+ keep = false
133
+ @async_depth += 1
134
+ begin
135
+ keep = async_returnable?(raw_pool.handler, entry)
136
+ rescue StandardError
137
+ keep = false
138
+ ensure
139
+ @async_depth -= 1
140
+ entry.state[:last_activity] = @last_activity
141
+ async_forget(entry)
142
+ keep ? raw_pool.checkin(entry) : async_remove_quietly(entry)
143
+ ActiveSupport::Notifications.instrument(DETACH, connection: self, closed: !keep)
144
+ end
145
+ end
146
+
147
+ #: (Handler handler, RawEntry entry) -> bool
148
+ def async_returnable?(handler, entry)
149
+ handler.release(self, entry)
150
+ if entry.tainted || handler.options.reset_on_checkin?
151
+ return false unless without_session_state_detection { handler.reset(self, entry) }
152
+
153
+ entry.clear_taint!
154
+ end
155
+ handler.clean?(entry)
156
+ end
157
+
158
+ # An exception that interrupts a statement (a stopped task, a timeout) leaves its result unread and the
159
+ # session's state unknown, so the raw connection is removed rather than returned. Any non-StandardError is
160
+ # taken as such an interruption; for the rest the handler says whether a statement is still running.
161
+ #
162
+ #: [T] () { () -> T } -> T
163
+ def async_in_flight
164
+ yield
165
+ rescue Exception => error # rubocop:disable Lint/RescueException
166
+ entry = @async_entry
167
+ if entry && async_interrupted?(error, entry)
168
+ async_lose_transaction if @async_in_transaction || async_materialized_transaction?
169
+ async_drop(entry)
170
+ end
171
+ raise
172
+ end
173
+
174
+ # The open transaction went with the removed raw connection, and the database rolls it back when that
175
+ # connection closes. Its savepoints are invalidated so rolling them back sends nothing, and the real
176
+ # transaction's `ROLLBACK` is skipped, so unwinding never attaches (or builds) a raw connection.
177
+ #
178
+ #: () -> void
179
+ def async_lose_transaction
180
+ @async_transaction_lost = true
181
+ transaction_manager.instance_variable_get(:@stack).each(&:invalidate!)
182
+ end
183
+
184
+ # The database rolled the lost transaction back when its raw connection was closed, so `ROLLBACK` is skipped.
185
+ #
186
+ #: () -> bool
187
+ def async_lost_transaction_rolled_back?
188
+ return false unless @async_transaction_lost
189
+
190
+ @async_transaction_lost = false
191
+ true
192
+ end
193
+
194
+ # Until the lost transaction is rolled back, a statement would run outside it on another raw connection, so
195
+ # it is refused instead.
196
+ #
197
+ #: () -> void
198
+ def async_check_transaction_lost!
199
+ return unless @async_transaction_lost
200
+ return @async_transaction_lost = false unless open_transactions.positive?
201
+
202
+ raise async_transaction_lost_error
203
+ end
204
+
205
+ # ActiveRecord pops the transaction before `COMMIT`, so no transaction looks open here: without this, `COMMIT`
206
+ # would go to another raw connection and report success for writes the database rolled back.
207
+ # `within_new_transaction` turns the error into a failed transaction, so `after_commit` callbacks do not run.
208
+ #
209
+ #: () -> void
210
+ def async_refuse_lost_commit!
211
+ return unless @async_transaction_lost
212
+
213
+ async_forget_lost_transaction
214
+ raise async_transaction_lost_error
215
+ end
216
+
217
+ # The lease is over (or the commit refused), so the lost transaction cannot leak into what comes next.
218
+ #
219
+ #: () -> void
220
+ def async_forget_lost_transaction
221
+ @async_transaction_lost = false
222
+ @async_in_transaction = false unless @async_entry
223
+ end
224
+
225
+ #: () -> ActiveRecord::ConnectionFailed
226
+ def async_transaction_lost_error
227
+ ActiveRecord::ConnectionFailed.new(
228
+ 'the transaction was lost when its raw connection was removed after an interrupted statement',
229
+ connection_pool: @pool
230
+ )
231
+ end
232
+
233
+ #: (Exception error, RawEntry entry) -> bool
234
+ def async_interrupted?(error, entry)
235
+ !error.is_a?(StandardError) || async_raw_pool.handler.in_flight?(entry.raw)
236
+ rescue StandardError
237
+ true
238
+ end
239
+
240
+ # Drops the attached entry: its connection is gone or being replaced.
241
+ #
242
+ #: (RawEntry entry) -> void
243
+ def async_drop(entry)
244
+ async_raw_pool&.handler&.release(self, entry)
245
+ rescue StandardError
246
+ nil
247
+ ensure
248
+ async_forget(entry)
249
+ async_remove_quietly(entry)
250
+ end
251
+
252
+ #: (RawEntry entry) -> void
253
+ def async_forget(entry)
254
+ entry.owner = nil
255
+ entry.pinned = false
256
+ @async_entry = nil
257
+ @raw_connection = nil
258
+ @raw_connection_dirty = false
259
+ @async_in_transaction = false
260
+ @verified = false
261
+ @last_activity = nil
262
+ @connected_since = nil
263
+ end
264
+
265
+ # The entry's state is unknown, so it is closed. A close error is moot: the slot is freed either way.
266
+ #
267
+ #: (RawEntry entry) -> void
268
+ def async_remove_quietly(entry)
269
+ async_raw_pool&.remove(entry)
270
+ rescue StandardError
271
+ nil
272
+ end
273
+ end
274
+ end
275
+ end
276
+ end