Class: ResilientReads::Middleware

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

Overview

Rack middleware that automatically wraps GET/HEAD requests in a distribute_reads context. Respects the “read your own write” delay: after a mutating request, subsequent reads stay on primary for primary_delay seconds.

Constant Summary collapse

WRITE_METHODS =
%w[POST PUT PATCH DELETE].freeze
"_resilient_reads_last_write".freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
# File 'lib/resilient_reads/middleware.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/resilient_reads/middleware.rb', line 14

def call(env)
  return @app.call(env) unless ResilientReads.config.by_default
  return @app.call(env) if ResilientReads.replica_pool.empty?

  request = Rack::Request.new(env)

  if write_request?(request)
    status, headers, body = @app.call(env)
    set_last_write_cookie(headers)
    [ status, headers, body ]
  elsif recent_write?(request)
    # Within the primary_delay window — skip replica routing.
    @app.call(env)
  else
    ResilientReads.run { @app.call(env) }
  end
end