rate_guard 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +44 -0
  3. data/LICENSE +21 -0
  4. data/README.md +237 -0
  5. data/lib/rate_guard/admission.rb +13 -0
  6. data/lib/rate_guard/algorithms/fixed_window_counter.rb +83 -0
  7. data/lib/rate_guard/algorithms/leaky_bucket_meter.rb +93 -0
  8. data/lib/rate_guard/algorithms/leaky_bucket_queue.rb +93 -0
  9. data/lib/rate_guard/algorithms/redis_sliding_window_counter.rb +137 -0
  10. data/lib/rate_guard/algorithms/sliding_window_counter.lua +60 -0
  11. data/lib/rate_guard/algorithms/sliding_window_counter.rb +148 -0
  12. data/lib/rate_guard/algorithms/sliding_window_log.rb +105 -0
  13. data/lib/rate_guard/algorithms/token_bucket.rb +93 -0
  14. data/lib/rate_guard/bypass.rb +39 -0
  15. data/lib/rate_guard/clock.rb +20 -0
  16. data/lib/rate_guard/configuration.rb +77 -0
  17. data/lib/rate_guard/errors.rb +9 -0
  18. data/lib/rate_guard/identifiers/api_key.rb +36 -0
  19. data/lib/rate_guard/identifiers/first_of.rb +28 -0
  20. data/lib/rate_guard/identifiers/global.rb +14 -0
  21. data/lib/rate_guard/identifiers/ip.rb +19 -0
  22. data/lib/rate_guard/identifiers/user.rb +34 -0
  23. data/lib/rate_guard/identifiers.rb +17 -0
  24. data/lib/rate_guard/json_log_formatter.rb +29 -0
  25. data/lib/rate_guard/metrics.rb +49 -0
  26. data/lib/rate_guard/middleware/client_ip.rb +40 -0
  27. data/lib/rate_guard/middleware.rb +147 -0
  28. data/lib/rate_guard/policy.rb +129 -0
  29. data/lib/rate_guard/policy_set.rb +59 -0
  30. data/lib/rate_guard/redis_error_reporter.rb +51 -0
  31. data/lib/rate_guard/registry.rb +109 -0
  32. data/lib/rate_guard/request.rb +7 -0
  33. data/lib/rate_guard/result.rb +17 -0
  34. data/lib/rate_guard/tiers.rb +25 -0
  35. data/lib/rate_guard/utils/numeric_utils.rb +22 -0
  36. data/lib/rate_guard/validators/configuration_validator.rb +28 -0
  37. data/lib/rate_guard/validators/cost_validator.rb +36 -0
  38. data/lib/rate_guard/version.rb +5 -0
  39. data/lib/rate_guard.rb +84 -0
  40. metadata +105 -0
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'errors'
4
+ require_relative 'algorithms/token_bucket'
5
+ require_relative 'algorithms/leaky_bucket_meter'
6
+ require_relative 'algorithms/leaky_bucket_queue'
7
+ require_relative 'algorithms/fixed_window_counter'
8
+ require_relative 'algorithms/sliding_window_log'
9
+ require_relative 'algorithms/sliding_window_counter'
10
+
11
+ module RateGuard
12
+ # Maps algorithm names (:token_bucket, ...) to how they are built.
13
+ module Registry
14
+ # kind :immediate - #acquire, allow or reject now
15
+ # :queue - #enqueue / #dequeue, run later
16
+ # redis true if it can store its state in Redis
17
+ Entry = Data.define(:name, :kind, :redis, :builder)
18
+
19
+ KINDS = %i[immediate queue].freeze
20
+
21
+ @entries = {}
22
+
23
+ class << self
24
+ # Adds an algorithm. The block gets the Configuration and returns a limiter.
25
+ def register(name, kind: :immediate, redis: false, &builder)
26
+ raise ArgumentError, "kind must be one of #{KINDS.inspect}" unless KINDS.include?(kind)
27
+ raise ArgumentError, 'a builder block is required' if builder.nil?
28
+ raise ConfigurationError, "algorithm #{name.inspect} is already registered" if @entries.key?(name)
29
+
30
+ @entries[name] = Entry.new(name:, kind:, redis:, builder:)
31
+ end
32
+
33
+ def unregister(name)
34
+ @entries.delete(name)
35
+ end
36
+
37
+ def registered?(name)
38
+ @entries.key?(name)
39
+ end
40
+
41
+ def names
42
+ @entries.keys
43
+ end
44
+
45
+ def fetch(name)
46
+ @entries.fetch(name) do
47
+ raise ConfigurationError, "unknown algorithm #{name.inspect} (available: #{names.map(&:inspect).join(', ')})"
48
+ end
49
+ end
50
+
51
+ # Builds a new limiter from a configuration.
52
+ def build(config)
53
+ entry = fetch(config.algorithm)
54
+ if config.redis && !entry.redis
55
+ supported = @entries.values.select(&:redis).map { |e| e.name.inspect }.join(', ')
56
+ raise ConfigurationError,
57
+ "#{entry.name.inspect} keeps its state in memory; Redis storage is only supported by #{supported}"
58
+ end
59
+
60
+ entry.builder.call(config)
61
+ end
62
+
63
+ private
64
+
65
+ # Passes clock only when configured; otherwise the algorithm's default.
66
+ def clock_option(config)
67
+ config.clock.nil? ? {} : { clock: config.clock }
68
+ end
69
+ end
70
+
71
+ # Translates "limit per window" into each algorithm's settings.
72
+ register(:token_bucket) do |config|
73
+ Algorithms::TokenBucket.new(capacity: config.limit, refill_rate: config.limit.fdiv(config.window),
74
+ **clock_option(config))
75
+ end
76
+
77
+ register(:leaky_bucket_meter) do |config|
78
+ Algorithms::LeakyBucketMeter.new(capacity: config.limit, leak_rate: config.limit.fdiv(config.window),
79
+ **clock_option(config))
80
+ end
81
+
82
+ register(:leaky_bucket_queue, kind: :queue) do |config|
83
+ Algorithms::LeakyBucketQueue.new(capacity: config.limit, leak_rate: config.limit.fdiv(config.window),
84
+ **clock_option(config))
85
+ end
86
+
87
+ register(:fixed_window) do |config|
88
+ Algorithms::FixedWindowCounter.new(limit: config.limit, window: config.window, **clock_option(config))
89
+ end
90
+
91
+ register(:sliding_window_log) do |config|
92
+ Algorithms::SlidingWindowLog.new(limit: config.limit, window: config.window, **clock_option(config))
93
+ end
94
+
95
+ # In memory, or in Redis when config.redis is set.
96
+ # The Redis code loads only when used, so the redis gem is optional.
97
+ register(:sliding_window_counter, redis: true) do |config|
98
+ if config.redis
99
+ require_relative 'algorithms/redis_sliding_window_counter'
100
+ Algorithms::RedisSlidingWindowCounter.new(
101
+ redis: config.redis, limit: config.limit, window: config.window, namespace: config.namespace,
102
+ failure_policy: config.redis_failure_policy, on_error: config.on_redis_error, **clock_option(config)
103
+ )
104
+ else
105
+ Algorithms::SlidingWindowCounter.new(limit: config.limit, window: config.window, **clock_option(config))
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RateGuard
4
+ # A request as policies see it: upper-case method, normalized path,
5
+ # and the raw env for your own callables.
6
+ Request = Data.define(:http_method, :path, :env)
7
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RateGuard
4
+ # Result of asking a limiter to allow one request.
5
+ #
6
+ # allowed - true if the request may go ahead
7
+ # remaining - requests left afterwards
8
+ # retry_after - seconds until a retry can succeed (0.0 if allowed)
9
+ # reset_after - seconds until the limit is fully restored (nil if unknown)
10
+ Result = Data.define(:allowed, :remaining, :retry_after, :reset_after) do
11
+ def initialize(allowed:, remaining:, retry_after:, reset_after: nil)
12
+ super(allowed:, remaining:, retry_after:, reset_after:)
13
+ end
14
+
15
+ def allowed? = allowed
16
+ end
17
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RateGuard
4
+ # Different limits per plan. Picks a limiter for each request:
5
+ #
6
+ # Tiers.new(free: free_limiter, premium: premium_limiter) { |key, env| plan_of(key) }
7
+ #
8
+ # An unknown plan uses the first tier, never no limit.
9
+ class Tiers
10
+ def initialize(limiters, &resolve)
11
+ raise ArgumentError, 'Tiers needs at least one tier' if limiters.empty?
12
+ raise ArgumentError, 'Tiers needs a block that picks the tier' if resolve.nil?
13
+
14
+ @limiters = limiters.freeze
15
+ @default = limiters.values.first
16
+ @resolve = resolve
17
+ end
18
+
19
+ def select(key, env)
20
+ @limiters.fetch(@resolve.call(key, env)) { @default }
21
+ end
22
+
23
+ def limiters = @limiters.values
24
+ end
25
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RateGuard
4
+ module Utils
5
+ # Number checks shared by the algorithms.
6
+ module NumericUtils
7
+ module_function
8
+
9
+ def positive_number?(value)
10
+ value.is_a?(Numeric) &&
11
+ value.real? &&
12
+ value.finite? &&
13
+ value.positive?
14
+ end
15
+
16
+ def positive_integer?(value)
17
+ value.is_a?(Integer) &&
18
+ value.positive?
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../utils/numeric_utils'
4
+
5
+ module RateGuard
6
+ # Validation shared by the algorithms.
7
+ module Validators
8
+ # Checks algorithm settings: types and ranges.
9
+ module ConfigurationValidator
10
+ module_function
11
+
12
+ def validate!(**attributes)
13
+ attributes.each do |name, (value, type)|
14
+ valid = case type
15
+ when :integer
16
+ value.is_a?(Integer) && value.positive?
17
+ when :number
18
+ Utils::NumericUtils.positive_number?(value)
19
+ else
20
+ raise ArgumentError, "Unknown validation type: #{type}"
21
+ end
22
+
23
+ raise ArgumentError, "#{name} must be a positive #{type}" unless valid
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../utils/numeric_utils'
4
+
5
+ module RateGuard
6
+ module Validators
7
+ # Checks a request's cost: a positive number within the limit.
8
+ # reserve: units that must stay free; cost + reserve must fit too.
9
+ module CostValidator
10
+ module_function
11
+
12
+ def validate!(cost:, maximum:, type:, maximum_name: 'limit', reserve: 0)
13
+ valid = case type
14
+ when :number
15
+ Utils::NumericUtils.positive_number?(cost)
16
+ when :integer
17
+ Utils::NumericUtils.positive_integer?(cost)
18
+ else
19
+ raise ArgumentError, "Unknown cost type: #{type}"
20
+ end
21
+
22
+ raise ArgumentError, "cost must be a positive #{type}" unless valid
23
+ raise ArgumentError, "cost #{cost} exceeds #{maximum_name} #{maximum}" if cost > maximum
24
+
25
+ validate_reserve!(reserve, cost, maximum, maximum_name)
26
+ end
27
+
28
+ def validate_reserve!(reserve, cost, maximum, maximum_name)
29
+ raise ArgumentError, 'reserve must be a non-negative integer' unless reserve.is_a?(Integer) && reserve >= 0
30
+ return unless cost + reserve > maximum
31
+
32
+ raise ArgumentError, "cost #{cost} plus reserve #{reserve} exceeds #{maximum_name} #{maximum}"
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RateGuard
4
+ VERSION = '0.1.0'
5
+ end
data/lib/rate_guard.rb ADDED
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'rate_guard/version'
4
+ require_relative 'rate_guard/errors'
5
+ require_relative 'rate_guard/clock'
6
+ require_relative 'rate_guard/result'
7
+ require_relative 'rate_guard/admission'
8
+ require_relative 'rate_guard/registry'
9
+ require_relative 'rate_guard/configuration'
10
+ require_relative 'rate_guard/identifiers'
11
+ require_relative 'rate_guard/request'
12
+ require_relative 'rate_guard/tiers'
13
+ require_relative 'rate_guard/policy'
14
+ require_relative 'rate_guard/policy_set'
15
+ require_relative 'rate_guard/bypass'
16
+ require_relative 'rate_guard/metrics'
17
+ require_relative 'rate_guard/json_log_formatter'
18
+ require_relative 'rate_guard/redis_error_reporter'
19
+
20
+ # Entry point: configure the library and build limiters.
21
+ module RateGuard
22
+ class << self
23
+ # Sets the global configuration. Kept only if valid, then frozen.
24
+ #
25
+ # RateGuard.configure do |config|
26
+ # config.algorithm = :sliding_window_counter
27
+ # config.limit = 60
28
+ # config.window = 60
29
+ # end
30
+ def configure
31
+ config = Configuration.new
32
+ yield config
33
+ @configuration = config.validate!.freeze
34
+ end
35
+
36
+ def configuration
37
+ @configuration or raise ConfigurationError, 'RateGuard.configure has not been called'
38
+ end
39
+
40
+ # Builds a new limiter (#acquire). Build once at boot and share it.
41
+ # Overrides apply to this limiter only:
42
+ # RateGuard.limiter(limit: 5, namespace: 'rate_guard:login')
43
+ def limiter(config = configuration, **overrides)
44
+ build(with_overrides(config, overrides), kind: :immediate, alternative: 'RateGuard.queue')
45
+ end
46
+
47
+ # Builds a new queue limiter (#enqueue, #dequeue).
48
+ def queue(config = configuration)
49
+ build(config, kind: :queue, alternative: 'RateGuard.limiter')
50
+ end
51
+
52
+ # Clears the configuration. For tests.
53
+ def reset_configuration!
54
+ @configuration = nil
55
+ end
56
+
57
+ private
58
+
59
+ # Returns a copy with some settings changed. The original is untouched.
60
+ def with_overrides(config, overrides)
61
+ return config if overrides.empty?
62
+
63
+ config.dup.tap do |copy|
64
+ overrides.each do |setting, value|
65
+ raise ArgumentError, "unknown setting #{setting.inspect}" unless copy.respond_to?(:"#{setting}=")
66
+
67
+ copy.public_send(:"#{setting}=", value)
68
+ end
69
+ end
70
+ end
71
+
72
+ def build(config, kind:, alternative:)
73
+ config.validate!
74
+ entry = Registry.fetch(config.algorithm)
75
+ unless entry.kind == kind
76
+ raise ConfigurationError,
77
+ "#{config.algorithm.inspect} is #{entry.kind == :queue ? 'a queue' : 'an immediate'} algorithm; " \
78
+ "build it with #{alternative}"
79
+ end
80
+
81
+ Registry.build(config)
82
+ end
83
+ end
84
+ end
metadata ADDED
@@ -0,0 +1,105 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rate_guard
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Luka Tchelidze
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rack
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.0'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '4'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '3.0'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '4'
32
+ description: Thread-safe rate limiters (token bucket, leaky bucket meter and queue,
33
+ fixed window, sliding window log, sliding window counter) with a Rack 3 middleware
34
+ that applies per-route policies, identifies clients by IP, API key or user, sends
35
+ RateLimit headers and retry-after, and can share counts between servers through
36
+ Redis with a fail-open or fail-closed policy.
37
+ executables: []
38
+ extensions: []
39
+ extra_rdoc_files: []
40
+ files:
41
+ - CHANGELOG.md
42
+ - LICENSE
43
+ - README.md
44
+ - lib/rate_guard.rb
45
+ - lib/rate_guard/admission.rb
46
+ - lib/rate_guard/algorithms/fixed_window_counter.rb
47
+ - lib/rate_guard/algorithms/leaky_bucket_meter.rb
48
+ - lib/rate_guard/algorithms/leaky_bucket_queue.rb
49
+ - lib/rate_guard/algorithms/redis_sliding_window_counter.rb
50
+ - lib/rate_guard/algorithms/sliding_window_counter.lua
51
+ - lib/rate_guard/algorithms/sliding_window_counter.rb
52
+ - lib/rate_guard/algorithms/sliding_window_log.rb
53
+ - lib/rate_guard/algorithms/token_bucket.rb
54
+ - lib/rate_guard/bypass.rb
55
+ - lib/rate_guard/clock.rb
56
+ - lib/rate_guard/configuration.rb
57
+ - lib/rate_guard/errors.rb
58
+ - lib/rate_guard/identifiers.rb
59
+ - lib/rate_guard/identifiers/api_key.rb
60
+ - lib/rate_guard/identifiers/first_of.rb
61
+ - lib/rate_guard/identifiers/global.rb
62
+ - lib/rate_guard/identifiers/ip.rb
63
+ - lib/rate_guard/identifiers/user.rb
64
+ - lib/rate_guard/json_log_formatter.rb
65
+ - lib/rate_guard/metrics.rb
66
+ - lib/rate_guard/middleware.rb
67
+ - lib/rate_guard/middleware/client_ip.rb
68
+ - lib/rate_guard/policy.rb
69
+ - lib/rate_guard/policy_set.rb
70
+ - lib/rate_guard/redis_error_reporter.rb
71
+ - lib/rate_guard/registry.rb
72
+ - lib/rate_guard/request.rb
73
+ - lib/rate_guard/result.rb
74
+ - lib/rate_guard/tiers.rb
75
+ - lib/rate_guard/utils/numeric_utils.rb
76
+ - lib/rate_guard/validators/configuration_validator.rb
77
+ - lib/rate_guard/validators/cost_validator.rb
78
+ - lib/rate_guard/version.rb
79
+ homepage: https://github.com/Null-logic-0/ruby-rate-limiter
80
+ licenses:
81
+ - MIT
82
+ metadata:
83
+ source_code_uri: https://github.com/Null-logic-0/ruby-rate-limiter
84
+ changelog_uri: https://github.com/Null-logic-0/ruby-rate-limiter/blob/main/CHANGELOG.md
85
+ rubygems_mfa_required: 'true'
86
+ allowed_push_host: https://rubygems.org
87
+ rdoc_options: []
88
+ require_paths:
89
+ - lib
90
+ required_ruby_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '4.0'
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ requirements: []
101
+ rubygems_version: 4.0.3
102
+ specification_version: 4
103
+ summary: 'Rate limiting for Ruby and Rack: six algorithms, per-route policies, optional
104
+ Redis.'
105
+ test_files: []