2020-04-22 11:09:27 -04:00
# frozen_string_literal: true
module Limitable
extend ActiveSupport :: Concern
2020-05-27 14:08:14 -04:00
GLOBAL_SCOPE = :limitable_global_scope
2020-04-22 11:09:27 -04:00
included do
class_attribute :limit_scope
2021-06-02 11:09:59 -04:00
class_attribute :limit_relation
2020-04-22 11:09:27 -04:00
class_attribute :limit_name
2021-05-05 17:09:59 -04:00
class_attribute :limit_feature_flag
2021-07-30 20:10:15 -04:00
class_attribute :limit_feature_flag_for_override # Allows selectively disabling by actor (as per https://docs.gitlab.com/ee/development/feature_flags/#selectively-disable-by-actor)
2020-04-22 11:09:27 -04:00
self . limit_name = self . name . demodulize . tableize
validate :validate_plan_limit_not_exceeded , on : :create
end
2022-06-08 08:08:46 -04:00
def exceeds_limits?
limits , relation = fetch_plan_limit_data
limits & . exceeded? ( limit_name , relation )
end
2020-04-22 11:09:27 -04:00
private
def validate_plan_limit_not_exceeded
2022-06-08 08:08:46 -04:00
limits , relation = fetch_plan_limit_data
check_plan_limit_not_exceeded ( limits , relation )
end
def fetch_plan_limit_data
2020-05-27 14:08:14 -04:00
if GLOBAL_SCOPE == limit_scope
2022-06-08 08:08:46 -04:00
global_plan_limits
2020-05-27 14:08:14 -04:00
else
2022-06-08 08:08:46 -04:00
scoped_plan_limits
2020-05-27 14:08:14 -04:00
end
end
2022-06-08 08:08:46 -04:00
def scoped_plan_limits
2020-04-22 11:09:27 -04:00
scope_relation = self . public_send ( limit_scope ) # rubocop:disable GitlabSecurity/PublicSend
return unless scope_relation
2022-05-06 11:09:03 -04:00
return if limit_feature_flag && :: Feature . disabled? ( limit_feature_flag , scope_relation )
return if limit_feature_flag_for_override && :: Feature . enabled? ( limit_feature_flag_for_override , scope_relation )
2020-04-22 11:09:27 -04:00
2021-06-02 11:09:59 -04:00
relation = limit_relation ? self . public_send ( limit_relation ) : self . class . where ( limit_scope = > scope_relation ) # rubocop:disable GitlabSecurity/PublicSend
2020-05-27 14:08:14 -04:00
limits = scope_relation . actual_limits
2020-04-22 11:09:27 -04:00
2022-06-08 08:08:46 -04:00
[ limits , relation ]
2020-05-27 14:08:14 -04:00
end
2022-06-08 08:08:46 -04:00
def global_plan_limits
2020-05-27 14:08:14 -04:00
relation = self . class . all
limits = Plan . default . actual_limits
2022-06-08 08:08:46 -04:00
[ limits , relation ]
2020-05-27 14:08:14 -04:00
end
def check_plan_limit_not_exceeded ( limits , relation )
2022-06-08 08:08:46 -04:00
return unless limits & . exceeded? ( limit_name , relation )
2020-05-27 14:08:14 -04:00
errors . add ( :base , _ ( " Maximum number of %{name} (%{count}) exceeded " ) %
{ name : limit_name . humanize ( capitalize : false ) , count : limits . public_send ( limit_name ) } ) # rubocop:disable GitlabSecurity/PublicSend
2020-04-22 11:09:27 -04:00
end
end