debian-mirror-gitlab/lib/api/helpers/rate_limiter.rb

35 lines
1.1 KiB
Ruby
Raw Normal View History

2020-04-22 19:07:51 +05:30
# frozen_string_literal: true
module API
module Helpers
2022-01-26 12:08:38 +05:30
# == RateLimiter
#
# Helper that checks if the rate limit for a given endpoint is throttled by calling the
2022-04-04 11:22:00 +05:30
# Gitlab::ApplicationRateLimiter module. If the action is throttled for the current user, the request
2022-01-26 12:08:38 +05:30
# 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-22 19:07:51 +05:30
module RateLimiter
2022-01-26 12:08:38 +05:30
def check_rate_limit!(key, scope:, **options)
2022-03-02 08:16:31 +05:30
return if bypass_header_set?
2022-01-26 12:08:38 +05:30
return unless rate_limiter.throttled?(key, scope: scope, **options)
2020-04-22 19:07:51 +05:30
2022-01-26 12:08:38 +05:30
rate_limiter.log_request(request, "#{key}_request_limit".to_sym, current_user)
2020-04-22 19:07:51 +05:30
2022-01-26 12:08:38 +05:30
return yield if block_given?
2020-04-22 19:07:51 +05:30
render_api_error!({ error: _('This endpoint has been requested too many times. Try again later.') }, 429)
end
2022-01-26 12:08:38 +05:30
private
def rate_limiter
::Gitlab::ApplicationRateLimiter
2020-04-22 19:07:51 +05:30
end
2022-03-02 08:16:31 +05:30
def bypass_header_set?
::Gitlab::Throttle.bypass_header.present? && request.get_header(Gitlab::Throttle.bypass_header) == '1'
end
2020-04-22 19:07:51 +05:30
end
end
end