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,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module DatabaseAdapters
7
+ class Mysql < Base
8
+ VALID_MYSQL_DB_REGEX = /\A[a-zA-Z_][a-zA-Z0-9_-]{0,63}\z/
9
+ FORBIDDEN_DATABASES = %w[mysql information_schema performance_schema sys].freeze
10
+ SERVER_STATUS_IN_TRANS = 0x0001
11
+
12
+ def supports_namespaces?
13
+ true
14
+ end
15
+
16
+ def default_pool_options(configuration)
17
+ {
18
+ 'adapter' => 'trilogy',
19
+ 'encoding' => 'utf8mb4',
20
+ 'pool' => configuration.default_pool_size,
21
+ 'checkout_timeout' => configuration.checkout_timeout,
22
+ 'reaping_frequency' => configuration.reaping_frequency
23
+ }
24
+ end
25
+
26
+ def apply_read_only_config(merged_config)
27
+ updated = merged_config.dup
28
+ vars = updated['variables'].is_a?(Hash) ? updated['variables'].transform_keys(&:to_s) : {}
29
+ vars['transaction_read_only'] = 1
30
+ updated['variables'] = vars
31
+ updated
32
+ end
33
+
34
+ def non_idle_transaction?(conn)
35
+ return true if conn.respond_to?(:open_transactions) && conn.open_transactions.to_i.positive?
36
+
37
+ raw_state = check_raw_transaction_state(conn)
38
+ return raw_state unless raw_state.nil?
39
+
40
+ mariadb_in_transaction?(conn)
41
+ rescue StandardError
42
+ true
43
+ end
44
+
45
+ def switch_namespace(conn, tenant, persistent_schemas: [], shard_config: nil) # rubocop:disable Lint/UnusedMethodArgument
46
+ previous_db = current_namespace(conn, live: true)
47
+ switched = false
48
+ in_flight = false
49
+
50
+ use_database!(conn, tenant)
51
+ switched = true
52
+
53
+ begin
54
+ conn.clear_cache! if conn.respond_to?(:clear_cache!)
55
+ yield
56
+ rescue Exception # rubocop:disable Lint/RescueException
57
+ in_flight = true
58
+ raise
59
+ end
60
+ ensure
61
+ restore_database(conn, previous_db, suppress_errors: in_flight) if switched
62
+ end
63
+
64
+ def current_namespace(conn, live: false)
65
+ return conn.select_value('SELECT DATABASE()')&.to_s if live && conn.respond_to?(:select_value)
66
+ return conn.current_database.to_s if conn.respond_to?(:current_database)
67
+
68
+ nil
69
+ rescue StandardError
70
+ nil
71
+ end
72
+
73
+ def namespace_matches?(conn, expected_tenant, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
74
+ actual = current_namespace(conn, live: live)
75
+ !actual.nil? && actual.casecmp?(expected_tenant.to_s)
76
+ end
77
+
78
+ def verify_and_restore_namespace!(conn, expected_tenant:, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
79
+ actual = current_namespace(conn, live: live)
80
+ return if actual&.casecmp?(expected_tenant.to_s)
81
+
82
+ use_database!(conn, expected_tenant)
83
+ end
84
+
85
+ def verify_and_reset_default_namespace!(conn, default_namespace:, persistent_schemas: [], live: false) # rubocop:disable Lint/UnusedMethodArgument
86
+ unless present_value?(default_namespace)
87
+ raise TaintedConnectionError, 'cannot reset MySQL database: default_namespace is blank'
88
+ end
89
+
90
+ actual = current_namespace(conn, live: live)
91
+ raise TaintedConnectionError, 'unverifiable MySQL database' if actual.nil?
92
+ return if actual.casecmp?(default_namespace.to_s)
93
+
94
+ use_database!(conn, default_namespace)
95
+ end
96
+
97
+ def default_namespace_for(shard_cfg, configured_default: nil)
98
+ shard_cfg['database'] || shard_cfg[:database] || configured_default
99
+ end
100
+
101
+ protected
102
+
103
+ def default_adapter_name
104
+ 'trilogy'
105
+ end
106
+
107
+ def valid_tenant_identifier?(str)
108
+ VALID_MYSQL_DB_REGEX.match?(str)
109
+ end
110
+
111
+ def forbidden_tenant?(str)
112
+ FORBIDDEN_DATABASES.include?(str.downcase)
113
+ end
114
+
115
+ private
116
+
117
+ def check_raw_transaction_state(conn)
118
+ return nil unless conn.respond_to?(:raw_connection)
119
+
120
+ raw = conn.raw_connection
121
+ return true if raw.nil?
122
+ return raw.server_status.to_i.anybits?(SERVER_STATUS_IN_TRANS) if raw.respond_to?(:server_status)
123
+ return raw.in_transaction? if raw.respond_to?(:in_transaction?)
124
+ return nil unless defined?(::Trilogy::Result) && raw.respond_to?(:query)
125
+
126
+ res = raw.query('SELECT 1')
127
+ res.respond_to?(:in_transaction?) ? res.in_transaction? : nil
128
+ end
129
+
130
+ def mariadb_in_transaction?(conn)
131
+ return false unless conn.respond_to?(:mariadb?) && conn.mariadb? && conn.respond_to?(:select_value)
132
+
133
+ conn.select_value('SELECT @@in_transaction').to_i.positive?
134
+ end
135
+
136
+ def use_database!(conn, db_name)
137
+ quoted = "`#{db_name.to_s.gsub('`', '``')}`"
138
+ conn.execute("USE #{quoted}")
139
+ end
140
+
141
+ def restore_database(conn, previous_db, suppress_errors: false)
142
+ return unless present_value?(previous_db)
143
+
144
+ use_database!(conn, previous_db)
145
+ conn.clear_cache! if conn.respond_to?(:clear_cache!)
146
+ rescue StandardError
147
+ raise unless suppress_errors
148
+ end
149
+ end
150
+
151
+ register('mysql2', Mysql.instance)
152
+ register('trilogy', Mysql.instance)
153
+ end
154
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module DatabaseAdapters
7
+ class Postgresql < Base
8
+ FORBIDDEN_SCHEMA_PREFIXES = %w[pg_].freeze
9
+ FORBIDDEN_SCHEMAS = %w[information_schema].freeze
10
+
11
+ def supports_namespaces?
12
+ true
13
+ end
14
+
15
+ def apply_read_only_config(merged_config)
16
+ updated = merged_config.dup
17
+ vars = updated['variables'].is_a?(Hash) ? updated['variables'].transform_keys(&:to_s) : {}
18
+ vars['default_transaction_read_only'] = 'on'
19
+ updated['variables'] = vars
20
+ updated
21
+ end
22
+
23
+ # Fails CLOSED: returns true (non-idle / unsafe) whenever PG transaction status cannot be verified.
24
+ def non_idle_transaction?(conn)
25
+ return true unless defined?(PG::PQTRANS_IDLE)
26
+ return true unless conn.respond_to?(:raw_connection)
27
+
28
+ raw = conn.raw_connection
29
+ return true unless raw.respond_to?(:transaction_status)
30
+
31
+ raw.transaction_status != PG::PQTRANS_IDLE
32
+ rescue StandardError
33
+ true
34
+ end
35
+
36
+ def switch_namespace(conn, tenant, persistent_schemas: [], shard_config: nil) # rubocop:disable Lint/UnusedMethodArgument
37
+ previous_path = conn.respond_to?(:schema_search_path) ? conn.schema_search_path : nil
38
+ target_schemas = ([tenant] + Array(persistent_schemas).map(&:to_s)).uniq
39
+ switched = false
40
+ in_flight = false
41
+
42
+ formatted = format_search_path(target_schemas)
43
+ apply_search_path!(conn, formatted)
44
+ switched = true
45
+
46
+ begin
47
+ conn.clear_cache! if conn.respond_to?(:clear_cache!)
48
+ yield
49
+ rescue Exception # rubocop:disable Lint/RescueException
50
+ in_flight = true
51
+ raise
52
+ end
53
+ ensure
54
+ restore_search_path(conn, previous_path, suppress_errors: in_flight) if switched
55
+ end
56
+
57
+ def current_namespace(conn, live: false)
58
+ return conn.select_value('SHOW search_path').to_s if live && conn.respond_to?(:select_value)
59
+ return conn.schema_search_path.to_s if conn.respond_to?(:schema_search_path)
60
+
61
+ nil
62
+ rescue StandardError
63
+ nil
64
+ end
65
+
66
+ def namespace_matches?(conn, expected_tenant, persistent_schemas: [], live: false)
67
+ actual_path = current_namespace(conn, live: live)
68
+ return false if actual_path.nil?
69
+
70
+ expected = ([expected_tenant] + Array(persistent_schemas).map(&:to_s)).uniq
71
+ search_path_matches?(actual_path, expected)
72
+ end
73
+
74
+ def verify_and_restore_namespace!(conn, expected_tenant:, persistent_schemas: [], live: false)
75
+ actual_path = current_namespace(conn, live: live)
76
+ expected = ([expected_tenant] + Array(persistent_schemas).map(&:to_s)).uniq
77
+
78
+ return if actual_path && search_path_matches?(actual_path, expected)
79
+
80
+ apply_search_path!(conn, format_search_path(expected))
81
+ end
82
+
83
+ def verify_and_reset_default_namespace!(conn, default_namespace:, persistent_schemas: [], live: false)
84
+ expected = ([default_namespace || 'public'] + Array(persistent_schemas).map(&:to_s)).uniq
85
+ actual_path = current_namespace(conn, live: live)
86
+
87
+ raise TaintedConnectionError, 'unverifiable search_path' if actual_path.nil?
88
+ return if search_path_matches?(actual_path, expected)
89
+
90
+ apply_search_path!(conn, format_search_path(expected))
91
+ end
92
+
93
+ def default_namespace_for(_shard_cfg, configured_default: nil)
94
+ configured_default || 'public'
95
+ end
96
+
97
+ def format_search_path(schemas)
98
+ schemas.map do |s|
99
+ str = s.to_s.strip
100
+ unless valid_tenant_identifier?(str)
101
+ raise InvalidTenantError, "Invalid schema identifier in search_path: #{s.inspect}"
102
+ end
103
+
104
+ %("#{str.gsub('"', '""')}")
105
+ end.join(', ')
106
+ end
107
+
108
+ def search_path_matches?(current_path, expected_schemas)
109
+ tokens = current_path.to_s.split(',').map { |s| s.delete('"').strip }.reject(&:empty?)
110
+ return true if tokens == expected_schemas
111
+
112
+ # PostgreSQL's built-in default "$user, public" is acceptable ONLY when the
113
+ # expected default is strictly ["public"] with no persistent schemas.
114
+ expected_schemas == ['public'] && tokens == ['$user', 'public']
115
+ end
116
+
117
+ protected
118
+
119
+ def default_adapter_name
120
+ 'postgresql'
121
+ end
122
+
123
+ def forbidden_tenant?(str)
124
+ downcased = str.downcase
125
+ FORBIDDEN_SCHEMAS.include?(downcased) || FORBIDDEN_SCHEMA_PREFIXES.any? { |p| downcased.start_with?(p) }
126
+ end
127
+
128
+ private
129
+
130
+ # Rails 8's PostgreSQLAdapter#schema_search_path= skips executing SET search_path
131
+ # when its cached @schema_search_path already equals the target string. Force raw
132
+ # SET search_path in that case so out-of-band SQL SET search_path mutations are overwritten.
133
+ def apply_search_path!(conn, formatted)
134
+ cached = conn.respond_to?(:schema_search_path) ? conn.schema_search_path : nil
135
+ if cached == formatted && conn.respond_to?(:execute)
136
+ conn.execute("SET search_path TO #{formatted}")
137
+ else
138
+ conn.schema_search_path = formatted
139
+ end
140
+ end
141
+
142
+ def restore_search_path(conn, previous_path, suppress_errors: false)
143
+ return unless previous_path && conn.respond_to?(:schema_search_path=)
144
+
145
+ apply_search_path!(conn, previous_path)
146
+ conn.clear_cache! if conn.respond_to?(:clear_cache!)
147
+ rescue StandardError
148
+ # Do not mask an in-flight exception (e.g. Timeout::Error / PG::InFailedSqlTransaction);
149
+ # ConnectionSanitizer will perform live verification and discard the connection fail-closed.
150
+ raise unless suppress_errors
151
+ end
152
+ end
153
+
154
+ register('postgresql', Postgresql.instance)
155
+ register('postgis', Postgresql.instance)
156
+ end
157
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module DatabaseAdapters
7
+ class Sqlite < Base
8
+ VALID_SQLITE_TENANT_REGEX = /\A[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}\z/
9
+
10
+ def validate_config!(shard_key, shard_cfg)
11
+ has_url = present_value?(shard_cfg['url'] || shard_cfg[:url])
12
+ has_db = present_value?(shard_cfg['database'] || shard_cfg[:database])
13
+ return if has_url || has_db
14
+
15
+ raise ArgumentError, "SQLite shard '#{shard_key}' must explicitly configure 'database' or 'url'"
16
+ end
17
+
18
+ def default_pool_options(configuration)
19
+ {
20
+ 'adapter' => 'sqlite3',
21
+ 'pool' => configuration.default_pool_size,
22
+ 'checkout_timeout' => configuration.checkout_timeout,
23
+ 'reaping_frequency' => configuration.reaping_frequency
24
+ }
25
+ end
26
+
27
+ def prepare_connection(conn, read_only: true)
28
+ return unless conn.respond_to?(:execute)
29
+
30
+ conn.execute("PRAGMA query_only = #{read_only ? 'ON' : 'OFF'}")
31
+ end
32
+
33
+ def per_tenant_pool?(shard_cfg)
34
+ return false unless shard_cfg.is_a?(Hash)
35
+
36
+ db = (shard_cfg['database'] || shard_cfg[:database]).to_s
37
+ url = (shard_cfg['url'] || shard_cfg[:url]).to_s
38
+ db.include?('%{tenant}') || url.include?('%{tenant}')
39
+ end
40
+
41
+ def resolve_shard_config(shard_cfg, tenant: nil)
42
+ return shard_cfg unless per_tenant_pool?(shard_cfg)
43
+
44
+ tenant_str = tenant.to_s.strip
45
+ unless present_value?(tenant_str) && valid_tenant_identifier?(tenant_str)
46
+ raise InvalidTenantError,
47
+ "SQLite per-tenant database template requires a valid tenant name (got #{tenant.inspect})"
48
+ end
49
+
50
+ updated = shard_cfg.transform_keys(&:to_s)
51
+ updated['database'] = updated['database'].gsub('%{tenant}') { tenant_str } if updated['database']
52
+ updated['url'] = updated['url'].gsub('%{tenant}') { tenant_str } if updated['url']
53
+ updated
54
+ end
55
+
56
+ # SQLite isolates tenants via per-tenant database files (%{tenant} template).
57
+ # Fail closed if a tenant is requested on a shared non-template SQLite shard.
58
+ def switch_namespace(_conn, _tenant, persistent_schemas: [], shard_config: nil) # rubocop:disable Lint/UnusedMethodArgument
59
+ unless per_tenant_pool?(shard_config)
60
+ raise ConfigurationError,
61
+ "SQLite shard does not use a '%{tenant}' database template; " \
62
+ 'use SchemaShard.on_shard for shard-only routing or configure a per-tenant template'
63
+ end
64
+
65
+ yield
66
+ end
67
+
68
+ def default_namespace_for(_shard_cfg, configured_default: nil) # rubocop:disable Lint/UnusedMethodArgument
69
+ nil
70
+ end
71
+
72
+ def non_idle_transaction?(conn)
73
+ return true if conn.respond_to?(:open_transactions) && conn.open_transactions.to_i.positive?
74
+
75
+ if conn.respond_to?(:raw_connection)
76
+ raw = conn.raw_connection
77
+ return true if raw.nil?
78
+ return true if raw.respond_to?(:transaction_active?) && raw.transaction_active?
79
+ end
80
+
81
+ false
82
+ rescue StandardError
83
+ true
84
+ end
85
+
86
+ protected
87
+
88
+ def default_adapter_name
89
+ 'sqlite3'
90
+ end
91
+
92
+ def valid_tenant_identifier?(str)
93
+ VALID_SQLITE_TENANT_REGEX.match?(str)
94
+ end
95
+ end
96
+
97
+ register('sqlite3', Sqlite.instance)
98
+ end
99
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ class Error < StandardError; end
5
+ class ConfigurationError < Error; end
6
+ class InvalidTenantError < ArgumentError; end
7
+ class TaintedConnectionError < Error; end
8
+ class PoolLimitExceededError < Error; end
9
+ end
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ module ExecutionContext
5
+ CONFIG_KEY = :schema_shard_config
6
+ LABEL_KEY = :schema_shard_label
7
+ TENANT_KEY = :schema_shard_tenant
8
+ CONNECTION_KEY = :schema_shard_connection
9
+ POOL_KEY = :schema_shard_pool
10
+ READ_ONLY_KEY = :schema_shard_read_only
11
+ POOL_FRAMES_KEY = :schema_shard_pool_frames
12
+ DEPTH_KEY = :schema_shard_depth
13
+
14
+ module_function
15
+
16
+ def state
17
+ if defined?(ActiveSupport::IsolatedExecutionState)
18
+ ActiveSupport::IsolatedExecutionState
19
+ else
20
+ Thread.current
21
+ end
22
+ end
23
+
24
+ def current_config = state[CONFIG_KEY]
25
+ def current_shard_label = state[LABEL_KEY]
26
+ def current_tenant = state[TENANT_KEY]
27
+ def active_connection = state[CONNECTION_KEY]
28
+ def active_pool = state[POOL_KEY]
29
+ def read_only? = state[READ_ONLY_KEY]
30
+
31
+ def in_active_block?
32
+ state[DEPTH_KEY].to_i.positive?
33
+ end
34
+
35
+ def pool_active_on_thread?(pool)
36
+ frames = state[POOL_FRAMES_KEY]
37
+ return false unless frames
38
+
39
+ stack = frames[pool]
40
+ !stack.nil? && !stack.empty?
41
+ end
42
+
43
+ def enclosing_pool_frame(pool)
44
+ frames = state[POOL_FRAMES_KEY]
45
+ return nil unless frames
46
+
47
+ stack = frames[pool]
48
+ stack&.last
49
+ end
50
+
51
+ def push_pool_frame(pool, tenant:, tenant_switched:, tenant_adapter: nil)
52
+ st = state
53
+ frames = (st[POOL_FRAMES_KEY] ||= {}.compare_by_identity)
54
+ stack = (frames[pool] ||= [])
55
+ frame = {
56
+ tenant: tenant, tenant_switched: tenant_switched,
57
+ tenant_adapter: tenant_adapter, dirty: false, tainted: false
58
+ }
59
+ stack.push(frame)
60
+ frame
61
+ end
62
+
63
+ def pop_pool_frame(pool)
64
+ frames = state[POOL_FRAMES_KEY]
65
+ return nil unless frames
66
+
67
+ stack = frames[pool]
68
+ return nil unless stack
69
+
70
+ frame = stack.pop
71
+ frames.delete(pool) if stack.empty?
72
+ frame
73
+ end
74
+
75
+ def mark_pool_frames_dirty(pool)
76
+ frames = state[POOL_FRAMES_KEY]
77
+ return unless frames
78
+
79
+ frames[pool]&.each { |f| f[:dirty] = true }
80
+ end
81
+
82
+ def mark_pool_frames_tainted(pool)
83
+ frames = state[POOL_FRAMES_KEY]
84
+ return unless frames
85
+
86
+ frames[pool]&.each { |f| f[:tainted] = true }
87
+ end
88
+
89
+ def active_pool_tainted?
90
+ pool = state[POOL_KEY]
91
+ return false unless pool
92
+
93
+ enclosing_pool_frame(pool)&.dig(:tainted) == true
94
+ end
95
+
96
+ def with_context(shard_key:, config:, tenant:, read_only:)
97
+ st = state
98
+ prev_config = st[CONFIG_KEY]
99
+ prev_label = st[LABEL_KEY]
100
+ prev_tenant = st[TENANT_KEY]
101
+ prev_read_only = st[READ_ONLY_KEY]
102
+ prev_depth = st[DEPTH_KEY].to_i
103
+
104
+ st[CONFIG_KEY] = config
105
+ st[LABEL_KEY] = shard_key
106
+ st[TENANT_KEY] = tenant
107
+ st[READ_ONLY_KEY] = read_only
108
+ st[DEPTH_KEY] = prev_depth + 1
109
+
110
+ yield
111
+ ensure
112
+ st[CONFIG_KEY] = prev_config
113
+ st[LABEL_KEY] = prev_label
114
+ st[TENANT_KEY] = prev_tenant
115
+ st[READ_ONLY_KEY] = prev_read_only
116
+ st[DEPTH_KEY] = prev_depth
117
+ end
118
+
119
+ def with_connection(conn, pool)
120
+ st = state
121
+ prev_conn = st[CONNECTION_KEY]
122
+ prev_pool = st[POOL_KEY]
123
+
124
+ st[CONNECTION_KEY] = conn
125
+ st[POOL_KEY] = pool
126
+ yield
127
+ ensure
128
+ st[CONNECTION_KEY] = prev_conn
129
+ st[POOL_KEY] = prev_pool
130
+ end
131
+
132
+ def clear!(logger: nil)
133
+ st = state
134
+ logger&.warn '[SchemaShard] clear_thread_locals! called while a shard connection was active' if st[CONNECTION_KEY]
135
+
136
+ st[CONFIG_KEY] = nil
137
+ st[LABEL_KEY] = nil
138
+ st[TENANT_KEY] = nil
139
+ st[CONNECTION_KEY] = nil
140
+ st[POOL_KEY] = nil
141
+ st[READ_ONLY_KEY] = nil
142
+ st[POOL_FRAMES_KEY] = nil
143
+ st[DEPTH_KEY] = 0
144
+ end
145
+ end
146
+ end