Class: Labkit::RateLimit::Limiter

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

Overview

Limiter is the primary public API for rate limiting. Instantiate once per call site (e.g. at application boot), then call #check(identifier) on every request. The internal Evaluator is reused across calls, avoiding per-request object allocation.

Examples:

limiter = Labkit::RateLimit::Limiter.new(
  name: "rack_request",
  rules: [Labkit::RateLimit::Rule.new(name: "api_user", limit: 100, period: 60, characteristics: [:user])]
)
result = limiter.check({ user: 42, ip: "1.2.3.4" })
render_429 if result.action == :block

Constant Summary collapse

NAME_PATTERN =
/\A[a-z0-9_]+\z/
CONTRACT =

Where in rules: the contract's default rules go.

:contract

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, rules:, guard_rules: [], redis: nil, logger: nil, document: RateLimit.config.rule_document) ⇒ Limiter

Returns a new instance of Limiter.

Parameters:

  • rules (Array<Rule, :contract>) —

    the host's default rules, in order. The CONTRACT marker places the document's default rules for this limiter; without a marker they follow the code defaults.

  • guard_rules (Array<Rule>) (defaults to: []) —

    rules built in code that run before every other tier and that no override can replace.

  • document (Config::Document, nil) (defaults to: RateLimit.config.rule_document) —

    the loaded contract and overrides; defaults to the configured one. With none, only the code rules run and the CONTRACT marker places nothing.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/labkit/rate_limit/limiter.rb', line 37

def initialize(name:, rules:, guard_rules: [], redis: nil, logger: nil, document: RateLimit.config.rule_document)
  @logger = logger || RateLimit.config.logger || Labkit::Logging::JsonLogger.new($stdout)
  @name = validate_name!(name)
  effective = effective_rules(validate_entries!(guard_rules, "guard_rules"), validate_entries!(rules, "rules", marker: true), document)
  @rules = prepare_rules(effective).freeze

  @evaluator = Evaluator.new(
    name: @name,
    rules: @rules,
    redis: redis || RateLimit.config.redis,
    logger: @logger
  )
end

Instance Attribute Details

#rules ⇒ Object (readonly)

The rules the evaluator runs, in order: guard rules, the document's override rules for this limiter, then the default list, with names sanitised and duplicates dropped as prepare_rules does.



27
28
29
# File 'lib/labkit/rate_limit/limiter.rb', line 27

def rules
  @rules
end

Instance Method Details

#check(identifier, cost: 1, rule_context: nil) ⇒ Result

Parameters:

  • identifier (Identifier, Hash) —

    caller attributes for this request

  • cost (Numeric) (defaults to: 1) —

    amount to add to the counter. Defaults to 1 (count-mode). Pass a non-1 Numeric for cost-mode counters such as resource-usage limits; passing 0 reads the counter without writing. count_distinct rules ignore cost, so a cost of 0 still adds the value (or admits it, on an admit_counted_values rule). A negative cost would credit quota back, so the check fails open and logs instead of counting.

  • rule_context (Hash, nil) (defaults to: nil) —

    optional per-request context passed to one-arity callables on +limit+/+period+. Lets rules resolve dynamic configuration (e.g. per-namespace settings) without rebuilding the Rule or doing out-of-band DB queries. Zero-arity callables ignore it. The key contract is owned by the rule's callable, not validated here: if the rule reads ctx and the caller passes ctx, the callable's fallback branch fires silently. Keep the rule definition and the call site colocated.

Returns:



68
69
70
71
# File 'lib/labkit/rate_limit/limiter.rb', line 68

def check(identifier, cost: 1, rule_context: nil)
  id = to_identifier(identifier)
  @evaluator.check(id, cost: cost, rule_context: rule_context)
end

#clear(identifier) ⇒ Integer

Discards this limiter's state for one identifier: every rule's counter, and any ban written by a rule carrying ban_for.

For call sites where a later success should wipe earlier failures, such as an authentication ban cleared by a valid login. Counters otherwise only expire with their window; this is the only way to end one early.

Scoped to this limiter and identifier, not to a single rule: a caller clearing after a success knows who succeeded, not which rules matched.

Parameters:

  • identifier (Identifier, Hash) —

    caller attributes

Returns:

  • (Integer) —

    number of Redis keys removed; on a Redis error, those removed before it failed



108
109
110
# File 'lib/labkit/rate_limit/limiter.rb', line 108

def clear(identifier)
  @evaluator.clear(to_identifier(identifier))
end

#peek(identifier, rule_context: nil) ⇒ Result

Read the current rate-limit state without incrementing the counter. Mirrors #check except the underlying counter is not mutated and the TTL is not extended. Useful for "have we already throttled this caller?" checks where the caller has another path that does the actual increment (typical pattern: peek to gate a side-effect, then call #check on the path that should count).

When the underlying Redis key does not exist yet, the result reports count=0, exceeded=false, and remaining=resolved_limit; matched? is still true because the rule applied. The exception is an admit_counted_values rule whose limit resolves to 0 or less, which refuses every new value and so reports exceeded. On Redis error the result fails open identically to #check.

Parameters:

  • identifier (Identifier, Hash) —

    caller attributes for this request

  • rule_context (Hash, nil) (defaults to: nil) —

    see #check

Returns:



90
91
92
93
# File 'lib/labkit/rate_limit/limiter.rb', line 90

def peek(identifier, rule_context: nil)
  id = to_identifier(identifier)
  @evaluator.peek(id, rule_context: rule_context)
end