Class: RailsFailover::ActiveRecord::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_failover/active_record/middleware.rb

Constant Summary collapse

CURRENT_ROLE_HEADER =
"rails_failover.role"
WRITING_ROLE_HEADER =
"rails_failover.writing_role"

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



42
43
44
# File 'lib/rails_failover/active_record/middleware.rb', line 42

def initialize(app)
  @app = app
end

Class Attribute Details

.force_reading_role_callbackObject

Returns the value of attribute force_reading_role_callback.



36
37
38
# File 'lib/rails_failover/active_record/middleware.rb', line 36

def force_reading_role_callback
  @force_reading_role_callback
end

Instance Method Details

#call(env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rails_failover/active_record/middleware.rb', line 46

def call(env)
  current_role = ::ActiveRecord::Base.current_role || RailsFailover::ActiveRecord.writing_role
  is_writing_role = current_role.to_s.end_with?(RailsFailover::ActiveRecord.writing_role.to_s)
  writing_role = resolve_writing_role(current_role, is_writing_role)

  role =
    if self.class.force_reading_role_callback&.call(env) ||
         Handler.instance.primary_down?(writing_role)
      reading_role = resolve_reading_role(current_role, is_writing_role)
      ensure_reading_connection_established!(
        writing_role: writing_role,
        reading_role: reading_role,
      )
      reading_role
    else
      writing_role
    end

  ::ActiveRecord::Base.connected_to(role: role) do
    env[CURRENT_ROLE_HEADER] = role
    env[WRITING_ROLE_HEADER] = writing_role
    @app.call(env)
  end
rescue => e
  Interceptor.verify_primary(e, writing_role) if writing_role
  raise e
end