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.
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'erb'
4
+ require 'yaml'
5
+
6
+ module SchemaShard
7
+ class ConfigLoader
8
+ def initialize(configuration:)
9
+ @configuration = configuration
10
+ @mutex = Mutex.new
11
+ @cache = nil
12
+ end
13
+
14
+ def fetch!(shard_key)
15
+ config = load_all
16
+ env_name = @configuration.effective_env
17
+ env_config = config[env_name] || config[env_name.to_sym]
18
+
19
+ raise ArgumentError, "Environment '#{env_name}' not found in shard configuration" unless env_config.is_a?(Hash)
20
+
21
+ raw_cfg = env_config[shard_key.to_s] || env_config[shard_key.to_sym]
22
+ unless raw_cfg.is_a?(Hash)
23
+ raise ArgumentError, "Shard '#{shard_key}' not found in shard configuration for environment '#{env_name}'"
24
+ end
25
+
26
+ shard_cfg = resolve_url_config(raw_cfg)
27
+ db_adapter = DatabaseAdapters.for(shard_cfg['adapter'] || shard_cfg[:adapter])
28
+ db_adapter.validate_config!(shard_key, shard_cfg)
29
+ shard_cfg
30
+ end
31
+
32
+ def reload!
33
+ @mutex.synchronize { @cache = nil }
34
+ nil
35
+ end
36
+
37
+ def load_all
38
+ cached = @cache
39
+ return cached if cached
40
+
41
+ @mutex.synchronize do
42
+ @cache ||= deep_freeze(load_and_parse)
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def resolve_url_config(raw_cfg)
49
+ url = raw_cfg['url'] || raw_cfg[:url]
50
+ return raw_cfg if url.nil? || url.to_s.strip.empty?
51
+
52
+ if url.to_s.include?('%{tenant}')
53
+ return raw_cfg if present_value?(raw_cfg['adapter'] || raw_cfg[:adapter])
54
+
55
+ scheme = extract_url_adapter(url.to_s)
56
+ return scheme ? deep_freeze(raw_cfg.transform_keys(&:to_s).merge('adapter' => scheme)) : raw_cfg
57
+ end
58
+
59
+ require 'active_record' unless defined?(ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver)
60
+ resolver_class = ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver
61
+ resolved = resolver_class.new(url.to_s).to_hash.transform_keys(&:to_s)
62
+ explicit = raw_cfg.transform_keys(&:to_s).except('url').compact
63
+ deep_freeze(resolved.merge(explicit))
64
+ end
65
+
66
+ def extract_url_adapter(url_str)
67
+ scheme = url_str[/\A([a-z0-9_+-]+):/i, 1]&.downcase
68
+ return 'postgresql' if scheme == 'postgres'
69
+
70
+ scheme
71
+ end
72
+
73
+ def present_value?(val)
74
+ !val.nil? && !val.to_s.strip.empty?
75
+ end
76
+
77
+ def load_and_parse
78
+ if @configuration.shards
79
+ raw = @configuration.shards.respond_to?(:call) ? @configuration.shards.call : @configuration.shards
80
+ raise ArgumentError, 'Configured shards must be a Hash' unless raw.is_a?(Hash)
81
+
82
+ return extract_root(stringify_nested_keys(raw))
83
+ end
84
+
85
+ load_from_yaml
86
+ end
87
+
88
+ def load_from_yaml
89
+ path = @configuration.config_path
90
+ content = begin
91
+ File.read(path)
92
+ rescue Errno::ENOENT
93
+ raise ArgumentError, "shards.yml not found at #{path}"
94
+ end
95
+
96
+ rendered = begin
97
+ ERB.new(content).result
98
+ rescue StandardError => e
99
+ raise ArgumentError, "shards.yml ERB evaluation failed: #{e.message}"
100
+ end
101
+
102
+ parsed = begin
103
+ YAML.safe_load(rendered, aliases: true)
104
+ rescue Psych::SyntaxError => e
105
+ raise ArgumentError, "shards.yml is malformed: #{e.message}"
106
+ end
107
+
108
+ raise ArgumentError, 'shards.yml must parse to a YAML mapping' unless parsed.is_a?(Hash)
109
+
110
+ extract_root(parsed)
111
+ end
112
+
113
+ def extract_root(parsed)
114
+ root_key = @configuration.config_root_key
115
+ return parsed if root_key.nil? || root_key.to_s.empty?
116
+
117
+ shards = parsed.fetch(root_key.to_s) do
118
+ raise ArgumentError, "shards.yml is missing required top-level '#{root_key}' key"
119
+ end
120
+
121
+ raise ArgumentError, "shards.yml '#{root_key}' entry must be a YAML mapping" unless shards.is_a?(Hash)
122
+
123
+ shards
124
+ end
125
+
126
+ def stringify_nested_keys(obj)
127
+ case obj
128
+ when Hash
129
+ obj.each_with_object({}) { |(k, v), acc| acc[k.to_s] = stringify_nested_keys(v) }
130
+ when Array
131
+ obj.map { |v| stringify_nested_keys(v) }
132
+ else
133
+ obj
134
+ end
135
+ end
136
+
137
+ def deep_freeze(obj)
138
+ case obj
139
+ when Hash
140
+ obj.each do |k, v|
141
+ deep_freeze(k)
142
+ deep_freeze(v)
143
+ end
144
+ when Array
145
+ obj.each { |v| deep_freeze(v) }
146
+ end
147
+ obj.freeze
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ class Configuration
5
+ VALID_TENANT_MODES = %i[strict optional none].freeze
6
+
7
+ attr_accessor :config_root_key, :shards, :default_shard,
8
+ :tenant_adapter, :default_schema, :persistent_schemas,
9
+ :excluded_models, :default_pool_size, :checkout_timeout,
10
+ :reaping_frequency, :logger, :env, :log_shard_queries,
11
+ :auto_fork_safety, :live_verify_fast_path, :max_tracked_shards
12
+ attr_writer :config_path
13
+ attr_reader :tenant_mode, :max_pools, :cleanup_threshold
14
+
15
+ def initialize
16
+ @config_path = nil
17
+ @config_root_key = nil
18
+ @shards = nil
19
+ @default_shard = nil
20
+ @tenant_adapter = :auto
21
+ @tenant_mode = :strict
22
+ @default_schema = 'public'
23
+ @persistent_schemas = []
24
+ @excluded_models = []
25
+ @max_pools = [ENV.fetch('SCHEMA_SHARD_MAX_POOLS', 10).to_i, 1].max
26
+ @cleanup_threshold = clamp_cleanup_threshold(ENV.fetch('SCHEMA_SHARD_CLEANUP_THRESHOLD', 8).to_i)
27
+ @default_pool_size = [ENV.fetch('RAILS_MAX_THREADS', 5).to_i, 1].max
28
+ @checkout_timeout = 5
29
+ @reaping_frequency = 10
30
+ @logger = nil
31
+ @env = nil
32
+ @log_shard_queries = false
33
+ @auto_fork_safety = true
34
+ @live_verify_fast_path = false
35
+ @max_tracked_shards = 100
36
+ end
37
+
38
+ def config_path
39
+ @config_path || default_config_path
40
+ end
41
+
42
+ def tenant_mode=(mode)
43
+ sym = mode.to_sym
44
+ unless VALID_TENANT_MODES.include?(sym)
45
+ raise ConfigurationError,
46
+ "Invalid tenant_mode: #{mode.inspect}. Expected one of #{VALID_TENANT_MODES.inspect}"
47
+ end
48
+
49
+ @tenant_mode = sym
50
+ end
51
+
52
+ def max_pools=(value)
53
+ @max_pools = [value.to_i, 1].max
54
+ @cleanup_threshold = clamp_cleanup_threshold(@cleanup_threshold)
55
+ end
56
+
57
+ def cleanup_threshold=(value)
58
+ @cleanup_threshold = clamp_cleanup_threshold(value.to_i)
59
+ end
60
+
61
+ def effective_env
62
+ return @env.to_s unless @env.nil? || @env.to_s.empty?
63
+
64
+ default_env
65
+ end
66
+
67
+ def effective_logger
68
+ return @logger unless @logger.nil?
69
+
70
+ default_logger
71
+ end
72
+
73
+ private
74
+
75
+ def clamp_cleanup_threshold(value)
76
+ value.clamp(1, @max_pools)
77
+ end
78
+
79
+ def default_config_path
80
+ if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
81
+ Rails.root.join('config', 'shards.yml')
82
+ else
83
+ File.join('config', 'shards.yml')
84
+ end
85
+ end
86
+
87
+ def default_logger
88
+ Rails.logger if defined?(Rails) && Rails.respond_to?(:logger)
89
+ end
90
+
91
+ def default_env
92
+ if defined?(Rails) && Rails.respond_to?(:env) && Rails.env
93
+ Rails.env.to_s
94
+ else
95
+ ENV.fetch('RAILS_ENV', ENV.fetch('RACK_ENV', 'development'))
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ # Prepended onto ActiveRecord::Base.singleton_class to route connection,
5
+ # lease_connection, retrieve_connection, and connection_pool calls to the active
6
+ # shard connection ONLY when a shard is active AND the model is routable.
7
+ module ConnectionPatch
8
+ def connection
9
+ conn = SchemaShard.active_connection
10
+ if conn && SchemaShard.routable_model?(self)
11
+ raise_if_tainted!
12
+ return conn
13
+ end
14
+
15
+ super
16
+ end
17
+
18
+ def lease_connection
19
+ conn = SchemaShard.active_connection
20
+ if conn && SchemaShard.routable_model?(self)
21
+ raise_if_tainted!
22
+ return conn
23
+ end
24
+
25
+ super
26
+ end
27
+
28
+ def retrieve_connection
29
+ conn = SchemaShard.active_connection
30
+ if conn && SchemaShard.routable_model?(self)
31
+ raise_if_tainted!
32
+ return conn
33
+ end
34
+
35
+ super
36
+ end
37
+
38
+ def connection_pool
39
+ pool = SchemaShard.active_pool
40
+ if pool && SchemaShard.routable_model?(self)
41
+ raise_if_tainted!
42
+ return pool
43
+ end
44
+
45
+ super
46
+ end
47
+
48
+ private
49
+
50
+ def raise_if_tainted!
51
+ return unless SchemaShard::ExecutionContext.active_pool_tainted?
52
+
53
+ raise SchemaShard::TaintedConnectionError, 'Active shard connection was discarded due to a prior taint'
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ class ConnectionSanitizer
5
+ def initialize(configuration:, metrics:)
6
+ @configuration = configuration
7
+ @metrics = metrics
8
+ end
9
+
10
+ def clear_query_cache!(pool, conn)
11
+ conn.clear_query_cache if conn.respond_to?(:clear_query_cache)
12
+ pool.clear_query_cache if pool.respond_to?(:clear_query_cache)
13
+ end
14
+
15
+ def verify_nested_clean!(pool, conn, shard_key:, db_adapter:, tenant_adapter:, shard_config:, **opts)
16
+ outer_tenant = opts[:outer_tenant]
17
+ tenant_switched = opts.fetch(:tenant_switched, false)
18
+ verify_live = opts.fetch(:verify_live, false)
19
+
20
+ if db_adapter.non_idle_transaction?(conn)
21
+ ExecutionContext.mark_pool_frames_tainted(pool)
22
+ discard_tainted(pool, conn, shard_key, 'nested non-idle transaction')
23
+ raise TaintedConnectionError, "Connection on '#{shard_key}' left in non-idle transaction after nested switch"
24
+ end
25
+
26
+ if outer_tenant
27
+ db_adapter.verify_and_restore_namespace!(
28
+ conn,
29
+ expected_tenant: outer_tenant,
30
+ persistent_schemas: tenant_adapter.persistent_schemas,
31
+ live: verify_live
32
+ )
33
+ elsif tenant_switched && db_adapter.supports_namespaces?
34
+ db_adapter.verify_and_reset_default_namespace!(
35
+ conn,
36
+ default_namespace: tenant_adapter.default_namespace(shard_config, db_adapter: db_adapter),
37
+ persistent_schemas: tenant_adapter.persistent_schemas,
38
+ live: verify_live
39
+ )
40
+ end
41
+ rescue TaintedConnectionError
42
+ raise
43
+ rescue StandardError => e
44
+ ExecutionContext.mark_pool_frames_tainted(pool)
45
+ discard_tainted(pool, conn, shard_key, "failed to restore outer tenant namespace: #{e.message}")
46
+ raise TaintedConnectionError, "Failed to restore outer tenant namespace on '#{shard_key}': #{e.message}"
47
+ end
48
+
49
+ def sanitize_before_checkin(pool, conn, shard_key:, db_adapter:, tenant_adapter:, shard_config:, **opts)
50
+ tenant_switched = opts.fetch(:tenant_switched, false)
51
+ verify_live = opts.fetch(:verify_live, false)
52
+ clear_query_cache!(pool, conn)
53
+
54
+ if db_adapter.non_idle_transaction?(conn)
55
+ discard_tainted(pool, conn, shard_key, 'non-idle or unverifiable transaction state')
56
+ return
57
+ end
58
+
59
+ if tenant_switched && db_adapter.supports_namespaces?
60
+ db_adapter.verify_and_reset_default_namespace!(
61
+ conn,
62
+ default_namespace: tenant_adapter.default_namespace(shard_config, db_adapter: db_adapter),
63
+ persistent_schemas: tenant_adapter.persistent_schemas,
64
+ live: verify_live
65
+ )
66
+ end
67
+
68
+ conn.clear_cache! if conn.respond_to?(:clear_cache!)
69
+ rescue StandardError => e
70
+ discard_tainted(pool, conn, shard_key, "sanitization error: #{e.message}")
71
+ end
72
+
73
+ # Removes the connection from the pool FIRST so a subsequent discard!/disconnect!
74
+ # error can never leave a tainted connection inside the pool's available queue.
75
+ def discard_tainted(pool, conn, shard_key, reason)
76
+ logger&.warn "[SchemaShard] Discarding tainted connection on '#{shard_key}' (#{reason})"
77
+ @metrics.increment(:connection_discards_total)
78
+ @metrics.increment_shard(shard_key, :connection_discards_total)
79
+
80
+ errors = []
81
+ run_discard_step(errors) { pool.remove(conn) if pool.respond_to?(:remove) }
82
+ run_discard_step(errors) { conn.discard! if conn.respond_to?(:discard!) }
83
+ run_discard_step(errors) { conn.disconnect! if conn.respond_to?(:disconnect!) }
84
+
85
+ return if errors.empty?
86
+
87
+ msg = errors.map(&:message).join('; ')
88
+ logger&.error "[SchemaShard] Failed to discard tainted connection on '#{shard_key}': #{msg}"
89
+ raise TaintedConnectionError, "Failed to discard tainted connection on '#{shard_key}': #{msg}"
90
+ end
91
+
92
+ private
93
+
94
+ def run_discard_step(errors)
95
+ yield
96
+ rescue StandardError => e
97
+ errors << e
98
+ end
99
+
100
+ def logger
101
+ @configuration.effective_logger
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ module DatabaseAdapters
5
+ @registry = {}
6
+ @mutex = Mutex.new
7
+
8
+ class << self
9
+ def register(name, adapter)
10
+ @mutex.synchronize do
11
+ @registry[name.to_s.downcase] = adapter
12
+ end
13
+ end
14
+
15
+ def for(adapter_name)
16
+ key = adapter_name.to_s.downcase
17
+ key = 'postgresql' if key.empty?
18
+
19
+ @mutex.synchronize { @registry[key] } || Generic.instance
20
+ end
21
+ end
22
+
23
+ class Base
24
+ VALID_IDENTIFIER_REGEX = /\A[a-zA-Z_][a-zA-Z0-9_-]{0,62}\z/
25
+
26
+ def self.instance
27
+ @instance ||= new
28
+ end
29
+
30
+ def supports_namespaces?
31
+ false
32
+ end
33
+
34
+ def validate_config!(shard_key, shard_cfg)
35
+ has_url = present_value?(shard_cfg['url'] || shard_cfg[:url])
36
+ has_host_and_db = present_value?(shard_cfg['host'] || shard_cfg[:host]) &&
37
+ present_value?(shard_cfg['database'] || shard_cfg[:database])
38
+
39
+ return if has_url || has_host_and_db
40
+
41
+ raise ArgumentError,
42
+ "Shard '#{shard_key}' must explicitly configure either 'url' or both 'host' and 'database'"
43
+ end
44
+
45
+ def validate_tenant!(tenant, default_namespace:, allow_public: false)
46
+ if tenant.nil?
47
+ raise InvalidTenantError,
48
+ 'Tenant name cannot be nil; use SchemaShard.on_shard or SchemaShard.with_public if default is intended'
49
+ end
50
+
51
+ str = tenant.to_s.strip
52
+ if str.empty?
53
+ raise InvalidTenantError, 'Tenant name cannot be blank; refusing to fall back to default namespace'
54
+ end
55
+
56
+ raise InvalidTenantError, "Invalid tenant name: #{str.inspect}" unless valid_tenant_identifier?(str)
57
+ raise InvalidTenantError, "Forbidden system namespace: #{str.inspect}" if forbidden_tenant?(str)
58
+
59
+ if default_namespace && str.casecmp?(default_namespace.to_s) && !allow_public
60
+ raise InvalidTenantError,
61
+ "Default namespace '#{str}' requires explicit allow_public: true or SchemaShard.with_public"
62
+ end
63
+
64
+ str
65
+ end
66
+
67
+ def default_pool_options(configuration)
68
+ {
69
+ 'adapter' => default_adapter_name,
70
+ 'encoding' => 'unicode',
71
+ 'pool' => configuration.default_pool_size,
72
+ 'checkout_timeout' => configuration.checkout_timeout,
73
+ 'reaping_frequency' => configuration.reaping_frequency
74
+ }
75
+ end
76
+
77
+ def apply_read_only_config(merged_config)
78
+ merged_config
79
+ end
80
+
81
+ def prepare_connection(_conn, read_only: true) # rubocop:disable Lint/UnusedMethodArgument
82
+ nil
83
+ end
84
+
85
+ def per_tenant_pool?(_shard_cfg)
86
+ false
87
+ end
88
+
89
+ def resolve_shard_config(shard_cfg, tenant: nil) # rubocop:disable Lint/UnusedMethodArgument
90
+ shard_cfg
91
+ end
92
+
93
+ def non_idle_transaction?(conn)
94
+ return false unless conn.respond_to?(:open_transactions)
95
+
96
+ conn.open_transactions.to_i.positive?
97
+ rescue StandardError
98
+ true
99
+ end
100
+
101
+ # Fail closed: adapters that do not implement tenant isolation must NOT silently
102
+ # execute tenant-scoped queries against a shared database.
103
+ def switch_namespace(_conn, _tenant, persistent_schemas: [], shard_config: nil) # rubocop:disable Lint/UnusedMethodArgument
104
+ raise ConfigurationError,
105
+ "#{self.class.name} does not support tenant namespace switching; " \
106
+ 'use SchemaShard.on_shard, set tenant_mode: :none, or register a custom adapter'
107
+ end
108
+
109
+ def current_namespace(_conn, live: false) # rubocop:disable Lint/UnusedMethodArgument
110
+ nil
111
+ end
112
+
113
+ def namespace_matches?(_conn, _expected_tenant, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
114
+ true
115
+ end
116
+
117
+ def verify_and_restore_namespace!(_conn, expected_tenant:, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
118
+ nil
119
+ end
120
+
121
+ def verify_and_reset_default_namespace!(_conn, default_namespace:, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
122
+ nil
123
+ end
124
+
125
+ def default_namespace_for(shard_cfg, configured_default: nil)
126
+ configured_default || shard_cfg['database'] || shard_cfg[:database]
127
+ end
128
+
129
+ protected
130
+
131
+ def default_adapter_name
132
+ 'postgresql'
133
+ end
134
+
135
+ def valid_tenant_identifier?(str)
136
+ VALID_IDENTIFIER_REGEX.match?(str)
137
+ end
138
+
139
+ def forbidden_tenant?(_str)
140
+ false
141
+ end
142
+
143
+ def present_value?(value)
144
+ !value.nil? && !value.to_s.strip.empty?
145
+ end
146
+ end
147
+ end
148
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module DatabaseAdapters
7
+ class Generic < Base
8
+ def validate_config!(shard_key, shard_cfg)
9
+ has_url = present_value?(shard_cfg['url'] || shard_cfg[:url])
10
+ has_db = present_value?(shard_cfg['database'] || shard_cfg[:database])
11
+ return if has_url || has_db
12
+
13
+ raise ArgumentError, "Shard '#{shard_key}' must explicitly configure 'database' or 'url'"
14
+ end
15
+ end
16
+ end
17
+ end