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,336 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'active_record/async_connection_pool/raw_entry'
5
+
6
+ module ActiveRecord
7
+ module AsyncConnectionPool
8
+ # A bounded pool of physical driver connections. Waiters block on a per-waiter `Thread::Queue`, which yields to
9
+ # the fiber scheduler, so it serves reactor fibers, threads and the reaper alike.
10
+ class RawPool
11
+ NOTIFICATION = 'wait.active_record_async_connection_pool'
12
+
13
+ # Handed to a waiter when a slot (not an entry) became free: the waiter builds the connection itself.
14
+ SLOT = Object.new.freeze
15
+ private_constant :SLOT
16
+
17
+ #: Integer
18
+ attr_reader :size
19
+
20
+ #: Numeric
21
+ attr_reader :checkout_timeout
22
+
23
+ #: untyped
24
+ attr_reader :handler
25
+
26
+ # Bumped when an adapter clears its statement cache, eg. after a schema change. Statements prepared on a raw
27
+ # connection under an older generation are deallocated before it is used again.
28
+ #
29
+ #: Integer
30
+ attr_reader :statement_generation
31
+
32
+ # The ActiveRecord pool that owns the raw pool, if any, is named in timeout errors.
33
+ #
34
+ #: untyped
35
+ attr_reader :pool
36
+
37
+ # Open connections that `maintain` keeps even when idle past `idle_timeout` or older than `max_age`.
38
+ #
39
+ #: Integer
40
+ attr_reader :min_connections
41
+
42
+ #: (handler: untyped, size: Integer, checkout_timeout: Numeric, ?pool: untyped, ?min_connections: Integer) -> void
43
+ def initialize(handler:, size:, checkout_timeout:, pool: nil, min_connections: 0)
44
+ @handler = handler
45
+ @pool = pool
46
+ @min_connections = min_connections
47
+ @size = size
48
+ @checkout_timeout = checkout_timeout
49
+ @statement_generation = 0
50
+ @mutex = Thread::Mutex.new
51
+ @idle = [] #: Array[RawEntry]
52
+ @busy = [] #: Array[RawEntry]
53
+ @waiters = [] #: Array[Thread::Queue]
54
+ # Slots in use that are in neither list: connections being built, closed or health checked.
55
+ @reserved = 0
56
+ end
57
+
58
+ # Returns an idle entry, or builds one with the block while below `size`, or waits for one FIFO.
59
+ #
60
+ #: (?Numeric? timeout) { () -> untyped } -> RawEntry
61
+ def checkout(timeout = checkout_timeout, &build)
62
+ waiter = nil
63
+ @mutex.synchronize do
64
+ if (entry = @idle.pop)
65
+ @busy << entry
66
+ return entry
67
+ elsif in_use_count < size
68
+ @reserved += 1
69
+ else
70
+ waiter = Thread::Queue.new
71
+ @waiters << waiter
72
+ end
73
+ end
74
+
75
+ result = waiter ? await(waiter, timeout) : SLOT
76
+ return result unless result.equal?(SLOT)
77
+
78
+ build_entry(&build)
79
+ end
80
+
81
+ # Makes the entry idle, or hands it straight to the first waiter. Tainted and retired entries are closed instead.
82
+ # An entry that is not checked out (checked in twice, or from another pool) is ignored, so it can never reach two
83
+ # holders at once.
84
+ #
85
+ #: (RawEntry entry) -> void
86
+ def checkin(entry)
87
+ return remove(entry) if entry.tainted || entry.retired
88
+
89
+ @mutex.synchronize do
90
+ next unless @busy.include?(entry)
91
+
92
+ entry.last_used_at = now
93
+ if (waiter = @waiters.shift)
94
+ waiter << entry
95
+ else
96
+ @busy.delete(entry)
97
+ @idle << entry
98
+ end
99
+ end
100
+ end
101
+
102
+ # Closes the entry and frees its slot.
103
+ #
104
+ #: (RawEntry entry) -> void
105
+ def remove(entry)
106
+ tracked = @mutex.synchronize do
107
+ next false unless @busy.delete(entry) || @idle.delete(entry)
108
+
109
+ @reserved += 1
110
+ true
111
+ end
112
+ close_and_release(entry) if tracked
113
+ end
114
+
115
+ # Closes idle entries past `idle_timeout`, retires those older than `max_age` (both only if the handler finds
116
+ # them `expirable?`, longest idle first, and never below `min_connections` open unless `idle_timeout` is not
117
+ # positive, as ActiveRecord's `flush!` passes), and closes those that fail `healthy?` after sitting unused for
118
+ # longer than `keepalive`. Busy entries are never touched.
119
+ #
120
+ #: (idle_timeout: Numeric?, max_age: Numeric?, keepalive: Numeric?) -> void
121
+ def maintain(idle_timeout:, max_age:, keepalive:)
122
+ expired, checks = take_for_maintenance(idle_timeout, max_age, keepalive)
123
+
124
+ expired.each { |entry| close_and_release(entry, quiet: true) }
125
+ checks.each do |entry|
126
+ if healthy?(entry)
127
+ return_to_pool(entry)
128
+ else
129
+ close_and_release(entry, quiet: true)
130
+ end
131
+ end
132
+ end
133
+
134
+ #: () -> Integer
135
+ def bump_statement_generation!
136
+ @mutex.synchronize { @statement_generation += 1 }
137
+ end
138
+
139
+ # Drops every entry without closing it, for use after fork (the connections belong to the parent). The handler
140
+ # detaches each from the parent's session.
141
+ #
142
+ #: () -> void
143
+ def discard!
144
+ entries = @mutex.synchronize do
145
+ taken = @idle + @busy
146
+ @idle.clear
147
+ @busy.clear
148
+ @reserved = 0
149
+ taken
150
+ end
151
+ entries.each do |entry|
152
+ @handler.discard(entry.raw)
153
+ rescue StandardError
154
+ nil
155
+ end
156
+ end
157
+
158
+ # Closes every idle entry. Busy entries are closed by the adapters holding them.
159
+ #
160
+ #: () -> void
161
+ def disconnect!
162
+ expired = @mutex.synchronize do
163
+ taken = @idle
164
+ @idle = []
165
+ @reserved += taken.size
166
+ taken
167
+ end
168
+ expired.each { |entry| close_and_release(entry, quiet: true) }
169
+ end
170
+
171
+ # Retires every open entry, as if past `max_age`: idle ones are closed now, busy ones when checked in.
172
+ #
173
+ #: () -> void
174
+ def recycle!
175
+ @mutex.synchronize { @busy.each(&:retire!) }
176
+ disconnect!
177
+ end
178
+
179
+ # `size` is the limit and `connections` the number open, as in ActiveRecord's `ConnectionPool#stat`.
180
+ #
181
+ #: () -> { size: Integer, connections: Integer, busy: Integer, idle: Integer, waiting: Integer, pinned: Integer }
182
+ def stat
183
+ @mutex.synchronize do
184
+ {
185
+ size:,
186
+ connections: @busy.size + @idle.size,
187
+ busy: @busy.size,
188
+ idle: @idle.size,
189
+ waiting: @waiters.size,
190
+ pinned: @busy.count(&:pinned),
191
+ }
192
+ end
193
+ end
194
+
195
+ private
196
+
197
+ # Removes idle entries due for closing or a health check, keeping their slots reserved. Returns both lists.
198
+ #
199
+ #: (Numeric? idle_timeout, Numeric? max_age, Numeric? keepalive) -> [Array[RawEntry], Array[RawEntry]]
200
+ def take_for_maintenance(idle_timeout, max_age, keepalive)
201
+ @mutex.synchronize do
202
+ t = now
203
+ expired = due_for_expiry(t, idle_timeout, max_age)
204
+ checks = keepalive ? (@idle - expired).select { |e| t - e.last_used_at > keepalive } : []
205
+ @idle -= expired + checks
206
+ @reserved += expired.size + checks.size
207
+ [expired, checks]
208
+ end
209
+ end
210
+
211
+ # Longest idle first, down to `min_connections` open (none kept for a non-positive `idle_timeout`).
212
+ #
213
+ #: (Float at, Numeric? idle_timeout, Numeric? max_age) -> Array[RawEntry]
214
+ def due_for_expiry(at, idle_timeout, max_age)
215
+ due = @idle.select { |e| e.expired?(at, idle_timeout, max_age) && @handler.expirable?(e) }
216
+ retained = idle_timeout && idle_timeout <= 0 ? 0 : min_connections
217
+ due.sort_by(&:last_used_at).first([@idle.size + @busy.size - retained, 0].max)
218
+ end
219
+
220
+ #: () -> Integer
221
+ def in_use_count = @idle.size + @busy.size + @reserved
222
+
223
+ #: () -> Float
224
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
225
+
226
+ # Waits for an entry or a slot. If the wait times out as a hand-off lands, the hand-off is kept.
227
+ #
228
+ #: (Thread::Queue waiter, Numeric? timeout) -> untyped
229
+ def await(waiter, timeout)
230
+ started = now
231
+ payload = { wait_time: 0.0 }
232
+ ActiveSupport::Notifications.instrument(NOTIFICATION, payload) do
233
+ result = pop_or_abandon(waiter, timeout)
234
+ result = abandon(waiter) if result.nil?
235
+ payload[:wait_time] = now - started
236
+ next result if result
237
+
238
+ raise ActiveRecord::ConnectionTimeoutError.new(timeout_message(timeout, payload[:wait_time]),
239
+ connection_pool: @pool)
240
+ end
241
+ end
242
+
243
+ #: (Numeric? timeout, Float wait_time) -> String
244
+ def timeout_message(timeout, wait_time)
245
+ where = (pool = @pool) && " (database: #{pool.db_config.name}, role: #{pool.role}, shard: #{pool.shard})"
246
+ "could not obtain a raw connection within #{timeout} seconds (waited #{wait_time.round(3)} seconds); all " \
247
+ "#{size} raw connections are in use#{where}"
248
+ end
249
+
250
+ # Pops the hand-off. If interrupted (task stop, Timeout, Thread#raise), leaves the queue and returns anything
251
+ # already handed over to the pool so it is not lost.
252
+ #
253
+ #: (Thread::Queue waiter, Numeric? timeout) -> untyped
254
+ def pop_or_abandon(waiter, timeout)
255
+ waiter.pop(timeout:)
256
+ rescue Exception # rubocop:disable Lint/RescueException
257
+ handed = abandon(waiter)
258
+ if handed.equal?(SLOT)
259
+ release_slot
260
+ elsif handed
261
+ checkin(handed)
262
+ end
263
+ raise
264
+ end
265
+
266
+ # Stops waiting after a timeout. Returns what was handed over in the meantime, if anything.
267
+ #
268
+ #: (Thread::Queue waiter) -> untyped
269
+ def abandon(waiter)
270
+ @mutex.synchronize do
271
+ next if @waiters.delete(waiter)
272
+
273
+ # Handed over while we were timing out: it is already in the queue, so take it.
274
+ waiter.pop
275
+ end
276
+ end
277
+
278
+ #: () { () -> untyped } -> RawEntry
279
+ def build_entry
280
+ entry = RawEntry.new(yield)
281
+ @mutex.synchronize do
282
+ @reserved -= 1
283
+ @busy << entry
284
+ end
285
+ entry
286
+ rescue Exception # rubocop:disable Lint/RescueException
287
+ release_slot
288
+ raise
289
+ end
290
+
291
+ # Reserved slot is no longer needed: give it to the first waiter, or free it.
292
+ #
293
+ #: () -> void
294
+ def release_slot
295
+ @mutex.synchronize do
296
+ if (waiter = @waiters.shift)
297
+ waiter << SLOT
298
+ else
299
+ @reserved -= 1
300
+ end
301
+ end
302
+ end
303
+
304
+ #: (RawEntry entry, ?quiet: bool) -> void
305
+ def close_and_release(entry, quiet: false)
306
+ @handler.close_entry(entry)
307
+ rescue StandardError
308
+ raise unless quiet
309
+ ensure
310
+ release_slot
311
+ end
312
+
313
+ # A kept-alive entry goes back to the first waiter if any arrived meanwhile, else idle.
314
+ #
315
+ #: (RawEntry entry) -> void
316
+ def return_to_pool(entry)
317
+ @mutex.synchronize do
318
+ @reserved -= 1
319
+ if (waiter = @waiters.shift)
320
+ @busy << entry
321
+ waiter << entry
322
+ else
323
+ @idle << entry
324
+ end
325
+ end
326
+ end
327
+
328
+ #: (RawEntry entry) -> bool
329
+ def healthy?(entry)
330
+ @handler.healthy?(entry.raw)
331
+ rescue StandardError
332
+ false
333
+ end
334
+ end
335
+ end
336
+ end
@@ -0,0 +1,223 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'strscan'
5
+
6
+ module ActiveRecord
7
+ module AsyncConnectionPool
8
+ # Splits SQL into statements, the way the database's own lexer would, so handlers can tell whether any of them
9
+ # leaves state in the database session. Quoted text and comments are skipped, so a `;` or a keyword inside them is
10
+ # not mistaken for a statement.
11
+ module SessionState
12
+ # How one database lexes quotes and comments.
13
+ #
14
+ # - `comments`: skipped like whitespace. MySQL's executable comments (`/*!...*/`, and MariaDB's `/*M!...*/`) are
15
+ # run, so only their opener and the closing `*/` are skipped. Optimizer hints (`/*+...*/`) are plain comments.
16
+ # - `nested`: whether `/* */` comments nest.
17
+ # - `tokens`: strings and quoted identifiers, tried in order before plain text.
18
+ # - `dollar`: whether `$tag$` opens a dollar-quoted string.
19
+ Dialect = Struct.new(:comments, :nested, :tokens, :dollar, keyword_init: true)
20
+
21
+ SINGLE = /'(?:[^']|'')*'?/
22
+ DOUBLE = /"(?:[^"]|"")*"?/
23
+ BACKTICK = /`(?:[^`]|``)*`?/
24
+ # A word, `$` included, so `a$b$` is one identifier rather than the start of a dollar quote.
25
+ WORD = /[\p{Alnum}_][\p{Alnum}_$]*/
26
+ # Anything else up to a character that can start a token or comment in some dialect.
27
+ OTHER = %r{[^;'"$/\-#`\[*\p{Alnum}_]+}
28
+ # A `$tag$` delimiter. A `$` after an identifier character belongs to the identifier, and `$1` is a positional
29
+ # parameter, so neither opens a dollar-quoted string.
30
+ DOLLAR_TAG = /(?<![\p{Alnum}_$])\$(?:[\p{Alpha}_][\p{Alnum}_]*)?\$/
31
+ # Without these there is one statement and no comment to strip.
32
+ SPLITTING = %r{;|--|/\*|\#}
33
+ # Without these there is also nothing quoted to blank.
34
+ QUOTING = %r{;|--|/\*|[\#'"`$\[]}
35
+ # What quoted text becomes in the code view.
36
+ BLANK = "''"
37
+
38
+ DIALECTS = {
39
+ # Rails turns `standard_conforming_strings` on, so only `E'...'` strings take backslash escapes. A `--` comment
40
+ # ends at a carriage return as well as a line feed.
41
+ postgresql: Dialect.new(
42
+ comments: [/--[^\n\r]*/], nested: true, dollar: true,
43
+ tokens: [/(?<![\p{Alnum}_$])[Ee]'(?:[^'\\]|\\.|'')*'?/m, SINGLE, DOUBLE]
44
+ ),
45
+ sqlite: Dialect.new(
46
+ comments: [/--[^\n]*/], nested: false, dollar: false,
47
+ tokens: [SINGLE, DOUBLE, BACKTICK, /\[[^\]]*\]?/]
48
+ ),
49
+ # MySQL, one per session `sql_mode`. `--` starts a comment only before whitespace, a control character or the
50
+ # end, so `1--1` is arithmetic. Strings take backslash escapes unless NO_BACKSLASH_ESCAPES is set, and `"`
51
+ # quotes a string unless ANSI_QUOTES makes it quote an identifier, which takes no backslash escapes.
52
+ # Each: [backslash escapes in strings, ANSI_QUOTES].
53
+ **{
54
+ mysql: [true, false],
55
+ mysql_no_backslash_escapes: [false, false],
56
+ mysql_ansi_quotes: [true, true],
57
+ mysql_ansi_quotes_no_backslash_escapes: [false, true],
58
+ }.transform_values do |(backslash_escapes, ansi_quotes)|
59
+ Dialect.new(
60
+ comments: [%r{/\*M?!\d*}, %r{\*/}, /--(?=[ \p{Cntrl}]|\z)[^\n]*/, /\#[^\n]*/], nested: false, dollar: false,
61
+ tokens: [
62
+ backslash_escapes ? /'(?:[^'\\]|\\.|'')*'?/m : SINGLE,
63
+ backslash_escapes && !ansi_quotes ? /"(?:[^"\\]|\\.|"")*"?/m : DOUBLE,
64
+ BACKTICK,
65
+ ]
66
+ )
67
+ end,
68
+ }.freeze
69
+
70
+ # `:any` reads the SQL as every known dialect would, for an adapter whose dialect is unknown.
71
+ DIALECT_NAMES = [*DIALECTS.keys, :any].freeze
72
+
73
+ @anchored = Concurrent::Map.new
74
+ @unanchored = Concurrent::Map.new
75
+
76
+ class << self
77
+ # The statements in `sql`, split on `;` outside quotes and comments, each stripped of leading comments and
78
+ # whitespace. Empty statements are dropped. With `:any`, the statements of every dialect's reading.
79
+ #
80
+ #: (String sql, dialect: Symbol) -> Array[String]
81
+ def statements(sql, dialect:)
82
+ return DIALECTS.keys.flat_map { |name| statements(sql, dialect: name) }.uniq if dialect == :any
83
+
84
+ rules = DIALECTS.fetch(dialect) { raise ArgumentError, "unknown SQL dialect: #{dialect.inspect}" }
85
+ return [sql.strip].reject(&:empty?) unless sql.match?(SPLITTING)
86
+
87
+ # Fixed anchor, so lookbehinds see the text before the scan position.
88
+ scan(StringScanner.new(sql, fixed_anchor: true), rules)
89
+ end
90
+
91
+ # Whether any statement in `sql` starts with one of the patterns, ignoring case. A string pattern matches
92
+ # literally. With `:any`, true when any dialect's reading matches.
93
+ #
94
+ #: (String sql, Array[Regexp | String] patterns, dialect: Symbol) -> bool
95
+ def matches?(sql, patterns, dialect:)
96
+ return false if patterns.empty?
97
+
98
+ anchored = patterns.map { |pattern| compile(@anchored, pattern, '\A') }
99
+ statements(sql, dialect:).any? { |statement| anchored.any? { |pattern| pattern.match?(statement) } }
100
+ end
101
+
102
+ # The statements in `sql` as `statements` splits them, with only their code left: each string, quoted
103
+ # identifier and dollar-quoted string becomes `''`, and each run of whitespace or comments a single space. A
104
+ # pattern matched against this view cannot match text inside quotes or comments.
105
+ #
106
+ #: (String sql, dialect: Symbol) -> Array[String]
107
+ def code(sql, dialect:)
108
+ return DIALECTS.keys.flat_map { |name| code(sql, dialect: name) }.uniq if dialect == :any
109
+
110
+ rules = DIALECTS.fetch(dialect) { raise ArgumentError, "unknown SQL dialect: #{dialect.inspect}" }
111
+ return [sql.strip].reject(&:empty?) unless sql.match?(QUOTING)
112
+
113
+ scan(StringScanner.new(sql, fixed_anchor: true), rules, code: String.new(encoding: sql.encoding))
114
+ end
115
+
116
+ # Whether any pattern matches anywhere in the code of any statement in `sql`, ignoring case. Patterns are not
117
+ # anchored; `\A` anchors one at the start of a statement.
118
+ #
119
+ #: (String sql, Array[Regexp | String] patterns, dialect: Symbol) -> bool
120
+ def code_matches?(sql, patterns, dialect:)
121
+ return false if patterns.empty?
122
+
123
+ compiled = patterns.map { |pattern| compile(@unanchored, pattern, '') }
124
+ code(sql, dialect:).any? { |statement| compiled.any? { |pattern| pattern.match?(statement) } }
125
+ end
126
+
127
+ private
128
+
129
+ #: (Concurrent::Map cache, Regexp | String pattern, String prefix) -> Regexp
130
+ def compile(cache, pattern, prefix)
131
+ cache.compute_if_absent(pattern) do
132
+ source, options = pattern.is_a?(Regexp) ? [pattern.source, pattern.options] : [Regexp.escape(pattern), 0]
133
+ options = (options & (Regexp::EXTENDED | Regexp::MULTILINE)) | Regexp::IGNORECASE
134
+ Regexp.new("#{prefix}(?:#{source})", options).freeze
135
+ end
136
+ end
137
+
138
+ # With `code`, statements are built from the code view into that buffer, rather than sliced from the SQL.
139
+ #
140
+ #: (StringScanner scanner, Dialect rules, ?code: String?) -> Array[String]
141
+ def scan(scanner, rules, code: nil)
142
+ result = [] #: Array[String]
143
+ start = nil #: Integer?
144
+ until scanner.eos?
145
+ position = scanner.pos
146
+ if scanner.skip(/;/)
147
+ add_statement(result, scanner.string, start, position, code)
148
+ start = nil
149
+ elsif skip_space_or_comment?(scanner, rules)
150
+ code << ' ' if code && start
151
+ else
152
+ start ||= position
153
+ append_token(scanner, rules, code)
154
+ end
155
+ end
156
+ add_statement(result, scanner.string, start, scanner.pos, code)
157
+ end
158
+
159
+ # Skips one token, adding it to the code view, blanked if quoted.
160
+ #
161
+ #: (StringScanner scanner, Dialect rules, String? code) -> void
162
+ def append_token(scanner, rules, code)
163
+ position = scanner.pos
164
+ quoted = skip_token_quoted?(scanner, rules)
165
+ code << (quoted ? BLANK : scanner.string.byteslice(position, scanner.pos - position)) if code
166
+ end
167
+
168
+ #: (Array[String] result, String sql, Integer? start, Integer finish, String? code) -> Array[String]
169
+ def add_statement(result, sql, start, finish, code)
170
+ return result unless start
171
+
172
+ if code
173
+ result << code.rstrip
174
+ code.clear
175
+ else
176
+ result << sql.byteslice(start, finish - start).rstrip
177
+ end
178
+ result
179
+ end
180
+
181
+ # Whitespace and comments before a statement are not part of it.
182
+ #
183
+ #: (StringScanner scanner, Dialect rules) -> bool
184
+ def skip_space_or_comment?(scanner, rules)
185
+ return true if scanner.skip(/\s+/) || rules.comments.any? { |comment| scanner.skip(comment) }
186
+ return false unless scanner.skip(%r{/\*})
187
+
188
+ rules.nested ? skip_nested_comment(scanner) : (scanner.skip_until(%r{\*/}) || scanner.terminate)
189
+ true
190
+ end
191
+
192
+ # An unterminated comment runs to the end.
193
+ #
194
+ #: (StringScanner scanner) -> void
195
+ def skip_nested_comment(scanner)
196
+ depth = 1
197
+ depth += scanner.matched == '/*' ? 1 : -1 while depth.positive? && scanner.skip_until(%r{/\*|\*/})
198
+ scanner.terminate if depth.positive?
199
+ end
200
+
201
+ # Skips one string, quoted identifier, dollar-quoted string, word or run of other text. An unterminated quote
202
+ # runs to the end. True when the token was quoted.
203
+ #
204
+ #: (StringScanner scanner, Dialect rules) -> bool
205
+ def skip_token_quoted?(scanner, rules)
206
+ return true if rules.tokens.any? { |token| scanner.skip(token) }
207
+ return true if rules.dollar && skip_dollar_quoted?(scanner)
208
+
209
+ scanner.skip(WORD) || scanner.skip(OTHER) || scanner.getch
210
+ false
211
+ end
212
+
213
+ #: (StringScanner scanner) -> bool
214
+ def skip_dollar_quoted?(scanner)
215
+ return false unless (tag = scanner.scan(DOLLAR_TAG))
216
+
217
+ scanner.skip_until(/#{Regexp.escape(tag)}/) || scanner.terminate
218
+ true
219
+ end
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,8 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ VERSION = '0.1.0'
7
+ end
8
+ end
@@ -0,0 +1,86 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'active_record'
5
+ require 'active_record/async_connection_pool/version'
6
+ require 'active_record/async_connection_pool/errors'
7
+ require 'active_record/async_connection_pool/database_options'
8
+ require 'active_record/async_connection_pool/raw_entry'
9
+ require 'active_record/async_connection_pool/raw_pool'
10
+ require 'active_record/async_connection_pool/session_state'
11
+ require 'active_record/async_connection_pool/handler'
12
+ require 'active_record/async_connection_pool/adapter_extension'
13
+ require 'active_record/async_connection_pool/pool_extension'
14
+ require 'active_record/async_connection_pool/handlers/sqlite3'
15
+ require 'active_record/async_connection_pool/handlers/postgresql'
16
+ require 'active_record/async_connection_pool/handlers/trilogy'
17
+
18
+ module ActiveRecord
19
+ # Lets fibers share a small pool of physical database connections, attaching one to a fiber only while it runs
20
+ # a query. Enabled per database with `raw_pool: true` in database.yml.
21
+ module AsyncConnectionPool
22
+ SESSION_STATES = %i[pin raise].freeze
23
+ POSTGRESQL_DETECTORS = %i[auto pg_query lexer].freeze
24
+ POSTGRESQL_DETECTOR_ENV = 'ASYNC_CONNECTION_POOL_POSTGRESQL_DETECTOR'
25
+
26
+ class << self
27
+ # What to do when a fiber changes session state (eg. advisory locks, `SET`): `:pin` keeps the connection
28
+ # attached to the fiber, `:raise` raises. A database's `session_state` key overrides this.
29
+ #
30
+ #: () -> Symbol
31
+ attr_reader :session_state
32
+
33
+ # Whether connections are reset when they return to the raw pool, by default.
34
+ #
35
+ #: bool
36
+ attr_accessor :reset_on_checkin
37
+
38
+ #: (Symbol | String) -> void
39
+ def session_state=(value)
40
+ @session_state = DatabaseOptions.validate_session_state!(value)
41
+ end
42
+
43
+ # How PostgreSQL statements are checked for session state: `:pg_query` parses them with the pg_query gem,
44
+ # `:lexer` matches them with the gem's own lexer, and `:auto` uses pg_query when it can be loaded.
45
+ #
46
+ #: () -> Symbol
47
+ attr_reader :postgresql_detector
48
+
49
+ # Raises `DetectorUnavailableError` for `:pg_query` when the pg_query gem can't be loaded.
50
+ #
51
+ #: (Symbol | String) -> void
52
+ def postgresql_detector=(value)
53
+ detector = validate_postgresql_detector!(value)
54
+ Handlers::PostgreSQL::PgQueryDetector.load! if detector == :pg_query
55
+ @postgresql_detector = detector
56
+ end
57
+
58
+ # The detector `ASYNC_CONNECTION_POOL_POSTGRESQL_DETECTOR` names, or `:auto` when it is unset or empty.
59
+ #
60
+ #: (?untyped env) -> Symbol
61
+ def default_postgresql_detector(env = ENV)
62
+ value = env[POSTGRESQL_DETECTOR_ENV].to_s
63
+ value.empty? ? :auto : validate_postgresql_detector!(value)
64
+ end
65
+
66
+ private
67
+
68
+ #: (untyped value) -> Symbol
69
+ def validate_postgresql_detector!(value)
70
+ detector = value.to_s.to_sym
71
+ return detector if POSTGRESQL_DETECTORS.include?(detector)
72
+
73
+ raise ArgumentError,
74
+ "postgresql_detector must be one of #{POSTGRESQL_DETECTORS.join(', ')} (got #{value.inspect})"
75
+ end
76
+ end
77
+
78
+ @session_state = :pin
79
+ @postgresql_detector = default_postgresql_detector
80
+ @reset_on_checkin = false
81
+ end
82
+ end
83
+
84
+ ActiveSupport.on_load(:active_record) do
85
+ ActiveRecord::ConnectionAdapters::ConnectionPool.prepend(ActiveRecord::AsyncConnectionPool::PoolExtension)
86
+ end