2020-04-15 11:09:17 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module API
|
|
|
|
module Helpers
|
2021-12-10 10:10:24 -05:00
|
|
|
# == RateLimiter
|
|
|
|
#
|
|
|
|
# Helper that checks if the rate limit for a given endpoint is throttled by calling the
|
2022-01-21 10:13:54 -05:00
|
|
|
# Gitlab::ApplicationRateLimiter module. If the action is throttled for the current user, the request
|
2021-12-10 10:10:24 -05:00
|
|
|
# will be logged and an error message will be rendered with a Too Many Requests response status.
|
|
|
|
# See app/controllers/concerns/check_rate_limit.rb for Rails controllers version
|
2020-04-15 11:09:17 -04:00
|
|
|
module RateLimiter
|
2021-12-10 10:10:24 -05:00
|
|
|
def check_rate_limit!(key, scope:, **options)
|
2021-12-20 10:12:25 -05:00
|
|
|
return if bypass_header_set?
|
2021-12-10 10:10:24 -05:00
|
|
|
return unless rate_limiter.throttled?(key, scope: scope, **options)
|
2020-04-15 11:09:17 -04:00
|
|
|
|
2021-12-10 10:10:24 -05:00
|
|
|
rate_limiter.log_request(request, "#{key}_request_limit".to_sym, current_user)
|
2020-04-15 11:09:17 -04:00
|
|
|
|
2021-12-10 10:10:24 -05:00
|
|
|
return yield if block_given?
|
2020-04-15 11:09:17 -04:00
|
|
|
|
|
|
|
render_api_error!({ error: _('This endpoint has been requested too many times. Try again later.') }, 429)
|
|
|
|
end
|
|
|
|
|
2021-12-10 10:10:24 -05:00
|
|
|
private
|
|
|
|
|
|
|
|
def rate_limiter
|
|
|
|
::Gitlab::ApplicationRateLimiter
|
2020-04-15 11:09:17 -04:00
|
|
|
end
|
2021-12-20 10:12:25 -05:00
|
|
|
|
|
|
|
def bypass_header_set?
|
|
|
|
::Gitlab::Throttle.bypass_header.present? && request.get_header(Gitlab::Throttle.bypass_header) == '1'
|
|
|
|
end
|
2020-04-15 11:09:17 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|