Class: Labkit::RateLimit::Rule

Inherits:
Data
  • Object
show all
Defined in:
lib/labkit/rate_limit/rule.rb

Overview

Rule is a value object describing a single rate limit rule. name - stable identifier used in Redis keys and log entries match - hash of identifier key/value pairs that must all match for the rule to apply; empty hash matches any identifier limit - request threshold, at least 1; may be a callable (resolved per check) period - window in seconds, at least 1; may be a callable (resolved per check) action - :limit (enforce; the result blocks when the rule is over its limit, which also terminates evaluation), :log (count and log only, never blocks and never terminates), or :skip (bypass: permit and terminate evaluation on match without counting; performs no Redis operation, so limit, period, characteristics, and count_distinct are inert) ban_for - optional ban duration in seconds. On crossing the limit the rule writes a separate ban key that outlives the counter window, and stops counting while it holds. action still decides who is blocked: :limit enforces the ban, :log records what it would have done. Rejected on :skip. May be a callable, resolved per check. characteristics - identifier keys used to build the compound Redis counter key count_distinct - optional Symbol naming an identifier key. When set, the rule counts the number of distinct values seen for that key within the (characteristics-bucketed) period, backed by a Redis SET. When nil (default), the rule counts the number of calls, backed by INCR. The named key must not overlap characteristics. admit_counted_values - optional Boolean, only valid with count_distinct and rejected on :skip. When true, the rule counts only the values it admits: a value already in the window's set is allowed even when the set is full, and a new value is added only while the count is below the limit, so a value this rule refuses is never counted. Rules count a request up to the one that blocks it, so put admitting rules after counter rules. Default false; nil means not set.

source - :code for a rule built in Ruby (default), :file for a rule loaded from a rate limit config document. A :file rule compiles its patterns with RE2 and checks its name in every environment, because an operator wrote it.

name must be a lowercase alphanumeric-and-underscore string of at most 64 characters. It is used as the middle segment of every Redis counter key for this rule, so changing a rule's name mid-window abandons its in-flight counters.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, limit:, period:, characteristics:, match: {}, action: :limit, count_distinct: nil, ban_for: nil, admit_counted_values: false, source: :code) ⇒ Rule

rubocop:disable Metrics/ParameterLists -- one keyword per Rule field; the public API grows by keywords with defaults

Raises:

  • (ArgumentError)


130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/labkit/rate_limit/rule.rb', line 130

def initialize( # rubocop:disable Metrics/ParameterLists -- one keyword per Rule field; the public API grows by keywords with defaults
  name:, limit:, period:, characteristics:,
  match: {}, action: :limit, count_distinct: nil, ban_for: nil, admit_counted_values: false, source: :code
)
  raise ArgumentError, "source must be :code or :file, got #{source.inspect}" unless %i[code file].include?(source)

  name_str = self.class.validate_name!(name, source)

  action_sym = action.to_sym
  raise ArgumentError, "Invalid action: #{action.inspect}. Must be one of: #{KNOWN_ACTIONS.inspect}" unless KNOWN_ACTIONS.include?(action_sym)

  characteristics_arr = Array(characteristics).map(&:to_sym).freeze
  count_distinct_sym = self.class.normalize_count_distinct(count_distinct, characteristics_arr)

  super(
    name: name_str.freeze,
    match: match.transform_keys(&:to_sym).transform_values { |v| Matcher.build(v, source == :file ? :re2 : :ruby) }.freeze,
    limit: self.class.normalize_numeric(:limit, limit, action_sym),
    period: self.class.normalize_numeric(:period, period, action_sym),
    action: action_sym,
    characteristics: characteristics_arr,
    count_distinct: count_distinct_sym,
    ban_for: self.class.normalize_ban_for(ban_for, action_sym, count_distinct_sym),
    admit_counted_values: self.class.normalize_admit_counted_values(admit_counted_values, action_sym, count_distinct_sym),
    source: source
  )
end

Instance Attribute Details

#action ⇒ Object (readonly)

Returns the value of attribute action

Returns:

  • (Object) —

    the current value of action



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def action
  @action
end

#admit_counted_values ⇒ Object (readonly)

Returns the value of attribute admit_counted_values

Returns:

  • (Object) —

    the current value of admit_counted_values



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def admit_counted_values
  @admit_counted_values
end

#ban_for ⇒ Object (readonly)

Returns the value of attribute ban_for

Returns:

  • (Object) —

    the current value of ban_for



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def ban_for
  @ban_for
end

#characteristics ⇒ Object (readonly)

Returns the value of attribute characteristics

Returns:

  • (Object) —

    the current value of characteristics



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def characteristics
  @characteristics
end

#count_distinct ⇒ Object (readonly)

Returns the value of attribute count_distinct

Returns:

  • (Object) —

    the current value of count_distinct



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def count_distinct
  @count_distinct
end

#limit ⇒ Object (readonly)

Returns the value of attribute limit

Returns:

  • (Object) —

    the current value of limit



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def limit
  @limit
