Class: ActiveRecord::Middleware::ShardSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/middleware/shard_selector.rb

Overview

The ShardSelector Middleware provides a framework for automatically swapping shards. Rails provides a basic framework to determine which shard to switch to and allows for applications to write custom strategies for swapping if needed.

The ShardSelector takes a set of options (currently only lock is supported) that can be used by the middleware to alter behavior. lock is true by default and will prohibit the request from switching shards once inside the block. If lock is false, then shard swapping will be allowed. For tenant based sharding, lock should always be true to prevent application code from mistakenly switching between tenants.

Options can be set in the config:

config.active_record.shard_selector = { lock: true }

Applications must also provide the code for the resolver as it depends on application specific models. An example resolver would look like this:

config.active_record.shard_resolver = ->(request) {
  subdomain = request.subdomain
  tenant = Tenant.find_by_subdomain!(subdomain)
  tenant.shard
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, resolver, options = {}) ⇒ ShardSelector

Returns a new instance of ShardSelector.



30
31
32
33
34
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/middleware/shard_selector.rb', line 30

def initialize(app, resolver, options = {})
  @app = app
  @resolver = resolver
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



36
37
38
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/middleware/shard_selector.rb', line 36

def options
  @options
end

#resolverObject (readonly)

Returns the value of attribute resolver.



36
37
38
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/middleware/shard_selector.rb', line 36

def resolver
  @resolver
end

Instance Method Details

#call(env) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/middleware/shard_selector.rb', line 38

def call(env)
  request = ActionDispatch::Request.new(env)

  shard = selected_shard(request)

  set_shard(shard) do
    @app.call(env)
  end
end