2020-05-24 23:13:21 +05:30
# frozen_string_literal: true
module Limitable
extend ActiveSupport :: Concern
2020-06-23 00:09:42 +05:30
GLOBAL_SCOPE = :limitable_global_scope
2020-05-24 23:13:21 +05:30
included do
class_attribute :limit_scope
2021-09-04 01:27:46 +05:30
class_attribute :limit_relation
2020-05-24 23:13:21 +05:30
class_attribute :limit_name
2021-06-08 01:23:25 +05:30
class_attribute :limit_feature_flag
2021-10-27 15:23:28 +05:30
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-05-24 23:13:21 +05:30
self . limit_name = self . name . demodulize . tableize
validate :validate_plan_limit_not_exceeded , on : :create
end
2022-07-23 23:45:48 +05:30
def exceeds_limits?
limits , relation = fetch_plan_limit_data
limits & . exceeded? ( limit_name , relation )
end
2020-05-24 23:13:21 +05:30
private
def validate_plan_limit_not_exceeded
2022-07-23 23:45:48 +05:30
limits , relation = fetch_plan_limit_data
check_plan_limit_not_exceeded ( limits , relation )
end
def fetch_plan_limit_data
2020-06-23 00:09:42 +05:30
if GLOBAL_SCOPE == limit_scope
2022-07-23 23:45:48 +05:30
global_plan_limits
2020-06-23 00:09:42 +05:30
else
2022-07-23 23:45:48 +05:30
scoped_plan_limits
2020-06-23 00:09:42 +05:30
end
end
2022-07-23 23:45:48 +05:30
def scoped_plan_limits
2020-05-24 23:13:21 +05:30
scope_relation = self . public_send ( limit_scope ) # rubocop:disable GitlabSecurity/PublicSend
return unless scope_relation
2022-07-16 23:28:13 +05:30
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-05-24 23:13:21 +05:30
2021-09-04 01:27:46 +05:30
relation = limit_relation ? self . public_send ( limit_relation ) : self . class . where ( limit_scope = > scope_relation ) # rubocop:disable GitlabSecurity/PublicSend
2020-06-23 00:09:42 +05:30
limits = scope_relation . actual_limits
2020-05-24 23:13:21 +05:30
2022-07-23 23:45:48 +05:30
[ limits , relation ]
2020-06-23 00:09:42 +05:30
end
2022-07-23 23:45:48 +05:30
def global_plan_limits
2020-06-23 00:09:42 +05:30
relation = self . class . all
limits = Plan . default . actual_limits
2022-07-23 23:45:48 +05:30
[ limits , relation ]
2020-06-23 00:09:42 +05:30
end
def check_plan_limit_not_exceeded ( limits , relation )
2022-07-23 23:45:48 +05:30
return unless limits & . exceeded? ( limit_name , relation )
2020-06-23 00:09:42 +05:30
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-05-24 23:13:21 +05:30
end
end