end

#match ⇒ Object (readonly)

Returns the value of attribute match

Returns:

  • (Object) —

    the current value of match



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def match
  @match
end

#name ⇒ Object (readonly)

Returns the value of attribute name

Returns:

  • (Object) —

    the current value of name



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def name
  @name
end

#period ⇒ Object (readonly)

Returns the value of attribute period

Returns:

  • (Object) —

    the current value of period



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def period
  @period
end

#source ⇒ Object (readonly)

Returns the value of attribute source

Returns:

  • (Object) —

    the current value of source



52
53
54
# File 'lib/labkit/rate_limit/rule.rb', line 52

def source
  @source
end

Class Method Details

.normalize_admit_counted_values(value, action_sym, count_distinct_sym) ⇒ Object

Admission only means something for a SET-backed rule, where a value can already be counted. A counter has no members to admit, and a :skip rule counts nothing.

Raises:

  • (ArgumentError)


89
90
91
92
93
94
95
96
97
# File 'lib/labkit/rate_limit/rule.rb', line 89

def self.normalize_admit_counted_values(value, action_sym, count_distinct_sym)
  # nil means "not set", like count_distinct and ban_for.
  value = false if value.nil?
  raise ArgumentError, "admit_counted_values must be true, false, or nil, got #{value.inspect}" unless [true, false].include?(value)
  raise ArgumentError, "admit_counted_values is not valid on a :skip rule" if value && action_sym == :skip
  raise ArgumentError, "admit_counted_values requires count_distinct" if value && count_distinct_sym.nil?

  value
end

.normalize_ban_for(value, action_sym, count_distinct_sym) ⇒ Object

ban_for changes the accounting; action still decides who gets blocked. A :skip rule counts nothing, so it has no limit to cross and no ban to write.

Raises:

  • (ArgumentError)


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/labkit/rate_limit/rule.rb', line 58

def self.normalize_ban_for(value, action_sym, count_distinct_sym)
  return nil if value.nil?

  raise ArgumentError, "ban_for is not valid on a :skip rule" if action_sym == :skip

  # The ban path counts with INCRBYFLOAT, so a SET-backed rule would
  # silently count calls instead of distinct values.
  raise ArgumentError, "ban_for cannot be combined with count_distinct #{count_distinct_sym.inspect}" if count_distinct_sym

  return value if value.respond_to?(:call)
  # Whole seconds: the ban is written with SET EX, and anything under a
  # second truncates to 0, which Redis rejects.
  return value if value.is_a?(Numeric) && value >= 1

  raise ArgumentError, "ban_for must be a Numeric of at least 1 second or a callable, got #{value.inspect}"
end

.normalize_count_distinct(value, characteristics_arr) ⇒ Object

Raises:

  • (ArgumentError)


99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/labkit/rate_limit/rule.rb', line 99

def self.normalize_count_distinct(value, characteristics_arr)
  sym =
    case value
    when nil    then nil
    when Symbol then value
    when String then value.to_sym
    else
      raise ArgumentError, "count_distinct must be a Symbol, String, or nil, got #{value.class}"
    end

  raise ArgumentError, "count_distinct #{sym.inspect} must not overlap characteristics #{characteristics_arr.inspect}" if sym && characteristics_arr.include?(sym)

  sym
end

.normalize_numeric(field, value, action_sym) ⇒ Object

A static limit under 1 blocks every request, and a period under a second reaches EXPIRE as 0, deleting the counter on every write. A :skip rule counts nothing, and a callable may still resolve to 0 to mean "deny all" ("deny new values" on an admit_counted_values rule).

Raises:

  • (ArgumentError)


79
80
81
82
83
84
# File 'lib/labkit/rate_limit/rule.rb', line 79

def self.normalize_numeric(field, value, action_sym)
  return value if action_sym == :skip || value.respond_to?(:call)
  return value if value.is_a?(Numeric) && value >= 1

  raise ArgumentError, "#{field} must be a Numeric of at least 1 or a callable, got #{value.inspect}"
end

.validate_name!(name, source) ⇒ Object

A :file rule is checked in every environment: an operator wrote it, and Limiter's production fallback of sanitising the name would silently change the counter key of a rule the operator can see in the file.

Raises:

  • (ArgumentError)


117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/labkit/rate_limit/rule.rb', line 117

def self.validate_name!(name, source)
  raise ArgumentError, "name must be a String or Symbol, got #{name.class}" unless name.is_a?(String) || name.is_a?(Symbol)

  name_str = name.to_s
  raise ArgumentError, "name must not be empty" if name_str.empty?
  return name_str unless source == :file || Labkit.dev_or_test?

  raise ArgumentError, "Invalid rule name: #{name.inspect}. Must match /\\A[a-z0-9_]+\\z/" unless RULE_NAME_PATTERN.match?(name_str)
  raise ArgumentError, "Rule name too long: #{name.inspect}. Maximum 64 characters" if name_str.length > RULE_NAME_MAX_LENGTH

  name_str
end