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,216 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ class PostgreSQL < Handler
8
+ # Prepended to `PostgreSQLAdapter` after `AdapterExtension`. With a raw pool, the session setters record the
9
+ # adapter's value and the handler applies it to whichever raw connection is attached; advisory locks pin;
10
+ # clearing the statement cache reaches idle raw connections too. Without one, every method defers to
11
+ # ActiveRecord.
12
+ module AdapterMethods
13
+ #: (*untyped args) -> void
14
+ def initialize(*args)
15
+ super
16
+ @async_pg_advisory_locks = 0
17
+ @async_pg_configuring = false
18
+ @async_pg_loading_types = false
19
+ @async_pg_configured = nil #: Hash[Symbol, untyped]?
20
+ @async_pg_min_messages = nil #: String?
21
+ @async_pg_session_auth = nil #: String?
22
+ end
23
+
24
+ # The value is applied now, on the attached raw connection, and again on every raw connection this adapter
25
+ # attaches to later. It never pins.
26
+ #
27
+ #: (String? schema_csv) -> void
28
+ def schema_search_path=(schema_csv)
29
+ if !async_raw_pool || @async_pg_configuring
30
+ super
31
+ elsif schema_csv
32
+ async_pg_session_setting(:search_path, :@schema_search_path, schema_csv)
33
+ end
34
+ end
35
+
36
+ #: (untyped level) -> void
37
+ def client_min_messages=(level)
38
+ if !async_raw_pool || @async_pg_configuring
39
+ super
40
+ else
41
+ async_pg_session_setting(:client_min_messages, :@async_pg_min_messages, level.to_s)
42
+ end
43
+ end
44
+
45
+ #: (String? user) -> void
46
+ def session_auth=(user)
47
+ if !async_raw_pool || @async_pg_configuring
48
+ super
49
+ else
50
+ clear_cache!
51
+ async_pg_session_setting(:session_auth, :@async_pg_session_auth, user)
52
+ end
53
+ end
54
+
55
+ # Pinned from the first lock taken until the last is released, or the lease ends.
56
+ #
57
+ #: (Integer lock_id) -> bool
58
+ def get_advisory_lock(lock_id)
59
+ return super unless async_raw_pool
60
+
61
+ lease_pin!(:advisory_lock)
62
+ acquired = false
63
+ begin
64
+ acquired = without_session_state_detection { super }
65
+ ensure
66
+ if acquired
67
+ @async_pg_advisory_locks += 1
68
+ elsif @async_pg_advisory_locks.zero?
69
+ release_lease_pin!(:advisory_lock)
70
+ end
71
+ end
72
+ acquired
73
+ end
74
+
75
+ #: (Integer lock_id) -> bool
76
+ def release_advisory_lock(lock_id)
77
+ return super unless async_raw_pool
78
+
79
+ released = without_session_state_detection { super }
80
+ if released && @async_pg_advisory_locks.positive?
81
+ @async_pg_advisory_locks -= 1
82
+ release_lease_pin!(:advisory_lock) if @async_pg_advisory_locks.zero?
83
+ end
84
+ released
85
+ end
86
+
87
+ # A lock still held when the lease ends taints the raw connection, so `DISCARD ALL` releases it.
88
+ #
89
+ #: () -> void
90
+ def release_lease_pins! # :nodoc:
91
+ if @async_pg_advisory_locks.positive?
92
+ @async_entry&.taint!
93
+ @async_pg_advisory_locks = 0
94
+ end
95
+ super
96
+ end
97
+
98
+ # Clears the attached raw connection's statements, as ActiveRecord does, and bumps the raw pool's
99
+ # statement generation so idle raw connections clear theirs before their next use. A new connection also
100
+ # forgets the session settings, as ActiveRecord does for `schema_search_path`.
101
+ #
102
+ #: (?new_connection: bool) -> void
103
+ def clear_cache!(new_connection: false)
104
+ super
105
+ return unless (raw_pool = async_raw_pool)
106
+
107
+ if new_connection
108
+ @async_pg_min_messages = nil
109
+ @async_pg_session_auth = nil
110
+ else
111
+ generation = raw_pool.bump_statement_generation!
112
+ @async_entry&.state&.store(:generation, generation)
113
+ end
114
+ end
115
+
116
+ # Types may have changed, so prepared statements may be stale on every raw connection.
117
+ #
118
+ #: () -> untyped
119
+ def reload_type_map
120
+ result = super
121
+ async_raw_pool&.bump_statement_generation! unless @async_pg_configuring || @async_pg_loading_types
122
+ result
123
+ end
124
+
125
+ private
126
+
127
+ # A new raw connection has no result decoders until `configure_connection` adds them, so the adapter forgets
128
+ # the previous raw connection's: its statements before then must not update a decoder it does not have.
129
+ #
130
+ #: () -> void
131
+ def connect
132
+ if async_raw_pool
133
+ @mapped_default_timezone = nil
134
+ @timestamp_decoder = nil
135
+ end
136
+ super
137
+ end
138
+
139
+ # Configures the raw connection as ActiveRecord does, from the configured search path rather than the
140
+ # adapter's, and records the result for the handler. The adapter's own values are applied on attach.
141
+ #
142
+ #: () -> void
143
+ def configure_connection
144
+ return super unless (raw_pool = async_raw_pool)
145
+
146
+ desired = @schema_search_path
147
+ @schema_search_path = nil
148
+ @async_pg_configured = nil
149
+ @async_pg_configuring = true
150
+ begin
151
+ super
152
+ @async_pg_configured = raw_pool.handler.configuration(self)
153
+ ensure
154
+ @async_pg_configuring = false
155
+ # Without its own value, the adapter takes the search path the session really has (`variables:` may
156
+ # override `schema_search_path:`).
157
+ @schema_search_path = desired || @async_pg_configured&.dig(:settings, :search_path) || @schema_search_path
158
+ end
159
+ raw_pool.handler.configured(self, @async_entry) if @async_entry
160
+ end
161
+
162
+ # Switching the session timezone to match `default_timezone` is the adapter's own doing, not session state.
163
+ #
164
+ #: () -> untyped
165
+ def update_typemap_for_default_timezone
166
+ return super unless async_raw_pool
167
+
168
+ without_session_state_detection { super }
169
+ end
170
+
171
+ # Loads the adapter's type map without invalidating prepared statements, for an adapter that has not
172
+ # configured a raw connection itself.
173
+ #
174
+ #: () -> void
175
+ def async_pg_load_type_map
176
+ @async_pg_loading_types = true
177
+ reload_type_map
178
+ ensure
179
+ @async_pg_loading_types = false
180
+ end
181
+
182
+ # Records the value as the adapter's, then applies it on the attached raw connection. If it cannot be
183
+ # applied, the previous value is kept.
184
+ #
185
+ #: (Symbol key, Symbol ivar, untyped value) -> void
186
+ def async_pg_session_setting(key, ivar, value)
187
+ previous = instance_variable_get(ivar)
188
+ instance_variable_set(ivar, value)
189
+ begin
190
+ with_raw_connection do
191
+ without_session_state_detection do
192
+ async_raw_pool.handler.set_session(self, @async_entry, key, value)
193
+ end
194
+ end
195
+ rescue Exception # rubocop:disable Lint/RescueException
196
+ instance_variable_set(ivar, previous)
197
+ raise
198
+ end
199
+ end
200
+
201
+ # The advisory locks were the raw connection's, so they go with it.
202
+ #
203
+ #: (RawEntry entry) -> void
204
+ def async_forget(entry)
205
+ super
206
+ @async_pg_advisory_locks = 0
207
+ end
208
+ end
209
+ end
210
+ end
211
+ end
212
+ end
213
+
214
+ ActiveSupport.on_load(:active_record_postgresqladapter) do
215
+ prepend ActiveRecord::AsyncConnectionPool::Handlers::PostgreSQL::AdapterMethods
216
+ end
@@ -0,0 +1,256 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ class PostgreSQL < Handler
8
+ # Decides whether SQL leaves state in the session from PostgreSQL's own parse tree, through the pg_query gem,
9
+ # so quoting, comments and identifiers are read exactly as the server reads them. Each statement of the SQL is
10
+ # checked; SQL pg_query can't parse (newer server syntax) counts as session state.
11
+ module PgQueryDetector
12
+ # Results are cached per SQL, up to this many, least recently used first out.
13
+ CACHE_SIZE = 1_000
14
+ # Longer SQL (bulk inserts, mostly) is rarely repeated, so it is parsed every time rather than cached.
15
+ CACHEABLE_BYTES = 16_384
16
+ PARSE_ERROR = 'parse_error.active_record_async_connection_pool'
17
+
18
+ # Function calls are only looked for when one of these words is in the SQL.
19
+ FUNCTION_HINT = /advisory|set_config/i
20
+ ADVISORY_LOCKS = %w[
21
+ pg_advisory_lock pg_advisory_lock_shared pg_try_advisory_lock pg_try_advisory_lock_shared
22
+ ].freeze
23
+ # `pg_temp` is the session's temp schema; `pg_temp_N` names it too. Any case, so a quoted `"PG_TEMP"` (another
24
+ # schema) errs on the side of session state.
25
+ TEMP_SCHEMA = /\Apg_temp(?:_\d+)?\z/i
26
+ # The names `SET [SESSION] TRANSACTION ...` and `SET TRANSACTION SNAPSHOT` parse to. Upper case, so they
27
+ # never name a custom setting, which needs a dot (`"TRANSACTION.x"`, `transaction.x`).
28
+ TRANSACTION_SETTINGS = ['TRANSACTION', 'TRANSACTION SNAPSHOT'].freeze
29
+ # `CURSOR_OPT_HOLD` in PostgreSQL's parsenodes.h.
30
+ CURSOR_OPT_HOLD = 0x0020
31
+ # Statements that always leave state: `DO` and `CALL` run server-side code, whatever it does; `DEALLOCATE`
32
+ # leaves the raw connection's statement pool listing statements that are gone.
33
+ ALWAYS = %i[listen_stmt prepare_stmt load_stmt do_stmt call_stmt deallocate_stmt].freeze
34
+ # Creating statements besides the `create_*_stmt` ones: aggregates, operators, base types and collations;
35
+ # composite types; views.
36
+ CREATING = %i[define_stmt composite_type_stmt view_stmt].freeze
37
+
38
+ # Thread-safe, size-bounded map from SQL to its result, dropping the least recently used entry.
39
+ class Cache
40
+ #: (Integer size) -> void
41
+ def initialize(size)
42
+ @size = size
43
+ @entries = {} #: Hash[String, bool]
44
+ @mutex = Mutex.new
45
+ end
46
+
47
+ #: (String sql) -> bool?
48
+ def [](sql)
49
+ @mutex.synchronize do
50
+ return nil unless @entries.key?(sql)
51
+
52
+ @entries[sql] = @entries.delete(sql)
53
+ end
54
+ end
55
+
56
+ #: (String sql, bool result) -> void
57
+ def []=(sql, result)
58
+ @mutex.synchronize do
59
+ @entries.delete(sql)
60
+ @entries[sql] = result
61
+ @entries.shift while @entries.size > @size
62
+ end
63
+ end
64
+
65
+ #: () -> Integer
66
+ def size
67
+ @mutex.synchronize { @entries.size }
68
+ end
69
+
70
+ #: () -> void
71
+ def clear
72
+ @mutex.synchronize { @entries.clear }
73
+ end
74
+ end
75
+
76
+ @cache = Cache.new(CACHE_SIZE)
77
+
78
+ class << self
79
+ #: Cache
80
+ attr_reader :cache
81
+
82
+ # Whether the pg_query gem loads. Tried once.
83
+ #
84
+ #: () -> bool
85
+ def available?
86
+ return @available unless @available.nil?
87
+
88
+ @available = begin
89
+ require 'pg_query'
90
+ true
91
+ rescue LoadError => error
92
+ @load_error = error
93
+ false
94
+ end
95
+ end
96
+
97
+ # Loads pg_query, or raises `DetectorUnavailableError`.
98
+ #
99
+ #: () -> void
100
+ def load!
101
+ return if available?
102
+
103
+ raise DetectorUnavailableError,
104
+ 'postgresql_detector is :pg_query, but the pg_query gem ' \
105
+ "can't be loaded (#{@load_error&.message}). Add gem 'pg_query' to the Gemfile, " \
106
+ 'or set postgresql_detector to :auto or :lexer.'
107
+ end
108
+
109
+ # Whether any statement in `sql` leaves state in the session. Never raises: SQL that can't be parsed or
110
+ # read is session state, and instruments `parse_error` (once per SQL while it stays cached).
111
+ #
112
+ #: (String sql) -> bool
113
+ def session_state?(sql)
114
+ cached = @cache[sql]
115
+ return cached unless cached.nil?
116
+
117
+ result = detect(sql)
118
+ @cache[sql] = result if sql.bytesize <= CACHEABLE_BYTES
119
+ result
120
+ end
121
+
122
+ private
123
+
124
+ # Any error counts as session state: `PgQuery::ParseError` (an `ArgumentError`, as is the parser refusing
125
+ # a NUL byte), or a tree this code doesn't expect, as a newer pg_query may build.
126
+ #
127
+ #: (String sql) -> bool
128
+ def detect(sql)
129
+ parsed = PgQuery.parse(sql)
130
+ parsed.tree.stmts.any? { |raw| statement?(raw.stmt) } ||
131
+ (sql.match?(FUNCTION_HINT) && function_call?(parsed))
132
+ rescue StandardError => error
133
+ ActiveSupport::Notifications.instrument(PARSE_ERROR, sql:, error:)
134
+ true
135
+ end
136
+
137
+ # Whether the statement itself leaves state, by its node type.
138
+ #
139
+ #: (untyped node) -> bool
140
+ def statement?(node)
141
+ type = node&.node
142
+ return false unless type
143
+ return true if ALWAYS.include?(type)
144
+
145
+ stmt = node.inner
146
+ case type
147
+ when :variable_set_stmt then variable_set?(stmt)
148
+ when :declare_cursor_stmt then stmt.options.anybits?(CURSOR_OPT_HOLD)
149
+ when :discard_stmt then stmt.target == :DISCARD_ALL
150
+ when :create_stmt then temp_relation?(stmt.relation) && stmt.oncommit != :ONCOMMIT_DROP
151
+ when :create_table_as_stmt then temp_into?(stmt.into)
152
+ when :select_stmt then temp_into?(select_into(stmt))
153
+ when :explain_stmt then statement?(stmt.query) # EXPLAIN ANALYZE runs the statement
154
+ else created_temp?(type, stmt)
155
+ end
156
+ end
157
+
158
+ # Whether a creating statement (any `create_*_stmt`, so new kinds are covered) makes its object in the temp
159
+ # schema.
160
+ #
161
+ #: (Symbol type, untyped stmt) -> bool
162
+ def created_temp?(type, stmt)
163
+ (type.start_with?('create_') || CREATING.include?(type)) && temp_target?(stmt)
164
+ end
165
+
166
+ # A relation or qualified name in the statement's own fields, or in a statement it wraps (`CREATE FOREIGN
167
+ # TABLE`'s), names the temp schema. Queries and expressions (`Node` fields) are not looked into.
168
+ #
169
+ #: (untyped message) -> bool
170
+ def temp_target?(message)
171
+ message.class.descriptor.any? do |field|
172
+ value = field.type == :message && field.get(message)
173
+ case value
174
+ when PgQuery::RangeVar then temp_relation?(value)
175
+ when Google::Protobuf::RepeatedField then temp_name?(value)
176
+ when PgQuery::Node, nil, false then false
177
+ else temp_target?(value)
178
+ end
179
+ end
180
+ end
181
+
182
+ # `SET`/`RESET` of the session, `SET SESSION AUTHORIZATION`, `ROLE` and `SESSION CHARACTERISTICS`
183
+ # included. `SET LOCAL` and `SET TRANSACTION [SNAPSHOT]` end with the transaction; `SET CONSTRAINTS` is a
184
+ # statement of its own.
185
+ #
186
+ #: (untyped stmt) -> bool
187
+ def variable_set?(stmt)
188
+ !stmt.is_local && TRANSACTION_SETTINGS.exclude?(stmt.name)
189
+ end
190
+
191
+ # `INTO` sits on the leftmost `SELECT` of a set operation.
192
+ #
193
+ #: (untyped select) -> untyped
194
+ def select_into(select)
195
+ return nil unless select
196
+
197
+ select.into_clause || select_into(select.larg)
198
+ end
199
+
200
+ #: (untyped into) -> bool
201
+ def temp_into?(into)
202
+ !into.nil? && temp_relation?(into.rel) && into.on_commit != :ONCOMMIT_DROP
203
+ end
204
+
205
+ #: (untyped relation) -> bool
206
+ def temp_relation?(relation)
207
+ !relation.nil? && (relation.relpersistence == 't' || TEMP_SCHEMA.match?(relation.schemaname))
208
+ end
209
+
210
+ #: (untyped names) -> bool
211
+ def temp_name?(names)
212
+ first = names.first
213
+ names.size > 1 && first.is_a?(PgQuery::Node) && TEMP_SCHEMA.match?(first.string&.sval.to_s)
214
+ end
215
+
216
+ # A call anywhere in the tree to a session advisory lock, or to `set_config` without a literal `true`
217
+ # third argument, by its unqualified name. Walks only message fields, without recursing (fiber stacks are
218
+ # small), which is many times faster than `PgQuery::ParserResult#walk!`.
219
+ #
220
+ #: (untyped parsed) -> bool
221
+ def function_call?(parsed)
222
+ pending = [parsed.tree]
223
+ while (message = pending.pop)
224
+ return true if message.is_a?(PgQuery::FuncCall) && session_function?(message)
225
+
226
+ pending.concat(children(message))
227
+ end
228
+ false
229
+ end
230
+
231
+ # A node holds one of hundreds of node types: only the one set is read.
232
+ #
233
+ #: (untyped message) -> Array[untyped]
234
+ def children(message)
235
+ case message
236
+ when Google::Protobuf::RepeatedField then message.to_a
237
+ when PgQuery::Node then message.node ? [message.inner] : []
238
+ else message.class.descriptor.filter_map { |field| field.get(message) if field.type == :message }
239
+ end
240
+ end
241
+
242
+ #: (untyped call) -> bool
243
+ def session_function?(call)
244
+ name = call.funcname.last&.string&.sval
245
+ return true if ADVISORY_LOCKS.include?(name)
246
+ return false unless name == 'set_config'
247
+
248
+ constant = call.args[2]&.a_const
249
+ constant&.boolval&.boolval != true
250
+ end
251
+ end
252
+ end
253
+ end
254
+ end
255
+ end
256
+ end