2018-11-19 21:01:13 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-03-09 21:28:20 -05:00
|
|
|
# rubocop:disable Style/ClassVars
|
|
|
|
|
|
|
|
# This is inspired by http://www.salsify.com/blog/engineering/tearing-capybara-ajax-tests
|
|
|
|
# Rack middleware that keeps track of the number of active requests and can block new requests.
|
|
|
|
module Gitlab
|
|
|
|
module Testing
|
|
|
|
class RequestBlockerMiddleware
|
|
|
|
@@num_active_requests = Concurrent::AtomicFixnum.new(0)
|
|
|
|
@@block_requests = Concurrent::AtomicBoolean.new(false)
|
2017-10-24 09:25:04 -04:00
|
|
|
@@slow_requests = Concurrent::AtomicBoolean.new(false)
|
2017-03-09 21:28:20 -05:00
|
|
|
|
|
|
|
# Returns the number of requests the server is currently processing.
|
|
|
|
def self.num_active_requests
|
|
|
|
@@num_active_requests.value
|
|
|
|
end
|
|
|
|
|
|
|
|
# Prevents the server from accepting new requests. Any new requests will return an HTTP
|
|
|
|
# 503 status.
|
|
|
|
def self.block_requests!
|
|
|
|
@@block_requests.value = true
|
|
|
|
end
|
|
|
|
|
2017-10-24 09:25:04 -04:00
|
|
|
# Slows down incoming requests (useful for race conditions).
|
|
|
|
def self.slow_requests!
|
|
|
|
@@slow_requests.value = true
|
|
|
|
end
|
|
|
|
|
2017-03-09 21:28:20 -05:00
|
|
|
# Allows the server to accept requests again.
|
|
|
|
def self.allow_requests!
|
|
|
|
@@block_requests.value = false
|
2017-10-24 09:25:04 -04:00
|
|
|
@@slow_requests.value = false
|
2017-03-09 21:28:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
increment_active_requests
|
2018-01-11 11:34:01 -05:00
|
|
|
|
2017-03-09 21:28:20 -05:00
|
|
|
if block_requests?
|
|
|
|
block_request(env)
|
|
|
|
else
|
2017-10-24 09:25:04 -04:00
|
|
|
sleep 0.2 if slow_requests?
|
2017-03-09 21:28:20 -05:00
|
|
|
@app.call(env)
|
|
|
|
end
|
2018-01-11 11:34:01 -05:00
|
|
|
|
2017-03-09 21:28:20 -05:00
|
|
|
ensure
|
|
|
|
decrement_active_requests
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def block_requests?
|
|
|
|
@@block_requests.true?
|
|
|
|
end
|
|
|
|
|
2017-10-24 09:25:04 -04:00
|
|
|
def slow_requests?
|
|
|
|
@@slow_requests.true?
|
|
|
|
end
|
|
|
|
|
2017-03-09 21:28:20 -05:00
|
|
|
def block_request(env)
|
|
|
|
[503, {}, []]
|
|
|
|
end
|
|
|
|
|
|
|
|
def increment_active_requests
|
|
|
|
@@num_active_requests.increment
|
|
|
|
end
|
|
|
|
|
|
|
|
def decrement_active_requests
|
|
|
|
@@num_active_requests.decrement
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|