Class: Switchman::Shard
- Inherits:
-
UnshardedRecord
- Object
- ActiveRecord::Base
- UnshardedRecord
- Switchman::Shard
- Defined in:
- lib/switchman/shard.rb
Constant Summary collapse
- IDS_PER_SHARD =
ten trillion possible ids per shard. yup.
10_000_000_000_000- NIL_NIL_ID =
takes an id-ish, and returns a local id and the shard it's local to. [nil, nil] if it can't be interpreted. [id, nil] if it's already a local ID. [nil, nil] if it's a well formed id, but the shard it refers to does not exist
[nil, nil].freeze
Class Method Summary collapse
- ._load(str) ⇒ Object
- .activate(shards) ⇒ Object
- .activate!(shards) ⇒ Object
- .active_shards ⇒ Object
- .clear_cache ⇒ Object
- .current(klass = ::ActiveRecord::Base) ⇒ Object
- .default(reload: false, with_fallback: false) ⇒ Object
-
.drop_database(name) ⇒ Object
Drops a specific database/schema from the currently active connection.
-
.global_id_for(any_id, source_shard = nil) ⇒ Object
takes an id-ish, and returns an integral global id.
-
.integral_id_for(any_id) ⇒ Object
converts an AR object, integral id, string id, or string short-global-id to a integral id.
- .local_id_for(any_id) ⇒ Object
- .lookup(id) ⇒ Object
- .partition_by_shard(array, partition_proc = nil) ⇒ Object
- .preload_cache(shard_ids: nil) ⇒ Object
-
.relative_id_for(any_id, source_shard, target_shard) ⇒ Object
takes an id-ish, and returns an integral id relative to target_shard.
- .shard_for(any_id, source_shard = nil) ⇒ Object
- .sharded_models ⇒ Object
-
.short_id_for(any_id) ⇒ Object
takes an id-ish, and returns a shortened global string id if global, and itself if local.
-
.signed_id_operation(input_id) ⇒ Object
it's tedious to hold onto this same kind of sign state and transform the result in multiple places, so here we can operate on the absolute value in a provided block and trust the sign will stay as provided.
-
.with_each_shard(*args, parallel: false, exception: :raise, output: :simple) ⇒ Object
Parameters.
Instance Method Summary collapse
-
#_dump(_depth) ⇒ Object
custom serialization, since shard is self-referential.
- #activate(*classes) ⇒ Object
-
#activate!(*classes) ⇒ Object
for use from console ONLY.
- #database_server ⇒ Object
- #database_server=(database_server) ⇒ Object
- #description ⇒ Object
- #destroy ⇒ Object
- #drop_database ⇒ Object
-
#global_id_for(local_id) ⇒ Object
takes an id local to this shard, and returns a global id.
- #name ⇒ Object
- #name=(name) ⇒ Object
- #original_id ⇒ Object
- #original_id_value ⇒ Object
- #primary? ⇒ Boolean
-
#shard ⇒ Object
Shards are always on the default shard.
Class Method Details
._load(str) ⇒ Object
626 627 628 |
# File 'lib/switchman/shard.rb', line 626 def self._load(str) lookup(str.to_i) end |
.activate(shards) ⇒ Object
99 100 101 102 103 104 105 106 |
# File 'lib/switchman/shard.rb', line 99 def activate(shards) activated_classes = activate!(shards) yield ensure activated_classes&.each do |klass| klass.connected_to_stack.pop end end |
.activate!(shards) ⇒ Object
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/switchman/shard.rb', line 108 def activate!(shards) activated_classes = nil shards.each do |klass, shard| next if klass == UnshardedRecord next unless klass.current_shard != shard.database_server.id.to_sym || klass.current_switchman_shard != shard (activated_classes ||= []) << klass klass.connected_to_stack << { shard: shard.database_server.id.to_sym, klasses: [klass], switchman_shard: shard } end activated_classes end |
.active_shards ⇒ Object
124 125 126 127 128 |
# File 'lib/switchman/shard.rb', line 124 def active_shards sharded_models.filter_map do |klass| [klass, current(klass)] end.to_h end |
.clear_cache ⇒ Object
160 161 162 |
# File 'lib/switchman/shard.rb', line 160 def clear_cache cached_shards.clear end |
.current(klass = ::ActiveRecord::Base) ⇒ Object
94 95 96 97 |
# File 'lib/switchman/shard.rb', line 94 def current(klass = ::ActiveRecord::Base) klass ||= ::ActiveRecord::Base klass.current_switchman_shard end |
.default(reload: false, with_fallback: false) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/switchman/shard.rb', line 62 def default(reload: false, with_fallback: false) if !@default || reload # Have to create a dummy object so that several key methods still work # (it's easier to do this in one place here, and just assume that sharding # is up and running everywhere else). This includes for looking up the # default shard itself. This also needs to be a local so that this method # can be re-entrant default = DefaultShard.instance # if we already have a default shard in place, and the caller wants # to use it as a fallback, use that instead of the dummy instance default = @default if with_fallback && @default # the first time we need a dummy dummy for re-entrancy to avoid looping on ourselves @default ||= default # Now find the actual record, if it exists @default = find_default_shard(default) # make sure this is not erroneously cached if @default.database_server.instance_variable_defined?(:@primary_shard) @default.database_server.remove_instance_variable(:@primary_shard) end # and finally, check for cached references to the default shard on the existing connection sharded_models.each do |klass| klass.connection.shard = @default if klass.connected? && klass.connection.shard.default? end end @default end |
.drop_database(name) ⇒ Object
Drops a specific database/schema from the currently active connection
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 |
# File 'lib/switchman/shard.rb', line 646 def self.drop_database(name) sharding_config = Switchman.config || {} drop_statement = sharding_config["postgresql"]&.[](:drop_statement) drop_statement ||= sharding_config[:drop_statement] drop_statement = Array(drop_statement).map { |statement| statement.gsub("%{name}", name) } if drop_statement ::GuardRail.activate(:deploy) do # Shut up, Postgres! conn = ::ActiveRecord::Base.connection old_proc = conn.raw_connection.set_notice_processor {} begin drop_statement ||= "DROP SCHEMA #{name} CASCADE" Array(drop_statement).each do |stmt| ::ActiveRecord::Base.connection.execute(stmt) end ensure conn.raw_connection.set_notice_processor(&old_proc) if old_proc end end end |
.global_id_for(any_id, source_shard = nil) ⇒ Object
takes an id-ish, and returns an integral global id. returns nil if it can't be interpreted
421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/switchman/shard.rb', line 421 def global_id_for(any_id, source_shard = nil) id = integral_id_for(any_id) return any_id unless id signed_id_operation(id) do |abs_id| if abs_id >= IDS_PER_SHARD abs_id else source_shard ||= Shard.current source_shard.global_id_for(abs_id) end end end |
.integral_id_for(any_id) ⇒ Object
converts an AR object, integral id, string id, or string short-global-id to a integral id. nil if it can't be interpreted
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
# File 'lib/switchman/shard.rb', line 348 def integral_id_for(any_id) case any_id when ::Arel::Nodes::Casted any_id = any_id.value when ::Arel::Nodes::BindParam any_id = any_id.value.value_before_type_cast end case any_id when ::ActiveRecord::Base any_id.id when /\A(\d+)~(-?\d+)\Z/ local_id = $2.to_i signed_id_operation(local_id) do |id| return nil if id > IDS_PER_SHARD ($1.to_i * IDS_PER_SHARD) + id end when Integer, /\A-?\d+\Z/ any_id.to_i end end |
.local_id_for(any_id) ⇒ Object
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/switchman/shard.rb', line 376 def local_id_for(any_id) id = integral_id_for(any_id) return NIL_NIL_ID unless id return_shard = nil local_id = signed_id_operation(id) do |abs_id| if abs_id < IDS_PER_SHARD abs_id elsif (return_shard = lookup(abs_id / IDS_PER_SHARD)) abs_id % IDS_PER_SHARD else return NIL_NIL_ID end end [local_id, return_shard] end |
.lookup(id) ⇒ Object
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/switchman/shard.rb', line 130 def lookup(id) id_i = id.to_i return current if id_i == current.id || id == "self" return default if id_i == default.id || id.nil? || id == "default" id = id_i raise ArgumentError if id.zero? unless cached_shards.key?(id) cached_shards[id] = Shard.default.activate do find_cached(["shard", id]) { find_by(id:) } end end cached_shards[id] end |
.partition_by_shard(array, partition_proc = nil) ⇒ Object
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/switchman/shard.rb', line 300 def partition_by_shard(array, partition_proc = nil) shard_arrays = {} array.each do |object| partition_object = partition_proc ? partition_proc.call(object) : object case partition_object when Shard shard = partition_object when ::ActiveRecord::Base if partition_object.respond_to?(:associated_shards) partition_object.associated_shards.each do |a_shard| shard_arrays[a_shard] ||= [] shard_arrays[a_shard] << object end next else shard = partition_object.shard end when Integer, /\A\d+\Z/, /\A(\d+)~(\d+)\Z/ local_id, shard = Shard.local_id_for(partition_object) local_id ||= partition_object object = local_id unless partition_proc end shard ||= Shard.current shard_arrays[shard] ||= [] shard_arrays[shard] << object end # TODO: use with_each_shard (or vice versa) to get # connection management and parallelism benefits shard_arrays.inject([]) do |results, (shard, objects)| results.concat(shard.activate { Array.wrap(yield objects) }) end end |
.preload_cache(shard_ids: nil) ⇒ Object
146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/switchman/shard.rb', line 146 def preload_cache(shard_ids: nil) if shard_ids missing = shard_ids - cached_shards.keys return if missing.empty? found = where(id: missing).select(&:database_server).index_by(&:id) # exclude shards w/o database servers missing.each { |id| found[id] = nil unless found.key?(id) } # cache nonexistence of shards cached_shards.reverse_merge!(found) else cached_shards.reverse_merge!(active_shards.values.index_by(&:id)) cached_shards.reverse_merge!(all.select(&:database_server).index_by(&:id)) end end |
.relative_id_for(any_id, source_shard, target_shard) ⇒ Object
takes an id-ish, and returns an integral id relative to target_shard. returns nil if it can't be interpreted, or the integral version of the id if it refers to a shard that does not exist
397 398 399 400 401 402 403 404 405 406 |
# File 'lib/switchman/shard.rb', line 397 def relative_id_for(any_id, source_shard, target_shard) integral_id = integral_id_for(any_id) local_id, shard = local_id_for(integral_id) return integral_id unless local_id shard ||= source_shard return local_id if shard == target_shard shard.global_id_for(local_id) end |
.shard_for(any_id, source_shard = nil) ⇒ Object
435 436 437 438 439 440 |
# File 'lib/switchman/shard.rb', line 435 def shard_for(any_id, source_shard = nil) return any_id.shard if any_id.is_a?(::ActiveRecord::Base) _, shard = local_id_for(any_id) shard || source_shard || Shard.current end |
.sharded_models ⇒ Object
58 59 60 |
# File 'lib/switchman/shard.rb', line 58 def sharded_models @sharded_models ||= [::ActiveRecord::Base, UnshardedRecord].freeze end |
.short_id_for(any_id) ⇒ Object
takes an id-ish, and returns a shortened global string id if global, and itself if local. returns any_id itself if it can't be interpreted
411 412 413 414 415 416 417 |
# File 'lib/switchman/shard.rb', line 411 def short_id_for(any_id) local_id, shard = local_id_for(any_id) return any_id unless local_id return local_id unless shard "#{shard.id}~#{local_id}" end |
.signed_id_operation(input_id) ⇒ Object
it's tedious to hold onto this same kind of sign state and transform the result in multiple places, so here we can operate on the absolute value in a provided block and trust the sign will stay as provided. This assumes no consumer will return a nil value from the block.
340 341 342 343 344 |
# File 'lib/switchman/shard.rb', line 340 def signed_id_operation(input_id) sign = input_id.negative? ? -1 : 1 output = yield input_id.abs output * sign end |
.with_each_shard(*args, parallel: false, exception: :raise, output: :simple) ⇒ Object
Parameters
shards- an array or relation of Shards to iterate overclasses- an array of classes to activate parallel: - true/false to execute in parallel, or an integer of how many sub-processes. Note that parallel invocation currently uses forking. exception: - :ignore, :raise, :defer (wait until the end and raise the first error), or a proc output: - :simple, :decorated (with database_server_id:shard_name), custom lambda transformer
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/switchman/shard.rb', line 174 def with_each_shard(*args, parallel: false, exception: :raise, output: :simple) raise ArgumentError, "wrong number of arguments (#{args.length} for 0...2)" if args.length > 2 return Array.wrap(yield) unless default.is_a?(Shard) if args.length == 1 if Array === args.first && args.first.first.is_a?(Class) classes = args.first else scope = args.first end else scope, classes = args end output = if output == :decorated ->(arg) { "#{Shard.current.description}: #{arg}" } elsif output == :simple nil else output end parallel = [Environment.cpu_count || 2, 2].min if parallel == true parallel = 0 if parallel == false || parallel.nil? scope ||= Shard.all if ::ActiveRecord::Relation === scope && scope.order_values.empty? scope = scope.order(::Arel.sql("database_server_id IS NOT NULL, database_server_id, id")) end if parallel > 1 if ::ActiveRecord::Relation === scope # still need a post-uniq, cause the default database server could be NULL or Rails.env in the db database_servers = scope.reorder("database_server_id").select(:database_server_id).distinct .filter_map(&:database_server).uniq # nothing to do return if database_servers.none? scopes = database_servers.index_with do |server| scope.merge(server.shards) end else scopes = scope.group_by(&:database_server) end # clear connections prior to forking (no more queries will be executed in the parent, # and we want them gone so that we don't accidentally use them post-fork doing something # silly like dealloc'ing prepared statements) ::ActiveRecord::Base.connection_handler.clear_all_connections!(:all) parent_process_name = sanitized_process_title ret = ::Parallel.map(scopes, in_processes: (scopes.length > 1) ? parallel : 0) do |server, subscope| name = server.id last_description = name begin max_length = 128 - name.length - 3 short_parent_name = parent_process_name[0..max_length] if max_length >= 0 new_title = [short_parent_name, name].join(" ") Process.setproctitle(new_title) Switchman.config[:on_fork_proc]&.call with_each_shard(subscope, classes, exception:, output: output || :decorated) do last_description = Shard.current.description Parallel::ResultWrapper.new(yield) end rescue => e logger.error e. Parallel::QuietExceptionWrapper.new(last_description, ::Parallel::ExceptionWrapper.new(e)) end end.flatten errors = ret.grep(Parallel::QuietExceptionWrapper) unless errors.empty? raise errors.first.exception if errors.length == 1 errors_desc = errors.map(&:name).sort.join(", ") raise Errors::ParallelShardExecError, "The following database server(s) did not finish processing cleanly: #{errors_desc}", cause: errors.first.exception end return ret.map(&:result) end classes ||= [] result = [] ex = nil old_stdout = $stdout old_stderr = $stderr scope.each do |shard| # shard references a database server that isn't configured in this environment next unless shard.database_server shard.activate(*classes) do if output $stdout = Parallel::TransformingIO.new(output, $stdout) $stderr = Parallel::TransformingIO.new(output, $stderr) end result.concat Array.wrap(yield) rescue case exception when :ignore # ignore when :defer ex ||= $! when Proc exception.call # when :raise else raise end ensure $stdout = old_stdout $stderr = old_stderr end end raise ex if ex result end |
Instance Method Details
#_dump(_depth) ⇒ Object
custom serialization, since shard is self-referential
622 623 624 |
# File 'lib/switchman/shard.rb', line 622 def _dump(_depth) id.to_s end |
#activate(*classes) ⇒ Object
609 610 611 612 |
# File 'lib/switchman/shard.rb', line 609 def activate(*classes, &) shards = hashify_classes(classes) Shard.activate(shards, &) end |
#activate!(*classes) ⇒ Object
for use from console ONLY
615 616 617 618 619 |
# File 'lib/switchman/shard.rb', line 615 def activate!(*classes) shards = hashify_classes(classes) Shard.activate!(shards) nil end |
#database_server ⇒ Object
579 580 581 |
# File 'lib/switchman/shard.rb', line 579 def database_server @database_server ||= DatabaseServer.find(database_server_id) end |
#database_server=(database_server) ⇒ Object
583 584 585 586 |
# File 'lib/switchman/shard.rb', line 583 def database_server=(database_server) self.database_server_id = database_server.id @database_server = database_server end |
#description ⇒ Object
592 593 594 |
# File 'lib/switchman/shard.rb', line 592 def description [database_server.id, name].compact.join(":") end |
#destroy ⇒ Object
679 680 681 682 683 |
# File 'lib/switchman/shard.rb', line 679 def destroy raise("Cannot destroy the default shard") if default? super end |
#drop_database ⇒ Object
630 631 632 633 634 635 636 637 638 639 640 641 |
# File 'lib/switchman/shard.rb', line 630 def drop_database raise "Cannot drop the database of the default shard" if default? return unless read_attribute(:name) begin activate do self.class.drop_database(name) end rescue ::ActiveRecord::StatementInvalid => e logger.error "Drop failed: #{e}" end end |
#global_id_for(local_id) ⇒ Object
takes an id local to this shard, and returns a global id
668 669 670 671 672 673 674 |
# File 'lib/switchman/shard.rb', line 668 def global_id_for(local_id) return nil unless local_id self.class.signed_id_operation(local_id) do |abs_id| abs_id + (id * IDS_PER_SHARD) end end |
#name ⇒ Object
565 566 567 568 569 570 571 572 |
# File 'lib/switchman/shard.rb', line 565 def name unless instance_variable_defined?(:@name) # protect against re-entrancy @name = nil @name = read_attribute(:name) || default_name end @name end |
#name=(name) ⇒ Object
574 575 576 577 |
# File 'lib/switchman/shard.rb', line 574 def name=(name) write_attribute(:name, @name = name) remove_instance_variable(:@name) if name.nil? end |
#original_id ⇒ Object
601 602 603 |
# File 'lib/switchman/shard.rb', line 601 def original_id id end |
#original_id_value ⇒ Object
605 606 607 |
# File 'lib/switchman/shard.rb', line 605 def original_id_value id end |
#primary? ⇒ Boolean
588 589 590 |
# File 'lib/switchman/shard.rb', line 588 def primary? self == database_server.primary_shard end |