schema_shard 0.1.1
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +38 -0
- data/LICENSE.txt +21 -0
- data/README.md +366 -0
- data/lib/generators/schema_shard/install_generator.rb +21 -0
- data/lib/generators/schema_shard/templates/initializer.rb.tt +40 -0
- data/lib/generators/schema_shard/templates/shards.yml.tt +31 -0
- data/lib/schema_shard/config_loader.rb +150 -0
- data/lib/schema_shard/configuration.rb +99 -0
- data/lib/schema_shard/connection_patch.rb +56 -0
- data/lib/schema_shard/connection_sanitizer.rb +104 -0
- data/lib/schema_shard/database_adapters/base.rb +148 -0
- data/lib/schema_shard/database_adapters/generic.rb +17 -0
- data/lib/schema_shard/database_adapters/mysql.rb +154 -0
- data/lib/schema_shard/database_adapters/postgresql.rb +157 -0
- data/lib/schema_shard/database_adapters/sqlite.rb +99 -0
- data/lib/schema_shard/errors.rb +9 -0
- data/lib/schema_shard/execution_context.rb +146 -0
- data/lib/schema_shard/metrics.rb +165 -0
- data/lib/schema_shard/middleware/sidekiq.rb +15 -0
- data/lib/schema_shard/pool_entry.rb +44 -0
- data/lib/schema_shard/pool_registry.rb +442 -0
- data/lib/schema_shard/query_logger.rb +48 -0
- data/lib/schema_shard/railtie.rb +30 -0
- data/lib/schema_shard/tenant_adapters/apartment.rb +84 -0
- data/lib/schema_shard/tenant_adapters/base.rb +82 -0
- data/lib/schema_shard/tenant_adapters/native.rb +29 -0
- data/lib/schema_shard/tenant_adapters/none.rb +14 -0
- data/lib/schema_shard/version.rb +5 -0
- data/lib/schema_shard.rb +516 -0
- metadata +136 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'concurrent'
|
|
4
|
+
|
|
5
|
+
module SchemaShard
|
|
6
|
+
class Metrics
|
|
7
|
+
METRIC_KEYS = %i[
|
|
8
|
+
pools_created_total
|
|
9
|
+
pools_evicted_total
|
|
10
|
+
pools_cleanup_total
|
|
11
|
+
connection_checkouts_total
|
|
12
|
+
connection_verification_failures_total
|
|
13
|
+
connection_timeouts_total
|
|
14
|
+
connection_discards_total
|
|
15
|
+
shard_switches_total
|
|
16
|
+
].freeze
|
|
17
|
+
|
|
18
|
+
SHARD_METRIC_KEYS = %i[
|
|
19
|
+
pools_created_total
|
|
20
|
+
verification_failures_total
|
|
21
|
+
switches_total
|
|
22
|
+
connection_discards_total
|
|
23
|
+
].freeze
|
|
24
|
+
|
|
25
|
+
OVERFLOW_SHARD_LABEL = '_other'
|
|
26
|
+
|
|
27
|
+
def initialize(configuration: nil)
|
|
28
|
+
@configuration = configuration
|
|
29
|
+
@metrics = Concurrent::Map.new
|
|
30
|
+
@shard_metrics = Concurrent::Map.new
|
|
31
|
+
METRIC_KEYS.each { |k| @metrics[k] = Concurrent::AtomicFixnum.new(0) }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def increment(metric_name, count = 1)
|
|
35
|
+
key = metric_name.to_sym
|
|
36
|
+
return unless METRIC_KEYS.include?(key)
|
|
37
|
+
|
|
38
|
+
counter = @metrics.compute_if_absent(key) { Concurrent::AtomicFixnum.new(0) }
|
|
39
|
+
counter.increment(count)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def increment_shard(shard_key, metric_name, count = 1)
|
|
43
|
+
key = metric_name.to_sym
|
|
44
|
+
return unless SHARD_METRIC_KEYS.include?(key)
|
|
45
|
+
|
|
46
|
+
shard_str = resolve_tracked_shard_key(shard_key.to_s)
|
|
47
|
+
shard_map = @shard_metrics.compute_if_absent(shard_str) { Concurrent::Map.new }
|
|
48
|
+
counter = shard_map.compute_if_absent(key) { Concurrent::AtomicFixnum.new(0) }
|
|
49
|
+
counter.increment(count)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def track_switch(shard_key)
|
|
53
|
+
increment(:shard_switches_total)
|
|
54
|
+
increment_shard(shard_key, :switches_total)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def snapshot(pool_status:)
|
|
58
|
+
global_snapshot = {}
|
|
59
|
+
@metrics.each_pair { |k, counter| global_snapshot[k] = counter.value }
|
|
60
|
+
|
|
61
|
+
per_shard_snapshot = {}
|
|
62
|
+
@shard_metrics.each_pair do |shard, metric_map|
|
|
63
|
+
shard_hash = {}
|
|
64
|
+
metric_map.each_pair { |name, counter| shard_hash[name] = counter.value }
|
|
65
|
+
per_shard_snapshot[shard] = shard_hash
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
{
|
|
69
|
+
global: global_snapshot,
|
|
70
|
+
per_shard: per_shard_snapshot,
|
|
71
|
+
timestamp: Time.now.to_f,
|
|
72
|
+
pools: pool_status
|
|
73
|
+
}
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def prometheus(pool_status:)
|
|
77
|
+
current = snapshot(pool_status: pool_status)
|
|
78
|
+
lines = []
|
|
79
|
+
|
|
80
|
+
append_global_prometheus_lines(lines, current[:global])
|
|
81
|
+
append_pool_prometheus_lines(lines, current[:pools])
|
|
82
|
+
append_per_shard_prometheus_lines(lines, current[:per_shard])
|
|
83
|
+
|
|
84
|
+
"#{lines.join("\n")}\n"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def statsd(pool_status:)
|
|
88
|
+
current = snapshot(pool_status: pool_status)
|
|
89
|
+
output = current[:global].map do |name, value|
|
|
90
|
+
{ name: "schema_shard.#{name}", value: value, type: :gauge, tags: ['component:schema_shard'] }
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
pm = current[:pools]
|
|
94
|
+
output << { name: 'schema_shard.pools.active_count',
|
|
95
|
+
value: pm[:active_count], type: :gauge,
|
|
96
|
+
tags: ['component:schema_shard'] }
|
|
97
|
+
output << { name: 'schema_shard.pools.usage_percentage',
|
|
98
|
+
value: pm[:usage_percentage], type: :gauge,
|
|
99
|
+
tags: ['component:schema_shard'] }
|
|
100
|
+
|
|
101
|
+
current[:per_shard].each do |shard, data|
|
|
102
|
+
data.each do |name, value|
|
|
103
|
+
output << { name: "schema_shard.shard.#{name}", value: value,
|
|
104
|
+
type: :gauge,
|
|
105
|
+
tags: ['component:schema_shard', "shard:#{shard}"] }
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
output
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def reset!
|
|
113
|
+
@metrics.each_value { |counter| counter.value = 0 }
|
|
114
|
+
@shard_metrics.clear
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
def resolve_tracked_shard_key(shard_str)
|
|
120
|
+
return shard_str if @shard_metrics.key?(shard_str)
|
|
121
|
+
|
|
122
|
+
limit = @configuration&.max_tracked_shards.to_i
|
|
123
|
+
return shard_str unless limit.positive? && @shard_metrics.size >= limit
|
|
124
|
+
|
|
125
|
+
OVERFLOW_SHARD_LABEL
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def append_global_prometheus_lines(lines, global_metrics)
|
|
129
|
+
global_metrics.each do |name, value|
|
|
130
|
+
lines << "# HELP schema_shard_#{name} #{name.to_s.tr('_', ' ').capitalize}"
|
|
131
|
+
lines << "# TYPE schema_shard_#{name} counter"
|
|
132
|
+
lines << "schema_shard_#{name} #{value}"
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def append_pool_prometheus_lines(lines, pool_metrics)
|
|
137
|
+
lines << '# HELP schema_shard_pools_active Number of currently active shard connection pools'
|
|
138
|
+
lines << '# TYPE schema_shard_pools_active gauge'
|
|
139
|
+
lines << "schema_shard_pools_active #{pool_metrics[:active_count]}"
|
|
140
|
+
lines << '# HELP schema_shard_pools_usage_percentage Percentage of maximum allowed shard pools in use'
|
|
141
|
+
lines << '# TYPE schema_shard_pools_usage_percentage gauge'
|
|
142
|
+
lines << "schema_shard_pools_usage_percentage #{pool_metrics[:usage_percentage]}"
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def append_per_shard_prometheus_lines(lines, per_shard_metrics)
|
|
146
|
+
by_metric = Hash.new { |h, k| h[k] = [] }
|
|
147
|
+
per_shard_metrics.each do |shard, data|
|
|
148
|
+
data.each { |name, value| by_metric[name] << [shard, value] }
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
by_metric.each do |name, samples|
|
|
152
|
+
metric_id = "schema_shard_per_shard_#{name}"
|
|
153
|
+
lines << "# HELP #{metric_id} Per-shard #{name.to_s.tr('_', ' ')}"
|
|
154
|
+
lines << "# TYPE #{metric_id} counter"
|
|
155
|
+
samples.each do |shard, value|
|
|
156
|
+
lines << "#{metric_id}{shard=\"#{escape_prometheus_label(shard)}\"} #{value}"
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def escape_prometheus_label(value)
|
|
162
|
+
value.to_s.gsub('\\', '\\\\\\\\').gsub('"', '\\"').gsub("\n", '\\n')
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
end
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SchemaShard
|
|
4
|
+
module Middleware
|
|
5
|
+
# Sidekiq server middleware guaranteeing SchemaShard execution state is cleared
|
|
6
|
+
# after every job, preventing leaked shard/tenant context across recycled worker threads.
|
|
7
|
+
class Sidekiq
|
|
8
|
+
def call(_worker, _job, _queue)
|
|
9
|
+
yield
|
|
10
|
+
ensure
|
|
11
|
+
SchemaShard.clear_thread_locals!
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
end
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'concurrent'
|
|
4
|
+
|
|
5
|
+
module SchemaShard
|
|
6
|
+
# Atomic refcount + eviction state bound to one ActiveRecord::ConnectionAdapters::ConnectionPool.
|
|
7
|
+
# Uses Dekker-style store-load ordering so concurrent eviction never races with active checkouts.
|
|
8
|
+
class PoolEntry
|
|
9
|
+
attr_reader :pool, :pool_key, :shard_key, :refcount, :evicted
|
|
10
|
+
|
|
11
|
+
def initialize(pool:, pool_key:, shard_key:, accessed_at:)
|
|
12
|
+
@pool = pool
|
|
13
|
+
@pool_key = pool_key
|
|
14
|
+
@shard_key = shard_key
|
|
15
|
+
@refcount = Concurrent::AtomicFixnum.new(0)
|
|
16
|
+
@evicted = Concurrent::AtomicBoolean.new(false)
|
|
17
|
+
@last_accessed = Concurrent::AtomicReference.new(accessed_at)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def touch(now)
|
|
21
|
+
@last_accessed.set(now)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def last_accessed
|
|
25
|
+
@last_accessed.get
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Increment refcount BEFORE checking evicted; pairs with eviction setting evicted BEFORE reading refcount.
|
|
29
|
+
def try_acquire?(now)
|
|
30
|
+
@refcount.increment
|
|
31
|
+
if @evicted.true?
|
|
32
|
+
@refcount.decrement
|
|
33
|
+
return false
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
touch(now)
|
|
37
|
+
true
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def release
|
|
41
|
+
@refcount.decrement
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'concurrent'
|
|
4
|
+
require 'digest'
|
|
5
|
+
require 'json'
|
|
6
|
+
|
|
7
|
+
module SchemaShard
|
|
8
|
+
class PoolRegistry
|
|
9
|
+
POOL_IDENTITY_KEYS = %w[
|
|
10
|
+
adapter
|
|
11
|
+
host
|
|
12
|
+
port
|
|
13
|
+
socket
|
|
14
|
+
database
|
|
15
|
+
username
|
|
16
|
+
url
|
|
17
|
+
sslmode
|
|
18
|
+
ssl_mode
|
|
19
|
+
sslrootcert
|
|
20
|
+
sslcert
|
|
21
|
+
sslkey
|
|
22
|
+
variables
|
|
23
|
+
pragmas
|
|
24
|
+
schema_search_path
|
|
25
|
+
prepared_statements
|
|
26
|
+
advisory_locks
|
|
27
|
+
pool
|
|
28
|
+
checkout_timeout
|
|
29
|
+
timeout
|
|
30
|
+
reaping_frequency
|
|
31
|
+
encoding
|
|
32
|
+
].freeze
|
|
33
|
+
|
|
34
|
+
def initialize(configuration:, metrics:)
|
|
35
|
+
@configuration = configuration
|
|
36
|
+
@metrics = metrics
|
|
37
|
+
@mutex = Mutex.new
|
|
38
|
+
@connection_pools = Concurrent::Map.new
|
|
39
|
+
@pool_keys_cache = Concurrent::Map.new
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def acquire(config, shard_key, db_adapter:, read_only: true, tenant: nil)
|
|
43
|
+
ensure_active_record_loaded!
|
|
44
|
+
resolved_config = db_adapter.resolve_shard_config(config, tenant: tenant)
|
|
45
|
+
per_tenant = db_adapter.per_tenant_pool?(config)
|
|
46
|
+
pool_key = resolve_pool_key(resolved_config, shard_key,
|
|
47
|
+
read_only: read_only, per_tenant_pool: per_tenant)
|
|
48
|
+
|
|
49
|
+
loop do
|
|
50
|
+
now = monotonic_now
|
|
51
|
+
|
|
52
|
+
# Always try lock-free fast path for an existing live pool before locking.
|
|
53
|
+
existing = @connection_pools[pool_key]
|
|
54
|
+
if existing
|
|
55
|
+
return existing if existing.try_acquire?(now)
|
|
56
|
+
|
|
57
|
+
next
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
acquired = acquire_under_lock(resolved_config, shard_key, pool_key, db_adapter: db_adapter,
|
|
61
|
+
read_only: read_only, now: now)
|
|
62
|
+
return acquired if acquired
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def clear_key_cache!
|
|
67
|
+
@pool_keys_cache.clear
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def pool_count
|
|
71
|
+
@connection_pools.size
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def pool_usage_info
|
|
75
|
+
@mutex.synchronize do
|
|
76
|
+
{
|
|
77
|
+
current_pools: @connection_pools.size,
|
|
78
|
+
max_pools: @configuration.max_pools,
|
|
79
|
+
cleanup_threshold: @configuration.cleanup_threshold,
|
|
80
|
+
usage_percentage: percent_used,
|
|
81
|
+
oldest_pool_age: oldest_pool_age_seconds,
|
|
82
|
+
pool_keys: @connection_pools.keys
|
|
83
|
+
}
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def pool_status_snapshot
|
|
88
|
+
count = @connection_pools.size
|
|
89
|
+
{
|
|
90
|
+
active_count: count,
|
|
91
|
+
max_allowed: @configuration.max_pools,
|
|
92
|
+
cleanup_threshold: @configuration.cleanup_threshold,
|
|
93
|
+
usage_percentage: (count.to_f / @configuration.max_pools * 100).round(2)
|
|
94
|
+
}
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def pool_statistics
|
|
98
|
+
snapshot = @mutex.synchronize do
|
|
99
|
+
@connection_pools.each_pair.with_object({}) { |(k, entry), acc| acc[k] = entry.pool }
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
snapshot.transform_values do |pool|
|
|
103
|
+
stat = safe_pool_stat(pool, fail_closed: false)
|
|
104
|
+
{
|
|
105
|
+
size: stat[:size],
|
|
106
|
+
checked_out: stat[:busy],
|
|
107
|
+
available: [stat[:size] - stat[:busy], 0].max,
|
|
108
|
+
pool_config: extract_pool_config_summary(pool)
|
|
109
|
+
}
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def total_active_connections
|
|
114
|
+
@connection_pools.values.sum { |entry| safe_pool_stat(entry.pool, fail_closed: false)[:busy] }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def cleanup_connection_pools!
|
|
118
|
+
pools_to_disconnect = []
|
|
119
|
+
|
|
120
|
+
@mutex.synchronize do
|
|
121
|
+
@connection_pools.each_value do |entry|
|
|
122
|
+
if entry.refcount.value.positive?
|
|
123
|
+
logger&.warn "[SchemaShard] Force-cleaning pool '#{entry.pool_key}' " \
|
|
124
|
+
"with #{entry.refcount.value} active thread reference(s)"
|
|
125
|
+
end
|
|
126
|
+
entry.evicted.make_true
|
|
127
|
+
pools_to_disconnect << entry.pool
|
|
128
|
+
end
|
|
129
|
+
@connection_pools.clear
|
|
130
|
+
@pool_keys_cache.clear
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
pools_to_disconnect.each { |pool| safe_disconnect(pool) }
|
|
134
|
+
|
|
135
|
+
if pools_to_disconnect.any?
|
|
136
|
+
@metrics.increment(:pools_cleanup_total, 1)
|
|
137
|
+
@metrics.increment(:pools_evicted_total, pools_to_disconnect.size)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
logger&.info '[SchemaShard] All connection pools cleaned up'
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def cleanup_unused_pools!
|
|
144
|
+
evicted_pools = []
|
|
145
|
+
|
|
146
|
+
@mutex.synchronize do
|
|
147
|
+
@connection_pools.keys.each do |key| # rubocop:disable Style/HashEachMethods
|
|
148
|
+
pool = try_evict_pool_without_lock(key)
|
|
149
|
+
evicted_pools << pool if pool
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
evicted_pools.each { |pool| safe_disconnect(pool) }
|
|
154
|
+
removed = evicted_pools.size
|
|
155
|
+
|
|
156
|
+
if removed.positive?
|
|
157
|
+
@metrics.increment(:pools_cleanup_total, 1)
|
|
158
|
+
@metrics.increment(:pools_evicted_total, removed)
|
|
159
|
+
logger&.info "[SchemaShard] Removed #{removed} unused pools"
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
removed
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def discard_pools_after_fork!
|
|
166
|
+
pools_to_discard = []
|
|
167
|
+
|
|
168
|
+
@mutex.synchronize do
|
|
169
|
+
@connection_pools.each_value do |entry|
|
|
170
|
+
entry.evicted.make_true
|
|
171
|
+
pools_to_discard << entry.pool
|
|
172
|
+
end
|
|
173
|
+
@connection_pools.clear
|
|
174
|
+
@pool_keys_cache.clear
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
pools_to_discard.each { |pool| safe_discard_pool(pool) }
|
|
178
|
+
nil
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def build_pool_key(config, shard_key, read_only: true)
|
|
182
|
+
str_config = stringify_keys(config)
|
|
183
|
+
identity = POOL_IDENTITY_KEYS.each_with_object({}) do |k, acc|
|
|
184
|
+
acc[k] = str_config[k] if str_config.key?(k)
|
|
185
|
+
end
|
|
186
|
+
identity['password_digest'] = Digest::SHA256.hexdigest(str_config['password'].to_s) if str_config.key?('password')
|
|
187
|
+
identity['read_only'] = read_only
|
|
188
|
+
|
|
189
|
+
digest = Digest::SHA256.hexdigest(JSON.generate(identity))[0, 16]
|
|
190
|
+
"#{shard_key}_#{digest}"
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def build_connection_pool(config, pool_key, db_adapter:, read_only: true)
|
|
194
|
+
ar_base = ensure_active_record_loaded!
|
|
195
|
+
merged = merge_pool_options(config, db_adapter: db_adapter, read_only: read_only)
|
|
196
|
+
|
|
197
|
+
db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(
|
|
198
|
+
@configuration.effective_env,
|
|
199
|
+
pool_key.to_s,
|
|
200
|
+
symbolize_keys(merged)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(
|
|
204
|
+
ar_base,
|
|
205
|
+
db_config,
|
|
206
|
+
read_only ? :reading : :writing,
|
|
207
|
+
pool_key.to_sym
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
ActiveRecord::ConnectionAdapters::ConnectionPool.new(pool_config)
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
private
|
|
214
|
+
|
|
215
|
+
def ensure_active_record_loaded!
|
|
216
|
+
return @ar_base if @ar_base
|
|
217
|
+
|
|
218
|
+
require 'active_record' unless defined?(ActiveRecord::DatabaseConfigurations::HashConfig)
|
|
219
|
+
@ar_base = ActiveRecord::Base
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def merge_pool_options(config, db_adapter:, read_only:)
|
|
223
|
+
str_config = resolve_url_options(stringify_keys(config))
|
|
224
|
+
merged = db_adapter.default_pool_options(@configuration).merge(str_config)
|
|
225
|
+
merged['pool'] = [merged['pool'].to_i, 1].max
|
|
226
|
+
timeout_val = merged['checkout_timeout'].to_f
|
|
227
|
+
merged['checkout_timeout'] = timeout_val.positive? ? timeout_val : @configuration.checkout_timeout.to_f
|
|
228
|
+
merged['reaping_frequency'] = (merged['reaping_frequency'] || @configuration.reaping_frequency).to_f
|
|
229
|
+
read_only ? db_adapter.apply_read_only_config(merged) : merged
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
def resolve_url_options(str_config)
|
|
233
|
+
url = str_config['url']
|
|
234
|
+
return str_config if url.nil? || url.to_s.strip.empty?
|
|
235
|
+
|
|
236
|
+
require 'active_record' unless defined?(ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver)
|
|
237
|
+
resolved = ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver.new(url.to_s)
|
|
238
|
+
.to_hash.transform_keys(&:to_s)
|
|
239
|
+
resolved.merge(str_config.except('url').compact)
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def acquire_under_lock(resolved_config, shard_key, pool_key, db_adapter:, read_only:, now:)
|
|
243
|
+
created = false
|
|
244
|
+
evicted_pools = []
|
|
245
|
+
lru_removed = 0
|
|
246
|
+
acquired = nil
|
|
247
|
+
|
|
248
|
+
begin
|
|
249
|
+
@mutex.synchronize do
|
|
250
|
+
entry = @connection_pools[pool_key]
|
|
251
|
+
if entry&.try_acquire?(now)
|
|
252
|
+
acquired = entry
|
|
253
|
+
else
|
|
254
|
+
if @connection_pools.size >= @configuration.cleanup_threshold
|
|
255
|
+
lru_evicted = run_lru_cleanup_without_lock!(exclude_key: pool_key)
|
|
256
|
+
lru_removed = lru_evicted.size
|
|
257
|
+
evicted_pools.concat(lru_evicted)
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
evicted_pools.concat(enforce_pool_limit_without_lock!(pool_key))
|
|
261
|
+
|
|
262
|
+
new_pool = build_connection_pool(resolved_config, pool_key, db_adapter: db_adapter, read_only: read_only)
|
|
263
|
+
new_entry = PoolEntry.new(pool: new_pool, pool_key: pool_key, shard_key: shard_key, accessed_at: now)
|
|
264
|
+
new_entry.try_acquire?(now)
|
|
265
|
+
@connection_pools[pool_key] = new_entry
|
|
266
|
+
acquired = new_entry
|
|
267
|
+
created = true
|
|
268
|
+
end
|
|
269
|
+
end
|
|
270
|
+
ensure
|
|
271
|
+
evicted_pools.each { |evicted_pool| safe_disconnect(evicted_pool) }
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
log_pool_created(pool_key) if created
|
|
275
|
+
record_acquire_metrics(shard_key, created: created, evicted_count: evicted_pools.size, lru_removed: lru_removed)
|
|
276
|
+
acquired
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
def log_pool_created(pool_key)
|
|
280
|
+
logger&.info "[SchemaShard] Created pool '#{pool_key}' (#{@connection_pools.size}/#{@configuration.max_pools})"
|
|
281
|
+
rescue StandardError
|
|
282
|
+
nil
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def record_acquire_metrics(shard_key, created:, evicted_count:, lru_removed:)
|
|
286
|
+
if created
|
|
287
|
+
@metrics.increment(:pools_created_total)
|
|
288
|
+
@metrics.increment_shard(shard_key, :pools_created_total)
|
|
289
|
+
end
|
|
290
|
+
return unless evicted_count.positive?
|
|
291
|
+
|
|
292
|
+
@metrics.increment(:pools_evicted_total, evicted_count)
|
|
293
|
+
@metrics.increment(:pools_cleanup_total, 1) if lru_removed.positive?
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
# Skip @pool_keys_cache for per-tenant pools and cap its size to avoid unbounded RAM growth.
|
|
297
|
+
def resolve_pool_key(config, shard_key, read_only:, per_tenant_pool:)
|
|
298
|
+
return build_pool_key(config, shard_key, read_only: read_only) if per_tenant_pool
|
|
299
|
+
|
|
300
|
+
cache_id = "#{@configuration.effective_env}:#{shard_key}:#{read_only ? 'ro' : 'rw'}"
|
|
301
|
+
cached = @pool_keys_cache[cache_id]
|
|
302
|
+
return cached if cached
|
|
303
|
+
if @pool_keys_cache.size >= [@configuration.max_pools * 10, 10].max
|
|
304
|
+
return build_pool_key(config, shard_key, read_only: read_only)
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
@pool_keys_cache.compute_if_absent(cache_id) do
|
|
308
|
+
build_pool_key(config, shard_key, read_only: read_only)
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
def enforce_pool_limit_without_lock!(pool_key)
|
|
313
|
+
return [] if @connection_pools.size < @configuration.max_pools
|
|
314
|
+
|
|
315
|
+
evicted_list = []
|
|
316
|
+
sorted_candidates = @connection_pools
|
|
317
|
+
.each_pair
|
|
318
|
+
.reject { |k, _| k == pool_key }
|
|
319
|
+
.sort_by { |_, entry| entry.last_accessed }
|
|
320
|
+
.map(&:first)
|
|
321
|
+
|
|
322
|
+
sorted_candidates.each do |candidate_key|
|
|
323
|
+
break if @connection_pools.size < @configuration.max_pools
|
|
324
|
+
|
|
325
|
+
evicted = try_evict_pool_without_lock(candidate_key)
|
|
326
|
+
next unless evicted
|
|
327
|
+
|
|
328
|
+
logger&.warn "[SchemaShard] Pool limit reached; evicting '#{candidate_key}'"
|
|
329
|
+
evicted_list << evicted
|
|
330
|
+
end
|
|
331
|
+
|
|
332
|
+
return evicted_list if @connection_pools.size < @configuration.max_pools
|
|
333
|
+
|
|
334
|
+
raise PoolLimitExceededError,
|
|
335
|
+
"Connection pool limit (#{@configuration.max_pools}) reached and no idle evictable pool found"
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
def run_lru_cleanup_without_lock!(exclude_key: nil)
|
|
339
|
+
target = [@configuration.cleanup_threshold - 2, 0].max
|
|
340
|
+
sorted_keys = @connection_pools
|
|
341
|
+
.each_pair
|
|
342
|
+
.reject { |k, _| k == exclude_key }
|
|
343
|
+
.sort_by { |_, entry| entry.last_accessed }
|
|
344
|
+
.map(&:first)
|
|
345
|
+
evicted = []
|
|
346
|
+
|
|
347
|
+
sorted_keys.each do |key|
|
|
348
|
+
break if @connection_pools.size <= target
|
|
349
|
+
|
|
350
|
+
pool = try_evict_pool_without_lock(key)
|
|
351
|
+
evicted << pool if pool
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
logger&.info "[SchemaShard] LRU cleanup removed #{evicted.size} pools" if evicted.any?
|
|
355
|
+
evicted
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
def try_evict_pool_without_lock(pool_key)
|
|
359
|
+
entry = @connection_pools.delete(pool_key)
|
|
360
|
+
return nil unless entry
|
|
361
|
+
|
|
362
|
+
entry.evicted.make_true
|
|
363
|
+
in_use = entry.refcount.value.positive? || safe_pool_stat(entry.pool, fail_closed: true)[:busy].positive?
|
|
364
|
+
|
|
365
|
+
if in_use
|
|
366
|
+
entry.evicted.make_false
|
|
367
|
+
@connection_pools[pool_key] = entry
|
|
368
|
+
return nil
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
entry.pool
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
def monotonic_now
|
|
375
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
def safe_pool_stat(pool, fail_closed: true)
|
|
379
|
+
pool.stat
|
|
380
|
+
rescue StandardError
|
|
381
|
+
{ size: 0, busy: fail_closed ? 1 : 0, dead: 0, idle: 0, waiting: 0, checkout_timeout: 0 }
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
def extract_pool_config_summary(pool)
|
|
385
|
+
cfg = pool.respond_to?(:db_config) ? pool.db_config.configuration_hash : {}
|
|
386
|
+
{
|
|
387
|
+
pool_size: pool.respond_to?(:size) ? pool.size : cfg[:pool],
|
|
388
|
+
checkout_timeout: pool.respond_to?(:checkout_timeout) ? pool.checkout_timeout : cfg[:checkout_timeout]
|
|
389
|
+
}
|
|
390
|
+
rescue StandardError
|
|
391
|
+
{ pool_size: nil, checkout_timeout: nil }
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
def safe_disconnect(pool)
|
|
395
|
+
pool.disconnect!
|
|
396
|
+
true
|
|
397
|
+
rescue StandardError => e
|
|
398
|
+
logger&.warn "[SchemaShard] Error disconnecting pool: #{e.message}"
|
|
399
|
+
false
|
|
400
|
+
end
|
|
401
|
+
|
|
402
|
+
# Never call disconnect! in a forked child — it would transmit Terminate/COM_QUIT
|
|
403
|
+
# packets over sockets inherited from the parent process.
|
|
404
|
+
def safe_discard_pool(pool)
|
|
405
|
+
if pool.respond_to?(:discard!)
|
|
406
|
+
pool.discard!
|
|
407
|
+
elsif pool.respond_to?(:discard_pool!)
|
|
408
|
+
pool.discard_pool!
|
|
409
|
+
else
|
|
410
|
+
logger&.error '[SchemaShard] Pool does not support #discard!; dropping reference without disconnecting'
|
|
411
|
+
return false
|
|
412
|
+
end
|
|
413
|
+
true
|
|
414
|
+
rescue StandardError => e
|
|
415
|
+
logger&.warn "[SchemaShard] Error discarding pool after fork: #{e.message}"
|
|
416
|
+
false
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
def percent_used
|
|
420
|
+
(@connection_pools.size.to_f / @configuration.max_pools * 100).round(2)
|
|
421
|
+
end
|
|
422
|
+
|
|
423
|
+
def oldest_pool_age_seconds
|
|
424
|
+
min_time = @connection_pools.values.map(&:last_accessed).min
|
|
425
|
+
return 0 unless min_time
|
|
426
|
+
|
|
427
|
+
[(monotonic_now - min_time).to_i, 0].max
|
|
428
|
+
end
|
|
429
|
+
|
|
430
|
+
def stringify_keys(hash)
|
|
431
|
+
hash.each_with_object({}) { |(k, v), acc| acc[k.to_s] = v }
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
def symbolize_keys(hash)
|
|
435
|
+
hash.each_with_object({}) { |(k, v), acc| acc[k.to_sym] = v }
|
|
436
|
+
end
|
|
437
|
+
|
|
438
|
+
def logger
|
|
439
|
+
@configuration.effective_logger
|
|
440
|
+
end
|
|
441
|
+
end
|
|
442
|
+
end
|