co-limit 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 72909f9bdd98c89548d9513f2431095a7edf110f0b2b62a3f928cb5f2f65ddba
4
+ data.tar.gz: a9be065e44bedb462c7595cf35bbb2a7f1feb9097f97581e210130891089d21e
5
+ SHA512:
6
+ metadata.gz: 20aee9b9a5a274424f880119f9dd7c59eb82624ceef1d3194e0c527b1a029370628563bb22885d5b688210504a02b244a744f60d2565825f7ad1970ac5e1f8ee
7
+ data.tar.gz: 3992bd40ac746931e6a797e0838cc36318029ca394cb425d84598636597761a461964857ce6ad35dc21ae79be8e434522758a7f2eb7ec1974a17c74447f51b1e
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-29
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at cosmicoppai@protonmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 CosmicOppai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,142 @@
1
+
2
+ # Limit Gem
3
+
4
+ Gem that provides flexible, Redis-backed rate limiting utilities. It supports both Fixed Window and Rolling Window (Sliding Log) strategies, to easily control the number of allowed requests for a given identifier within a time window.
5
+
6
+ You can define rate-limiting rules dynamically using a Proc, and configure Redis via environment variables (REDIS_HOST, REDIS_PORT, REDIS_PASSWORD) or by passing connection details directly.
7
+
8
+ This gem is ideal for APIs, background jobs, or any system that needs simple, efficient throttling logic.
9
+
10
+ ## Installation
11
+
12
+ To install the gem and add it to your application's Gemfile, execute:
13
+
14
+ ```bash
15
+ $ bundle add limit
16
+ ```
17
+
18
+ If you are not using Bundler, you can install the gem directly by running:
19
+
20
+ ```bash
21
+ $ gem install limit
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ### Example Usage
27
+
28
+ Here's an example of how to use the rate limiter in your application:
29
+
30
+ ```ruby
31
+ sync_limit_calculator = lambda do |key|
32
+ pms_name = key.split(':').last.to_sym
33
+ SITE_LIMITS.fetch(pms_name, :default)
34
+ end
35
+
36
+ rate_limiter = Limit::RollingWindowRateLimiter.new(
37
+ identifier_prefix: 'access',
38
+ limit_calculator: sync_limit_calculator,
39
+ host: '127.0.0.1',
40
+ port: 6379,
41
+ password: 'abcd1234'
42
+ )
43
+
44
+ key = '007:x'
45
+ success_count = 0
46
+ a = Time.now
47
+ 11.times do
48
+ allowed = rate_limiter.allowed?(key)
49
+ success_count += 1 if allowed
50
+ end
51
+
52
+ sleep 5 - (Time.now - a) + 0.5 # wait until the next window
53
+ allowed = rate_limiter.allowed?(key) # request will be allowed
54
+ success_count += 1 if allowed
55
+
56
+ puts "Success count: #{success_count}" # Expected to be 11
57
+ ```
58
+
59
+ ### Redis Configuration
60
+
61
+ You can configure the Redis connection either by passing the connection details as arguments or by setting environment variables.
62
+
63
+ - **Option 1**: Pass the connection details directly when initializing the limiter:
64
+
65
+ ```ruby
66
+ rate_limiter = Limit::RollingWindowRateLimiter.new(
67
+ identifier_prefix: 'access',
68
+ limit_calculator: sync_limit_calculator,
69
+ host: '127.0.0.1',
70
+ port: 6379,
71
+ password: 'abcd1234'
72
+ )
73
+ ```
74
+
75
+ - **Option 2**: Set the connection details as environment variables (`REDIS_HOST`, `REDIS_PORT`, and `REDIS_PASSWORD`), and the gem will automatically use them:
76
+
77
+ ```bash
78
+ export REDIS_HOST='127.0.0.1'
79
+ export REDIS_PORT='6379'
80
+ export REDIS_PASSWORD='abcd1234'
81
+ ```
82
+
83
+ In this case, the gem will use these environment variables to establish the Redis connection.
84
+
85
+ ### Key Points:
86
+
87
+ - **identifier_prefix**: A namespace prefix for Redis keys (e.g., `"access"`).
88
+ - **limit_calculator**: A `Proc` that takes a key (e.g., `"user_id:site_name"`) and returns a hash with `max_requests` and `window_seconds`.
89
+
90
+ ### Supported Rate Limiters:
91
+
92
+ - **Fixed Window Rate Limiter**:
93
+ Allows a specified number of requests within a fixed time window. This method can cause burst traffic as it doesn't account for requests made outside of the window until it resets.
94
+
95
+ - **Rolling Window Rate Limiter**:
96
+ Uses a sliding window mechanism, where only requests made within the last `n` seconds are counted. It provides more consistent traffic flow but can be more resource-intensive.
97
+
98
+ ## Development
99
+
100
+ After checking out the repo, install the dependencies by running:
101
+
102
+ ```bash
103
+ $ bin/setup
104
+ ```
105
+
106
+ To run tests, execute:
107
+
108
+ ```bash
109
+ $ rake test
110
+ ```
111
+
112
+ For an interactive prompt, run:
113
+
114
+ ```bash
115
+ $ bin/console
116
+ ```
117
+
118
+ To install the gem locally:
119
+
120
+ ```bash
121
+ $ bundle exec rake install
122
+ ```
123
+
124
+ To release a new version, update the version number in `version.rb`, and run:
125
+
126
+ ```bash
127
+ $ bundle exec rake release
128
+ ```
129
+
130
+ This will create a git tag for the new version, push the tag, and push the gem to [rubygems.org](https://rubygems.org).
131
+
132
+ ## Contributing
133
+
134
+ Bug reports and pull requests are welcome on GitHub at https://github.com/cosmicoppai/limit. This project aims to be a safe, welcoming space for collaboration. Contributors are expected to adhere to the [code of conduct](https://github.com/cosmicoppai/limit/blob/main/CODE_OF_CONDUCT.md).
135
+
136
+ ## License
137
+
138
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
139
+
140
+ ## Code of Conduct
141
+
142
+ Everyone interacting in the Limit project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [code of conduct](https://github.com/cosmicoppai/limit/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ task default: :test
data/Steepfile ADDED
@@ -0,0 +1,6 @@
1
+ target :lib do
2
+ signature "sig"
3
+ check "lib"
4
+
5
+ library 'redis'
6
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Limit
4
+ VERSION = '0.1.0'
5
+ end
data/lib/limit.rb ADDED
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'redis'
4
+ require 'logger'
5
+
6
+
7
+ module Limit
8
+
9
+ # Base Class, implementing:
10
+ # - Method to connect with redis
11
+ # - Signature for limit_calculator
12
+ class BaseLimiter
13
+ attr_reader :limit_calculator, :identifier_prefix
14
+
15
+ @redis = nil
16
+ @logger = Logger.new($stdout)
17
+
18
+ class << self
19
+
20
+ def connection
21
+ host = ENV['REDIS_HOST']
22
+ port = ENV['REDIS_PORT']
23
+ password = ENV['REDIS_PASSWORD']
24
+ @redis ||= create_connection(host: host, port: port, password: password)
25
+ end
26
+
27
+ def logger
28
+ @logger ||= Logger.new($stdout)
29
+ end
30
+
31
+ private
32
+
33
+ def create_connection(host:, port:, password:)
34
+ if password && !password.empty?
35
+ Redis.new(host: host, port: port, password: password)
36
+ else
37
+ logger.warn('Connecting without password')
38
+ Redis.new(host: host, port: port)
39
+ end
40
+ end
41
+
42
+ end
43
+
44
+ def initialize(identifier_prefix:, limit_calculator:, host: nil, port: nil, password: nil)
45
+
46
+ # @param identifier_prefix: [String] A namespace prefix for redis keys for this limiter instance
47
+ # @param limit_calculator: [Proc] A method that takes a key(String) and returns hash: {max_requests: Integer, window_seconds: Integer}
48
+
49
+ unless identifier_prefix.is_a?(String) && !identifier_prefix.empty?
50
+ raise ArgumentError, 'identifier_prefix must be a non-empty String'
51
+ end
52
+
53
+ raise ArgumentError, 'limit_calculator must be a Proc' unless limit_calculator.is_a?(Proc)
54
+
55
+ # Will be using the same connection across all instance unless wanted to connect to diff instance of redis
56
+
57
+ @redis = if host && port && password
58
+ self.class.send(:create_connection, host: host, port: port, password: password)
59
+ else
60
+ self.class.connection
61
+ end
62
+
63
+ @identifier_prefix = identifier_prefix
64
+ @limit_calculator = limit_calculator
65
+ @logger = self.class.logger
66
+
67
+ begin
68
+ @redis.ping
69
+ @logger.info("Successfully connected to Redis @ #{@redis.connection[:host]}:#{@redis.connection[:port]}")
70
+ rescue Redis::BaseError => e
71
+ @logger.error("Error connecting to Redis: #{e.message}")
72
+ raise e
73
+ end
74
+
75
+ end
76
+
77
+ def allowed?(key)
78
+ raise NotImplementedError "#{self.class.name} must implement the allowed? method"
79
+ end
80
+
81
+ def get_key(prefix)
82
+ raise NotImplementedError "#{self.class.name} must implement the get_key() method"
83
+ end
84
+
85
+
86
+ protected
87
+
88
+ def get_current_limit(key)
89
+ limit_data = @limit_calculator.call(key)
90
+
91
+ unless limit_data.is_a?(Hash) && limit_data[:max_requests].is_a?(Integer) && limit_data[:max_requests].positive? &&
92
+ limit_data[:window_seconds].is_a?(Integer) && limit_data[:window_seconds].positive?
93
+
94
+ raise ArgumentError, "Limit calculator for key '#{key}' returned invalid data: #{limit_data.inspect}. Expected { max_requests: Integer > 0, window_seconds: Integer > 0 }"
95
+ end
96
+
97
+ limit_data
98
+ end
99
+
100
+ def redis_pipeline(&block)
101
+ begin
102
+ @redis.pipelined { |pipe| block.call(pipe) }
103
+ rescue Redis::CommandError => e
104
+ @logger.error(e.message)
105
+ end
106
+ end
107
+
108
+ def current_micros
109
+ (Time.now.to_f * 1_000_000).to_i
110
+ end
111
+
112
+
113
+ end
114
+
115
+
116
+ # ====================================================================================================================
117
+
118
+ # Fixed Window Rate Limiter, allows n of request in a fixed window
119
+ # ALERT: There is a chance of bursts/spike in this method, so use it with caution
120
+ class FixedWindowRateLimiter < BaseLimiter
121
+ def allowed?(key)
122
+ limit_data = get_current_limit(key)
123
+ max_requests = limit_data[:max_requests]
124
+ window_seconds = limit_data[:window_seconds]
125
+
126
+ window_key = get_key(key, window_seconds)
127
+
128
+ results = redis_pipeline do |pipe|
129
+ # This is for simplicity as incr handles both creation and incrementing, rather than waiting on some read
130
+ # using the pipeline, the whole operation would also be atomic, as redis is single threaded and both queries are send in one trip
131
+ # https://redis.io/docs/latest/develop/use/pipelining/
132
+ pipe.incr(window_key)
133
+ pipe.expire(window_key, window_seconds)
134
+ end
135
+
136
+ results[0] <= max_requests
137
+ end
138
+
139
+ def get_key(prefix, window_seconds)
140
+ time_window = (Time.now.to_i / window_seconds) * window_seconds
141
+ "#{@identifier_prefix}:#{prefix}:#{time_window.to_s}"
142
+ end
143
+ end
144
+
145
+ # RollingWindow Rate limiter implemented using Sliding Log, allows n no of requests in rolling window
146
+ class RollingWindowRateLimiter < BaseLimiter
147
+ def allowed?(key)
148
+ limit_data = get_current_limit(key)
149
+ max_requests = limit_data[:max_requests]
150
+ window_seconds = limit_data[:window_seconds]
151
+
152
+ set_key = get_key(key)
153
+
154
+ curr_micros = current_micros
155
+
156
+ window_start_micros = curr_micros - (window_seconds*1_000_000)
157
+
158
+ results = redis_pipeline do |pipe|
159
+ # uses sorted set
160
+ # https://redis.io/glossary/redis-sorted-sets/
161
+ pipe.zremrangebyscore(set_key, 0, window_start_micros)
162
+ pipe.zadd(set_key, curr_micros, curr_micros.to_s)
163
+ pipe.zcard(set_key)
164
+ pipe.expire(set_key, window_seconds)
165
+ end
166
+
167
+ results[2] <= max_requests
168
+ end
169
+
170
+ def get_key(prefix)
171
+ "#{@identifier_prefix}:#{prefix}"
172
+ end
173
+ end
174
+
175
+
176
+ end
@@ -0,0 +1,37 @@
1
+ type redis = untyped
2
+
3
+ module Limit
4
+ VERSION: String
5
+
6
+ class BaseLimiter
7
+ self.@redis: redis
8
+ @logger: Logger
9
+
10
+ @redis: redis | nil
11
+
12
+ def self.connection: -> nil
13
+
14
+ def self.create_connection: (String, Integer, String) -> redis
15
+
16
+ def self.log: (String, String) -> nil
17
+
18
+ def self.logger: -> Logger
19
+
20
+ attr_reader identifier_prefix: String
21
+ attr_reader limit_calculator: Proc
22
+
23
+ def initialize: -> untyped
24
+
25
+ def allowed?: (String) -> bool
26
+
27
+ def get_current_limit: (String) -> Hash[String, Integer]
28
+
29
+ def get_key: (String) -> String
30
+
31
+ def current_micros: (nil) -> Integer
32
+
33
+ def log: (String, String) -> nil
34
+
35
+ def redis_pipeline: () { (redis) -> untyped } -> untyped
36
+ end
37
+ end
metadata ADDED
@@ -0,0 +1,68 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: co-limit
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - CosmicOppai
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-04-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 5.4.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 5.4.0
27
+ description:
28
+ email:
29
+ - cosmicoppai@protonmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - CHANGELOG.md
35
+ - CODE_OF_CONDUCT.md
36
+ - LICENSE.txt
37
+ - README.md
38
+ - Rakefile
39
+ - Steepfile
40
+ - lib/limit.rb
41
+ - lib/limit/version.rb
42
+ - sig/limit/limit.rbs
43
+ homepage: https://github.com/cosmicoppai/limit
44
+ licenses:
45
+ - MIT
46
+ metadata:
47
+ source_code_uri: https://github.com/cosmicoppai/limit
48
+ changelog_uri: https://github.com/Cosmicoppai/limit/blob/main/CHANGELOG.md
49
+ post_install_message:
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: 3.0.0
58
+ required_rubygems_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '0'
63
+ requirements: []
64
+ rubygems_version: 3.4.19
65
+ signing_key:
66
+ specification_version: 4
67
+ summary: Minimal Rate-Limiter
68
+ test_files: []