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
data/lib/schema_shard.rb
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'active_support'
|
|
4
|
+
require 'active_support/isolated_execution_state'
|
|
5
|
+
require 'active_record' unless defined?(Rails::Railtie)
|
|
6
|
+
|
|
7
|
+
require_relative 'schema_shard/version'
|
|
8
|
+
require_relative 'schema_shard/errors'
|
|
9
|
+
require_relative 'schema_shard/configuration'
|
|
10
|
+
require_relative 'schema_shard/database_adapters/base'
|
|
11
|
+
require_relative 'schema_shard/database_adapters/postgresql'
|
|
12
|
+
require_relative 'schema_shard/database_adapters/mysql'
|
|
13
|
+
require_relative 'schema_shard/database_adapters/sqlite'
|
|
14
|
+
require_relative 'schema_shard/database_adapters/generic'
|
|
15
|
+
require_relative 'schema_shard/tenant_adapters/base'
|
|
16
|
+
require_relative 'schema_shard/tenant_adapters/apartment'
|
|
17
|
+
require_relative 'schema_shard/tenant_adapters/native'
|
|
18
|
+
require_relative 'schema_shard/tenant_adapters/none'
|
|
19
|
+
require_relative 'schema_shard/config_loader'
|
|
20
|
+
require_relative 'schema_shard/execution_context'
|
|
21
|
+
require_relative 'schema_shard/pool_entry'
|
|
22
|
+
require_relative 'schema_shard/metrics'
|
|
23
|
+
require_relative 'schema_shard/pool_registry'
|
|
24
|
+
require_relative 'schema_shard/connection_sanitizer'
|
|
25
|
+
require_relative 'schema_shard/connection_patch'
|
|
26
|
+
require_relative 'schema_shard/middleware/sidekiq'
|
|
27
|
+
require_relative 'schema_shard/query_logger'
|
|
28
|
+
require_relative 'schema_shard/railtie' if defined?(Rails::Railtie)
|
|
29
|
+
|
|
30
|
+
module SchemaShard
|
|
31
|
+
module ForkHook
|
|
32
|
+
def _fork
|
|
33
|
+
pid = super
|
|
34
|
+
SchemaShard.discard_pools_after_fork! if pid.zero?
|
|
35
|
+
pid
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
class << self
|
|
40
|
+
def configuration
|
|
41
|
+
@configuration ||= Configuration.new
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def configure
|
|
45
|
+
yield(configuration)
|
|
46
|
+
configuration
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def reset_configuration!
|
|
50
|
+
@pool_registry&.cleanup_connection_pools!
|
|
51
|
+
@configuration = Configuration.new
|
|
52
|
+
@config_loader = nil
|
|
53
|
+
@pool_registry = nil
|
|
54
|
+
@sanitizer = nil
|
|
55
|
+
@metrics_store = nil
|
|
56
|
+
@excluded_models_cache = nil
|
|
57
|
+
configuration
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Prepends {SchemaShard::ConnectionPatch} onto +ActiveRecord::Base+ so model queries are
|
|
61
|
+
# routed to the active shard connection. Idempotent. Called automatically by the Railtie.
|
|
62
|
+
#
|
|
63
|
+
# NOTE: this does NOT install the +Process._fork+ hook; non-Rails apps should also call
|
|
64
|
+
# {.install_fork_hook!} (or {.discard_pools_after_fork!} in their fork callbacks).
|
|
65
|
+
#
|
|
66
|
+
# @return [void]
|
|
67
|
+
def install!
|
|
68
|
+
require 'active_record' unless defined?(ActiveRecord::Base)
|
|
69
|
+
return if ActiveRecord::Base.singleton_class.ancestors.include?(ConnectionPatch)
|
|
70
|
+
|
|
71
|
+
ActiveRecord::Base.singleton_class.prepend(ConnectionPatch)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Hooks +Process._fork+ (Ruby 3.1+) so forked children automatically discard inherited
|
|
75
|
+
# shard pools via {.discard_pools_after_fork!}. Idempotent; a no-op on Rubies without
|
|
76
|
+
# +Process._fork+. The Railtie calls this when +config.auto_fork_safety+ is true.
|
|
77
|
+
#
|
|
78
|
+
# @return [void]
|
|
79
|
+
def install_fork_hook!
|
|
80
|
+
return if @fork_hook_installed
|
|
81
|
+
return unless Process.respond_to?(:_fork)
|
|
82
|
+
|
|
83
|
+
Process.singleton_class.prepend(ForkHook)
|
|
84
|
+
@fork_hook_installed = true
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Runs the block against +shard_key+, scoped to +tenant+'s namespace (PostgreSQL schema,
|
|
88
|
+
# MySQL database, or SQLite per-tenant file).
|
|
89
|
+
#
|
|
90
|
+
# @param tenant [String, Symbol, nil] tenant name; +nil+ is only accepted in +:optional+
|
|
91
|
+
# mode (runs on the shard's default namespace) or ignored in +:none+ mode.
|
|
92
|
+
# @param shard_key [String, Symbol, nil] defaults to +configuration.default_shard+.
|
|
93
|
+
# @param allow_public [Boolean] permit the shard's default namespace as +tenant+.
|
|
94
|
+
# @param read_only [Boolean] enforce Ruby- and DB-level read-only protection.
|
|
95
|
+
# @yield the shard/tenant-scoped block
|
|
96
|
+
# @return [Object] the block's return value
|
|
97
|
+
# @raise [ArgumentError] when no block or shard key is given
|
|
98
|
+
# @raise [SchemaShard::InvalidTenantError] when the tenant name is invalid or forbidden
|
|
99
|
+
# @raise [SchemaShard::ConfigurationError] when opening a writable block inside a
|
|
100
|
+
# read-only block, or when the shard cannot isolate the requested tenant
|
|
101
|
+
def with(tenant = nil, shard_key: nil, allow_public: false, read_only: true, &)
|
|
102
|
+
raise ArgumentError, 'Block is required' unless block_given?
|
|
103
|
+
|
|
104
|
+
normalized_shard = resolve_shard_key!(shard_key)
|
|
105
|
+
shard_config = config_loader.fetch!(normalized_shard)
|
|
106
|
+
db_adapter = DatabaseAdapters.for(shard_config['adapter'] || shard_config[:adapter])
|
|
107
|
+
tenant_adapter = TenantAdapters.resolve(configuration, db_adapter: db_adapter)
|
|
108
|
+
|
|
109
|
+
normalized_tenant = resolve_tenant!(
|
|
110
|
+
tenant,
|
|
111
|
+
shard_config: shard_config,
|
|
112
|
+
db_adapter: db_adapter,
|
|
113
|
+
tenant_adapter: tenant_adapter,
|
|
114
|
+
allow_public: allow_public
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
execute_in_shard(
|
|
118
|
+
shard_key: normalized_shard,
|
|
119
|
+
shard_config: shard_config,
|
|
120
|
+
tenant: normalized_tenant,
|
|
121
|
+
db_adapter: db_adapter,
|
|
122
|
+
tenant_adapter: tenant_adapter,
|
|
123
|
+
read_only: read_only,
|
|
124
|
+
&
|
|
125
|
+
)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Runs the block against +shard_key+ on the shard's default namespace, without tenant
|
|
129
|
+
# selection, regardless of +tenant_mode+. When nested inside a tenant-scoped block on the
|
|
130
|
+
# same shard connection, the connection is temporarily switched to the default namespace
|
|
131
|
+
# and restored to the enclosing tenant afterwards.
|
|
132
|
+
#
|
|
133
|
+
# @param shard_key [String, Symbol, nil] defaults to +configuration.default_shard+.
|
|
134
|
+
# @param read_only [Boolean] enforce Ruby- and DB-level read-only protection.
|
|
135
|
+
# @yield the shard-scoped block
|
|
136
|
+
# @return [Object] the block's return value
|
|
137
|
+
# @raise [ArgumentError] when no block or shard key is given
|
|
138
|
+
# @raise [SchemaShard::ConfigurationError] when opening a writable block inside a read-only block
|
|
139
|
+
def on_shard(shard_key = nil, read_only: true, &)
|
|
140
|
+
raise ArgumentError, 'Block is required' unless block_given?
|
|
141
|
+
|
|
142
|
+
normalized_shard = resolve_shard_key!(shard_key)
|
|
143
|
+
shard_config = config_loader.fetch!(normalized_shard)
|
|
144
|
+
db_adapter = DatabaseAdapters.for(shard_config['adapter'] || shard_config[:adapter])
|
|
145
|
+
none_adapter = TenantAdapters::None.new(configuration)
|
|
146
|
+
|
|
147
|
+
execute_in_shard(
|
|
148
|
+
shard_key: normalized_shard,
|
|
149
|
+
shard_config: shard_config,
|
|
150
|
+
tenant: nil,
|
|
151
|
+
db_adapter: db_adapter,
|
|
152
|
+
tenant_adapter: none_adapter,
|
|
153
|
+
read_only: read_only,
|
|
154
|
+
&
|
|
155
|
+
)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Runs the block on the shard's default namespace as an explicit tenant (equivalent to
|
|
159
|
+
# +with(default_namespace, allow_public: true)+).
|
|
160
|
+
#
|
|
161
|
+
# @param shard_key [String, Symbol, nil] defaults to +configuration.default_shard+.
|
|
162
|
+
# @param read_only [Boolean] enforce Ruby- and DB-level read-only protection.
|
|
163
|
+
# @yield the block
|
|
164
|
+
# @return [Object] the block's return value
|
|
165
|
+
def with_public(shard_key: nil, read_only: true, &)
|
|
166
|
+
raise ArgumentError, 'Block is required' unless block_given?
|
|
167
|
+
|
|
168
|
+
normalized_shard = resolve_shard_key!(shard_key)
|
|
169
|
+
shard_config = config_loader.fetch!(normalized_shard)
|
|
170
|
+
db_adapter = DatabaseAdapters.for(shard_config['adapter'] || shard_config[:adapter])
|
|
171
|
+
tenant_adapter = TenantAdapters.resolve(configuration, db_adapter: db_adapter)
|
|
172
|
+
default_ns = tenant_adapter.default_namespace(shard_config, db_adapter: db_adapter)
|
|
173
|
+
|
|
174
|
+
with(default_ns, shard_key: normalized_shard, allow_public: true, read_only: read_only, &)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def current_config = ExecutionContext.current_config
|
|
178
|
+
def current_shard_label = ExecutionContext.current_shard_label
|
|
179
|
+
def current_tenant = ExecutionContext.current_tenant
|
|
180
|
+
def active_connection = ExecutionContext.active_connection
|
|
181
|
+
def active_pool = ExecutionContext.active_pool
|
|
182
|
+
|
|
183
|
+
def routable_model?(klass)
|
|
184
|
+
return true if klass == ActiveRecord::Base
|
|
185
|
+
return false if excluded_model?(klass)
|
|
186
|
+
return false if custom_connection_model?(klass)
|
|
187
|
+
|
|
188
|
+
true
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def clear_thread_locals!
|
|
192
|
+
ExecutionContext.clear!(logger: configuration.effective_logger)
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def reload_config!
|
|
196
|
+
config_loader.reload!
|
|
197
|
+
pool_registry.clear_key_cache!
|
|
198
|
+
pool_registry.cleanup_unused_pools!
|
|
199
|
+
nil
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def discard_pools_after_fork!
|
|
203
|
+
pool_registry.discard_pools_after_fork!
|
|
204
|
+
clear_thread_locals!
|
|
205
|
+
nil
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def pool_count = pool_registry.pool_count
|
|
209
|
+
def pool_usage_info = pool_registry.pool_usage_info
|
|
210
|
+
def pool_statistics = pool_registry.pool_statistics
|
|
211
|
+
def total_active_connections = pool_registry.total_active_connections
|
|
212
|
+
def cleanup_connection_pools! = pool_registry.cleanup_connection_pools!
|
|
213
|
+
def cleanup_unused_pools! = pool_registry.cleanup_unused_pools!
|
|
214
|
+
|
|
215
|
+
def metrics = metrics_store.snapshot(pool_status: pool_registry.pool_status_snapshot)
|
|
216
|
+
def prometheus_metrics = metrics_store.prometheus(pool_status: pool_registry.pool_status_snapshot)
|
|
217
|
+
def statsd_metrics = metrics_store.statsd(pool_status: pool_registry.pool_status_snapshot)
|
|
218
|
+
def reset_metrics! = metrics_store.reset!
|
|
219
|
+
|
|
220
|
+
def increment_metric(metric_name, count = 1)
|
|
221
|
+
metrics_store.increment(metric_name, count)
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def increment_shard_metric(shard_key, metric_name, count = 1)
|
|
225
|
+
metrics_store.increment_shard(shard_key, metric_name, count)
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
def config_loader
|
|
229
|
+
@config_loader ||= ConfigLoader.new(configuration: configuration)
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
def pool_registry
|
|
233
|
+
@pool_registry ||= PoolRegistry.new(configuration: configuration, metrics: metrics_store)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
def metrics_store
|
|
237
|
+
@metrics_store ||= Metrics.new(configuration: configuration)
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
def sanitizer
|
|
241
|
+
@sanitizer ||= ConnectionSanitizer.new(configuration: configuration, metrics: metrics_store)
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
private
|
|
245
|
+
|
|
246
|
+
def execute_in_shard(shard_key:, shard_config:, tenant:, db_adapter:, tenant_adapter:, read_only:, &block)
|
|
247
|
+
if same_active_context?(shard_key, shard_config, tenant, read_only, tenant_adapter, db_adapter)
|
|
248
|
+
metrics_store.track_switch(shard_key)
|
|
249
|
+
return yield
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
metrics_store.track_switch(shard_key)
|
|
253
|
+
reject_write_escalation!(read_only)
|
|
254
|
+
entry = nil
|
|
255
|
+
|
|
256
|
+
begin
|
|
257
|
+
entry = pool_registry.acquire(shard_config, shard_key, db_adapter: db_adapter,
|
|
258
|
+
read_only: read_only, tenant: tenant)
|
|
259
|
+
with_read_only_guard(read_only) do
|
|
260
|
+
ExecutionContext.with_context(shard_key: shard_key, config: shard_config,
|
|
261
|
+
tenant: tenant, read_only: read_only) do
|
|
262
|
+
scope = {
|
|
263
|
+
shard_key: shard_key, shard_config: shard_config, tenant: tenant,
|
|
264
|
+
db_adapter: db_adapter, tenant_adapter: tenant_adapter, read_only: read_only
|
|
265
|
+
}
|
|
266
|
+
with_pool_scope(entry.pool, scope, &block)
|
|
267
|
+
end
|
|
268
|
+
end
|
|
269
|
+
ensure
|
|
270
|
+
entry&.release
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
def resolve_shard_key!(shard_key)
|
|
275
|
+
resolved = shard_key.nil? ? configuration.default_shard : shard_key
|
|
276
|
+
if resolved.nil? || resolved.to_s.strip.empty?
|
|
277
|
+
raise ArgumentError, 'shard_key is required (or configure SchemaShard.configuration.default_shard)'
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
resolved.to_s
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
def resolve_tenant!(tenant, shard_config:, db_adapter:, tenant_adapter:, allow_public:)
|
|
284
|
+
return nil unless tenant_adapter.switches_tenant?
|
|
285
|
+
return nil if tenant.nil? && configuration.tenant_mode == :optional
|
|
286
|
+
|
|
287
|
+
effective_allow_public = allow_public || configuration.tenant_mode == :optional
|
|
288
|
+
default_ns = tenant_adapter.default_namespace(shard_config, db_adapter: db_adapter)
|
|
289
|
+
|
|
290
|
+
db_adapter.validate_tenant!(tenant, default_namespace: default_ns, allow_public: effective_allow_public)
|
|
291
|
+
end
|
|
292
|
+
|
|
293
|
+
def same_active_context?(shard_key, shard_config, tenant, read_only, tenant_adapter, db_adapter)
|
|
294
|
+
conn = ExecutionContext.active_connection
|
|
295
|
+
return false unless conn && context_metadata_matches?(shard_key, shard_config, tenant, read_only)
|
|
296
|
+
|
|
297
|
+
live = configuration.live_verify_fast_path
|
|
298
|
+
if tenant && tenant_adapter.switches_tenant?
|
|
299
|
+
return tenant_adapter.matches_current?(tenant, conn: conn, db_adapter: db_adapter, live: live)
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
return true unless tenant.nil? && db_adapter.supports_namespaces?
|
|
303
|
+
|
|
304
|
+
default_ns = tenant_adapter.default_namespace(shard_config, db_adapter: db_adapter)
|
|
305
|
+
db_adapter.namespace_matches?(conn, default_ns, persistent_schemas: tenant_adapter.persistent_schemas, live: live)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def context_metadata_matches?(shard_key, shard_config, tenant, read_only)
|
|
309
|
+
ExecutionContext.current_shard_label == shard_key &&
|
|
310
|
+
ExecutionContext.current_config == shard_config &&
|
|
311
|
+
ExecutionContext.current_tenant == tenant &&
|
|
312
|
+
ExecutionContext.read_only? == read_only
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# Reject before acquiring a pool so a refused escalation never creates (or evicts for)
|
|
316
|
+
# a writable connection pool.
|
|
317
|
+
def reject_write_escalation!(read_only)
|
|
318
|
+
return unless !read_only && ExecutionContext.read_only? == true
|
|
319
|
+
|
|
320
|
+
raise ConfigurationError, 'Cannot open a writable shard block (read_only: false) inside a read-only block'
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
def with_read_only_guard(read_only, &)
|
|
324
|
+
if read_only && ActiveRecord::Base.respond_to?(:while_preventing_writes)
|
|
325
|
+
ActiveRecord::Base.while_preventing_writes(&)
|
|
326
|
+
elsif !read_only && ExecutionContext.read_only? == true
|
|
327
|
+
reject_write_escalation!(read_only)
|
|
328
|
+
else
|
|
329
|
+
yield
|
|
330
|
+
end
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
def with_pool_scope(pool, scope, &block)
|
|
334
|
+
enclosing = ExecutionContext.enclosing_pool_frame(pool)
|
|
335
|
+
if enclosing&.dig(:tainted)
|
|
336
|
+
raise TaintedConnectionError, "Cannot open nested block on tainted shard pool '#{scope[:shard_key]}'"
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
reentrant = !enclosing.nil?
|
|
340
|
+
|
|
341
|
+
checkout_connection(pool) do |conn|
|
|
342
|
+
metrics_store.increment(:connection_checkouts_total)
|
|
343
|
+
run_on_connection(pool, conn, scope, enclosing: enclosing, reentrant: reentrant, &block)
|
|
344
|
+
end
|
|
345
|
+
rescue ActiveRecord::ConnectionTimeoutError => e
|
|
346
|
+
metrics_store.increment(:connection_timeouts_total)
|
|
347
|
+
configuration.effective_logger&.error "[SchemaShard] Checkout timeout for #{scope[:shard_key]}: #{e.message}"
|
|
348
|
+
raise
|
|
349
|
+
rescue ActiveRecord::ConnectionNotEstablished => e
|
|
350
|
+
metrics_store.increment(:connection_verification_failures_total)
|
|
351
|
+
metrics_store.increment_shard(scope[:shard_key], :verification_failures_total)
|
|
352
|
+
configuration.effective_logger&.error "[SchemaShard] Connection failed for #{scope[:shard_key]}: #{e.message}"
|
|
353
|
+
raise
|
|
354
|
+
end
|
|
355
|
+
|
|
356
|
+
def checkout_connection(pool, &)
|
|
357
|
+
@checkout_cap_cache ||= Concurrent::Map.new
|
|
358
|
+
supports_key = @checkout_cap_cache.compute_if_absent(pool.class) do
|
|
359
|
+
params = pool.method(:with_connection).parameters
|
|
360
|
+
params.any? { |type, name| type == :key && name == :prevent_permanent_checkout }
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
if supports_key
|
|
364
|
+
pool.with_connection(prevent_permanent_checkout: true, &)
|
|
365
|
+
else
|
|
366
|
+
pool.with_connection(&)
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
def run_on_connection(pool, conn, scope, enclosing:, reentrant:, &block)
|
|
371
|
+
block_raised = false
|
|
372
|
+
tenant_switched = !scope[:tenant].nil? && scope[:tenant_adapter].switches_tenant?
|
|
373
|
+
default_reset = tenant_switched ? nil : nested_default_reset(scope, enclosing)
|
|
374
|
+
tenant_switched ||= !default_reset.nil?
|
|
375
|
+
ExecutionContext.mark_pool_frames_dirty(pool) if reentrant && tenant_switched
|
|
376
|
+
frame = ExecutionContext.push_pool_frame(
|
|
377
|
+
pool, tenant: scope[:tenant], tenant_switched: tenant_switched, tenant_adapter: scope[:tenant_adapter]
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
begin
|
|
381
|
+
scope[:db_adapter].prepare_connection(conn, read_only: scope[:read_only])
|
|
382
|
+
ExecutionContext.with_connection(conn, pool) do
|
|
383
|
+
sanitizer.clear_query_cache!(pool, conn)
|
|
384
|
+
run_scoped_block(conn, scope, tenant_switched: tenant_switched, default_reset: default_reset, &block)
|
|
385
|
+
end
|
|
386
|
+
rescue Exception # rubocop:disable Lint/RescueException
|
|
387
|
+
block_raised = true
|
|
388
|
+
raise
|
|
389
|
+
ensure
|
|
390
|
+
ExecutionContext.pop_pool_frame(pool)
|
|
391
|
+
begin
|
|
392
|
+
cleanup_after_connection(
|
|
393
|
+
pool, conn, scope,
|
|
394
|
+
enclosing: enclosing, reentrant: reentrant,
|
|
395
|
+
tenant_switched: tenant_switched || frame[:dirty], block_raised: block_raised
|
|
396
|
+
)
|
|
397
|
+
ensure
|
|
398
|
+
pool.release_connection if !reentrant && pool.respond_to?(:release_connection)
|
|
399
|
+
end
|
|
400
|
+
end
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
def run_scoped_block(conn, scope, tenant_switched:, default_reset:, &)
|
|
404
|
+
if default_reset
|
|
405
|
+
scope[:db_adapter].switch_namespace(
|
|
406
|
+
conn, default_reset[:namespace],
|
|
407
|
+
persistent_schemas: default_reset[:persistent_schemas], shard_config: scope[:shard_config], &
|
|
408
|
+
)
|
|
409
|
+
elsif tenant_switched
|
|
410
|
+
scope[:tenant_adapter].switch(
|
|
411
|
+
scope[:tenant], conn: conn, db_adapter: scope[:db_adapter], shard_config: scope[:shard_config], &
|
|
412
|
+
)
|
|
413
|
+
else
|
|
414
|
+
yield
|
|
415
|
+
end
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
# A tenant-less block (+on_shard+, or +with(nil)+ in :optional mode) that re-enters a
|
|
419
|
+
# connection an enclosing block pinned to a tenant namespace must NOT inherit that
|
|
420
|
+
# tenant's search_path / database. Returns the shard default namespace to switch to
|
|
421
|
+
# (fail closed if it cannot be determined), or nil when no reset is needed.
|
|
422
|
+
def nested_default_reset(scope, enclosing)
|
|
423
|
+
return nil unless scope[:tenant].nil? && enclosing && !enclosing[:tenant].nil?
|
|
424
|
+
|
|
425
|
+
db_adapter = scope[:db_adapter]
|
|
426
|
+
return nil unless db_adapter.supports_namespaces?
|
|
427
|
+
|
|
428
|
+
adapter = TenantAdapters.resolve(configuration, db_adapter: db_adapter)
|
|
429
|
+
namespace = adapter.default_namespace(scope[:shard_config], db_adapter: db_adapter)
|
|
430
|
+
if namespace.nil? || namespace.to_s.strip.empty?
|
|
431
|
+
raise ConfigurationError,
|
|
432
|
+
"Cannot determine default namespace for shard '#{scope[:shard_key]}' while nested inside " \
|
|
433
|
+
"tenant '#{enclosing[:tenant]}'; refusing to run on the enclosing tenant's namespace"
|
|
434
|
+
end
|
|
435
|
+
|
|
436
|
+
{ namespace: namespace.to_s, persistent_schemas: adapter.persistent_schemas }
|
|
437
|
+
end
|
|
438
|
+
|
|
439
|
+
def cleanup_after_connection(pool, conn, scope, enclosing:, reentrant:, tenant_switched:, block_raised:)
|
|
440
|
+
if reentrant
|
|
441
|
+
sanitizer.clear_query_cache!(pool, conn)
|
|
442
|
+
sanitizer.verify_nested_clean!(
|
|
443
|
+
pool, conn,
|
|
444
|
+
shard_key: scope[:shard_key], db_adapter: scope[:db_adapter],
|
|
445
|
+
tenant_adapter: cleanup_tenant_adapter(enclosing[:tenant_adapter], scope[:db_adapter]),
|
|
446
|
+
shard_config: scope[:shard_config],
|
|
447
|
+
outer_tenant: enclosing[:tenant], tenant_switched: tenant_switched, verify_live: block_raised
|
|
448
|
+
)
|
|
449
|
+
else
|
|
450
|
+
sanitizer.sanitize_before_checkin(
|
|
451
|
+
pool, conn,
|
|
452
|
+
shard_key: scope[:shard_key], db_adapter: scope[:db_adapter],
|
|
453
|
+
tenant_adapter: cleanup_tenant_adapter(scope[:tenant_adapter], scope[:db_adapter]),
|
|
454
|
+
shard_config: scope[:shard_config],
|
|
455
|
+
tenant_switched: tenant_switched, verify_live: block_raised
|
|
456
|
+
)
|
|
457
|
+
end
|
|
458
|
+
end
|
|
459
|
+
|
|
460
|
+
def cleanup_tenant_adapter(adapter, db_adapter)
|
|
461
|
+
return adapter if adapter && !adapter.is_a?(TenantAdapters::None)
|
|
462
|
+
|
|
463
|
+
TenantAdapters.resolve(configuration, db_adapter: db_adapter)
|
|
464
|
+
end
|
|
465
|
+
|
|
466
|
+
def excluded_model?(klass)
|
|
467
|
+
excluded_set = cached_excluded_models_set
|
|
468
|
+
return false if excluded_set.empty?
|
|
469
|
+
|
|
470
|
+
klass.ancestors.any? do |ancestor|
|
|
471
|
+
ancestor.is_a?(Class) && ancestor < ActiveRecord::Base && excluded_set.include?(ancestor.name)
|
|
472
|
+
end
|
|
473
|
+
end
|
|
474
|
+
|
|
475
|
+
def cached_excluded_models_set
|
|
476
|
+
apt_excluded = (::Apartment.excluded_models if defined?(::Apartment) && ::Apartment.respond_to?(:excluded_models))
|
|
477
|
+
cache_key = [
|
|
478
|
+
configuration.tenant_adapter,
|
|
479
|
+
configuration.tenant_mode,
|
|
480
|
+
Array(configuration.excluded_models).dup,
|
|
481
|
+
apt_excluded ? Array(apt_excluded).dup : nil
|
|
482
|
+
]
|
|
483
|
+
cached = @excluded_models_cache
|
|
484
|
+
return cached[1] if cached && cached[0] == cache_key
|
|
485
|
+
|
|
486
|
+
set = TenantAdapters.resolve(configuration).excluded_models.to_set.freeze
|
|
487
|
+
@excluded_models_cache = [cache_key, set]
|
|
488
|
+
set
|
|
489
|
+
end
|
|
490
|
+
|
|
491
|
+
def custom_connection_model?(klass)
|
|
492
|
+
if klass.respond_to?(:connection_class_for_self)
|
|
493
|
+
conn_class = klass.connection_class_for_self
|
|
494
|
+
return true unless primary_connection_class?(conn_class)
|
|
495
|
+
end
|
|
496
|
+
|
|
497
|
+
return false unless klass.respond_to?(:connection_handler)
|
|
498
|
+
|
|
499
|
+
handler = klass.connection_handler
|
|
500
|
+
klass.ancestors.any? do |ancestor|
|
|
501
|
+
next false unless ancestor.is_a?(Class) && ancestor < ActiveRecord::Base && ancestor.name
|
|
502
|
+
next false if primary_connection_class?(ancestor)
|
|
503
|
+
|
|
504
|
+
!handler.retrieve_connection_pool(ancestor.name, strict: false).nil?
|
|
505
|
+
end
|
|
506
|
+
end
|
|
507
|
+
|
|
508
|
+
def primary_connection_class?(klass)
|
|
509
|
+
return true if klass == ActiveRecord::Base
|
|
510
|
+
return true if klass.respond_to?(:primary_class?) && klass.primary_class?
|
|
511
|
+
return true if defined?(ApplicationRecord) && klass == ApplicationRecord
|
|
512
|
+
|
|
513
|
+
false
|
|
514
|
+
end
|
|
515
|
+
end
|
|
516
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: schema_shard
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.1
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Raynald Serenas (syrens)
|
|
8
|
+
autorequire:
|
|
9
|
+
bindir: bin
|
|
10
|
+
cert_chain: []
|
|
11
|
+
date: 2026-11-29 00:00:00.000000000 Z
|
|
12
|
+
dependencies:
|
|
13
|
+
- !ruby/object:Gem::Dependency
|
|
14
|
+
name: activerecord
|
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
|
16
|
+
requirements:
|
|
17
|
+
- - ">="
|
|
18
|
+
- !ruby/object:Gem::Version
|
|
19
|
+
version: '8.0'
|
|
20
|
+
- - "<"
|
|
21
|
+
- !ruby/object:Gem::Version
|
|
22
|
+
version: '9.0'
|
|
23
|
+
type: :runtime
|
|
24
|
+
prerelease: false
|
|
25
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
26
|
+
requirements:
|
|
27
|
+
- - ">="
|
|
28
|
+
- !ruby/object:Gem::Version
|
|
29
|
+
version: '8.0'
|
|
30
|
+
- - "<"
|
|
31
|
+
- !ruby/object:Gem::Version
|
|
32
|
+
version: '9.0'
|
|
33
|
+
- !ruby/object:Gem::Dependency
|
|
34
|
+
name: activesupport
|
|
35
|
+
requirement: !ruby/object:Gem::Requirement
|
|
36
|
+
requirements:
|
|
37
|
+
- - ">="
|
|
38
|
+
- !ruby/object:Gem::Version
|
|
39
|
+
version: '8.0'
|
|
40
|
+
- - "<"
|
|
41
|
+
- !ruby/object:Gem::Version
|
|
42
|
+
version: '9.0'
|
|
43
|
+
type: :runtime
|
|
44
|
+
prerelease: false
|
|
45
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
46
|
+
requirements:
|
|
47
|
+
- - ">="
|
|
48
|
+
- !ruby/object:Gem::Version
|
|
49
|
+
version: '8.0'
|
|
50
|
+
- - "<"
|
|
51
|
+
- !ruby/object:Gem::Version
|
|
52
|
+
version: '9.0'
|
|
53
|
+
- !ruby/object:Gem::Dependency
|
|
54
|
+
name: concurrent-ruby
|
|
55
|
+
requirement: !ruby/object:Gem::Requirement
|
|
56
|
+
requirements:
|
|
57
|
+
- - "~>"
|
|
58
|
+
- !ruby/object:Gem::Version
|
|
59
|
+
version: '1.2'
|
|
60
|
+
type: :runtime
|
|
61
|
+
prerelease: false
|
|
62
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
63
|
+
requirements:
|
|
64
|
+
- - "~>"
|
|
65
|
+
- !ruby/object:Gem::Version
|
|
66
|
+
version: '1.2'
|
|
67
|
+
description: |-
|
|
68
|
+
SchemaShard provides dynamic, LRU-managed database shard and read-replica connection
|
|
69
|
+
pooling for Rails 8+ applications with optional, fail-closed multi-tenant isolation
|
|
70
|
+
(PostgreSQL schemas via ros-apartment or native search_path, MySQL/Trilogy databases,
|
|
71
|
+
SQLite3 per-tenant files, or pure shard-only routing). Includes dual-layer read-only
|
|
72
|
+
enforcement, connection hygiene, fork safety, and Prometheus/StatsD observability.
|
|
73
|
+
email:
|
|
74
|
+
- raynald.serenas@gmail.com
|
|
75
|
+
executables: []
|
|
76
|
+
extensions: []
|
|
77
|
+
extra_rdoc_files: []
|
|
78
|
+
files:
|
|
79
|
+
- CHANGELOG.md
|
|
80
|
+
- LICENSE.txt
|
|
81
|
+
- README.md
|
|
82
|
+
- lib/generators/schema_shard/install_generator.rb
|
|
83
|
+
- lib/generators/schema_shard/templates/initializer.rb.tt
|
|
84
|
+
- lib/generators/schema_shard/templates/shards.yml.tt
|
|
85
|
+
- lib/schema_shard.rb
|
|
86
|
+
- lib/schema_shard/config_loader.rb
|
|
87
|
+
- lib/schema_shard/configuration.rb
|
|
88
|
+
- lib/schema_shard/connection_patch.rb
|
|
89
|
+
- lib/schema_shard/connection_sanitizer.rb
|
|
90
|
+
- lib/schema_shard/database_adapters/base.rb
|
|
91
|
+
- lib/schema_shard/database_adapters/generic.rb
|
|
92
|
+
- lib/schema_shard/database_adapters/mysql.rb
|
|
93
|
+
- lib/schema_shard/database_adapters/postgresql.rb
|
|
94
|
+
- lib/schema_shard/database_adapters/sqlite.rb
|
|
95
|
+
- lib/schema_shard/errors.rb
|
|
96
|
+
- lib/schema_shard/execution_context.rb
|
|
97
|
+
- lib/schema_shard/metrics.rb
|
|
98
|
+
- lib/schema_shard/middleware/sidekiq.rb
|
|
99
|
+
- lib/schema_shard/pool_entry.rb
|
|
100
|
+
- lib/schema_shard/pool_registry.rb
|
|
101
|
+
- lib/schema_shard/query_logger.rb
|
|
102
|
+
- lib/schema_shard/railtie.rb
|
|
103
|
+
- lib/schema_shard/tenant_adapters/apartment.rb
|
|
104
|
+
- lib/schema_shard/tenant_adapters/base.rb
|
|
105
|
+
- lib/schema_shard/tenant_adapters/native.rb
|
|
106
|
+
- lib/schema_shard/tenant_adapters/none.rb
|
|
107
|
+
- lib/schema_shard/version.rb
|
|
108
|
+
homepage: https://github.com/syrens/schema_shard
|
|
109
|
+
licenses:
|
|
110
|
+
- MIT
|
|
111
|
+
metadata:
|
|
112
|
+
source_code_uri: https://github.com/syrens/schema_shard
|
|
113
|
+
changelog_uri: https://github.com/syrens/schema_shard/blob/main/CHANGELOG.md
|
|
114
|
+
bug_tracker_uri: https://github.com/syrens/schema_shard/issues
|
|
115
|
+
rubygems_mfa_required: 'true'
|
|
116
|
+
post_install_message:
|
|
117
|
+
rdoc_options: []
|
|
118
|
+
require_paths:
|
|
119
|
+
- lib
|
|
120
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
121
|
+
requirements:
|
|
122
|
+
- - ">="
|
|
123
|
+
- !ruby/object:Gem::Version
|
|
124
|
+
version: 3.2.0
|
|
125
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
126
|
+
requirements:
|
|
127
|
+
- - ">="
|
|
128
|
+
- !ruby/object:Gem::Version
|
|
129
|
+
version: '0'
|
|
130
|
+
requirements: []
|
|
131
|
+
rubygems_version: 3.5.22
|
|
132
|
+
signing_key:
|
|
133
|
+
specification_version: 4
|
|
134
|
+
summary: Rails 8-first database sharding and read-replica routing with optional multi-tenant
|
|
135
|
+
isolation.
|
|
136
|
+
test_files: []
|