speed_check 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 42c058df28e8bc2d1a46aaf1479eab81862435462a1868778fb029443aa9ed6d
4
+ data.tar.gz: 02baf86b3972200e089a90368d23872d5d028ddd310487139563556156734692
5
+ SHA512:
6
+ metadata.gz: 05b34be079f246f8783f6ebb81e4972962accf044ca46b2c9f76f6b4ac8321f90fe270f432addadb160458a4ccda26108e1c2ef73f53999445105e15ebfb9b9c
7
+ data.tar.gz: 17da9b782b2ef9196dc32e9b5927466fe58ee10c759e0bf31506a86394c0c7d95f8afa4a979d37feed6ae9d62c426851666363ce310441ccac13cfa8157a6f5a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,35 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 2.6
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/MultilineBlockChain:
14
+ Enabled: false
15
+
16
+ Style/TrailingCommaInHashLiteral:
17
+ Enabled: false
18
+
19
+ Layout/LineLength:
20
+ Max: 120
21
+
22
+ Style/TrailingCommaInArguments:
23
+ Enabled: false
24
+
25
+ Metrics/MethodLength:
26
+ Enabled: false
27
+
28
+ Metrics/BlockLength:
29
+ Enabled: false
30
+
31
+ Documentation:
32
+ Enabled: false
33
+
34
+ Layout/MultilineMethodCallIndentation:
35
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-03-02
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 eldemcan@users.noreply.github.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/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in speed_check.gemspec
6
+ gemspec
7
+
8
+ gem 'mock_redis', '~> 0.36.0'
9
+ gem "rake", "~> 13.0"
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,62 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ speed_check (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.5.0)
11
+ json (2.6.3)
12
+ mock_redis (0.36.0)
13
+ ruby2_keywords
14
+ parallel (1.22.1)
15
+ parser (3.2.2.0)
16
+ ast (~> 2.4.1)
17
+ rainbow (3.1.1)
18
+ rake (13.0.6)
19
+ regexp_parser (2.7.0)
20
+ rexml (3.2.5)
21
+ rspec (3.12.0)
22
+ rspec-core (~> 3.12.0)
23
+ rspec-expectations (~> 3.12.0)
24
+ rspec-mocks (~> 3.12.0)
25
+ rspec-core (3.12.1)
26
+ rspec-support (~> 3.12.0)
27
+ rspec-expectations (3.12.2)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.12.0)
30
+ rspec-mocks (3.12.5)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.12.0)
33
+ rspec-support (3.12.0)
34
+ rubocop (1.48.1)
35
+ json (~> 2.3)
36
+ parallel (~> 1.10)
37
+ parser (>= 3.2.0.0)
38
+ rainbow (>= 2.2.2, < 4.0)
39
+ regexp_parser (>= 1.8, < 3.0)
40
+ rexml (>= 3.2.5, < 4.0)
41
+ rubocop-ast (>= 1.26.0, < 2.0)
42
+ ruby-progressbar (~> 1.7)
43
+ unicode-display_width (>= 2.4.0, < 3.0)
44
+ rubocop-ast (1.28.0)
45
+ parser (>= 3.2.1.0)
46
+ ruby-progressbar (1.13.0)
47
+ ruby2_keywords (0.0.5)
48
+ unicode-display_width (2.4.2)
49
+
50
+ PLATFORMS
51
+ arm64-darwin-21
52
+ x86_64-linux
53
+
54
+ DEPENDENCIES
55
+ mock_redis (~> 0.36.0)
56
+ rake (~> 13.0)
57
+ rspec (~> 3.0)
58
+ rubocop (~> 1.21)
59
+ speed_check!
60
+
61
+ BUNDLED WITH
62
+ 2.4.10
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Can Eldem
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,63 @@
1
+ # SpeedCheck
2
+
3
+
4
+ SpeedCheck is a Ruby gem that provides a simple way to implement sliding window rate limiting using Redis as the database. With SpeedCheck, you can easily limit the number of requests or actions performed by a user or IP address within a certain time period, such as 10 requests per minute.
5
+
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'speed_check'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install speed_check
22
+
23
+ ## Usage
24
+
25
+ First, you'll need to create a Redis client to use with SpeedCheck:
26
+
27
+ ```ruby
28
+ redis = Redis.new(host: "127.0.0.1", port: 6380, db: 15)
29
+ ```
30
+
31
+ Next, create a limiter object using the Redis client:
32
+
33
+ ```ruby
34
+ limit = SpeedCheck::Limiter.new(client: redis)
35
+ ```
36
+
37
+ To limit requests or actions for a specific identifier (e.g. user ID, IP address), use the window method with the identifier and limit value:
38
+
39
+ ```ruby
40
+ limit.window("some_identifier", 10) do
41
+ # your code here
42
+ end
43
+ ```
44
+
45
+ This will limit the number of requests or actions performed by "some_identifier" to 10 within a one-minute sliding window. If the limit is exceeded, an exception SpeedCheck::LimitExceeded will be raised.
46
+
47
+ ## Development
48
+
49
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
50
+
51
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
52
+
53
+ ## Contributing
54
+
55
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/speed_check. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/speed_check/blob/master/CODE_OF_CONDUCT.md).
56
+
57
+ ## License
58
+
59
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
60
+
61
+ ## Code of Conduct
62
+
63
+ Everyone interacting in the SpeedCheck project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/speed_check/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SpeedCheck
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "speed_check/version"
4
+
5
+ require "time"
6
+ require "date"
7
+ require "json"
8
+
9
+ module SpeedCheck
10
+ class LimitExceedError < StandardError
11
+ end
12
+
13
+ class Limiter
14
+ EXPIRE = 300 # 5 min
15
+
16
+ attr_reader :expire, :client
17
+
18
+ def initialize(opts)
19
+ @client = opts[:client]
20
+
21
+ raise ArgumentError, "client is required" if client.nil?
22
+
23
+ client.ping
24
+ end
25
+
26
+ def window(identifier, capacity_per_minute)
27
+ @request_time = Time.now.utc
28
+ @key = identifier
29
+
30
+ current_window_capacity = calculate_window_capacity
31
+
32
+ if current_window_capacity >= capacity_per_minute
33
+ raise(
34
+ LimitExceedError,
35
+ JSON.dump(
36
+ { capacity_per_minute: capacity_per_minute, identifier: @key },
37
+ ),
38
+ )
39
+ end
40
+
41
+ increase_current_time_counter
42
+
43
+ yield
44
+
45
+ delete_old_times
46
+ end
47
+
48
+ private
49
+
50
+ def calculate_window_capacity
51
+ seconds_in_window = (0..59).map { |n| @request_time - n }
52
+ keys_in_window = seconds_in_window.map { |time| key_for_time(time) }
53
+ counter_data = client.hgetall(@key)
54
+ keys_in_window.sum { |key| counter_data[key].to_i }
55
+ end
56
+
57
+ def delete_old_times
58
+ hash_keys = client.hkeys(@key)
59
+
60
+ old_fields =
61
+ hash_keys.select do |formatted_time|
62
+ time_utc =
63
+ Time.utc(
64
+ @request_time.year,
65
+ @request_time.month,
66
+ @request_time.day,
67
+ *formatted_time.split(":"),
68
+ )
69
+ time_utc <= (@request_time - 120)
70
+ end
71
+ client.hdel(@key, old_fields) unless blank?(old_fields)
72
+ end
73
+
74
+ def increase_current_time_counter
75
+ time_key = key_for_time(@request_time)
76
+ client.pipelined do |pipe|
77
+ pipe.hincrby(@key, time_key, 1)
78
+ pipe.expire(@key, expire)
79
+ end
80
+ end
81
+
82
+ # copy-pasted from ActiveSupport
83
+ def blank?(obj)
84
+ obj.respond_to?(:empty?) ? obj.empty? : !obj
85
+ end
86
+
87
+ def key_for_time(time)
88
+ time.strftime("%H:%M:%S")
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,12 @@
1
+ module SpeedCheck
2
+ VERSION: String
3
+
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ class Limiter
6
+ attr_accessor expire: Integer
7
+ attr_accessor client: Redis
8
+
9
+ def initialize: (opts: Hash) -> void
10
+ def window(identifier: String, capacity_per_minute: Integer) -> void
11
+ end
12
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: speed_check
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Can Eldem
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-04-02 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: SpeedCheck provides a simple way to limit the number of requests or actions
14
+ performed by a user or IP address within a certain time period.
15
+ email:
16
+ - eldemcan@users.noreply.github.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".rspec"
22
+ - ".rubocop.yml"
23
+ - CHANGELOG.md
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - Gemfile.lock
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - lib/speed_check.rb
31
+ - lib/speed_check/version.rb
32
+ - sig/speed_check.rbs
33
+ homepage: https://github.com/eldemcan/speed_check
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://github.com/eldemcan/speed_check
38
+ source_code_uri: https://github.com/eldemcan/speed_check
39
+ changelog_uri: https://github.com/eldemcan/speed_check
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: 2.7.0
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 3.3.26
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: A Ruby gem for sliding window rate limiting using Redis as the database.
59
+ test_files: []