limiter-ruby 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: 89a952e1a844303c615335021b9d5b8dc63d02ef09036f73aa28cd16b191875f
4
+ data.tar.gz: 8475379bf65884d9376d2d37544900847712c8434b0ef1197d3427d7d5ccc276
5
+ SHA512:
6
+ metadata.gz: d035c3075ca83f56ecd77afa1f190e0ea76bfdb7266fcf934f50b49e72be0e5c3ad7bd3440d16ad4b4177a7d3b92060f082dea62345afd4a9968f2ed9e3e199b
7
+ data.tar.gz: 0604d0feffafebcb9462424fc24160ffd025f695d7a4b8e4237a34f93ba1fcb50cf2e075784e9ce1a59fcbecdda60abde265c2f58c15582fe4a1dfc7aba510c0
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -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 bilal@bilalbudhani.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) 2024 bilal
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,47 @@
1
+ # Limiter
2
+
3
+ [Limiter.dev](https://limiter.dev) enables building rate limits for your application with ease. It provides a simple interface to define rate limits and track usage.
4
+
5
+ ## Usage
6
+
7
+ ### Generate API Token
8
+
9
+ Before using the gem you must register at <https://limiter.dev> and generate an token to interact with the api. Thereafter, add the token to app's environment variable
10
+
11
+ ```
12
+ LIMITER_TOKEN: [GENERATED TOKEN]
13
+ ```
14
+
15
+ ### Install the gem
16
+
17
+ In the `Gemfile` add the following
18
+
19
+ ```ruby
20
+ gem "limiter"
21
+ ```
22
+
23
+ ## Integrate
24
+
25
+ Assuming this is a Ruby on Rails app within ActiveJob
26
+
27
+ ```ruby
28
+ class ExpensiveJob < ApplicationJob
29
+
30
+ def perform
31
+ rate_limit = limiter.check(user.id) # A unique identifier
32
+
33
+ if rate_limit.exhausted? # Rate limit got hit
34
+ self.class.set(wait: rate_limit.resets_in).perform_later(..args)
35
+ return
36
+ end
37
+
38
+ # Good to continue expensive operation
39
+ # ...
40
+ end
41
+
42
+ private
43
+ def limiter
44
+ Limiter::Client.new(namespace: "openai", limit: 60, period: 1.minute)
45
+ end
46
+ end
47
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Limiter
4
+ class Client
5
+
6
+ BASE_DOMAIN = "https://api.limiter.dev".freeze
7
+
8
+ attr_reader :namespace, :limit, :period, :identifier, :token
9
+
10
+ def initialize(namespace:, limit:, period:)
11
+ @namespace = namespace
12
+ @limit = limit
13
+ @period = period.to_i
14
+ @token = ENV["LIMITER_TOKEN"]
15
+
16
+ ErrorHandler.error("LIMITER_TOKEN environment variable is not set") if @token.nil?
17
+ end
18
+
19
+ def check(identifier)
20
+ @identifier = identifier
21
+ RateLimitResponse.new(request)
22
+ end
23
+
24
+ def formatted_period
25
+ case @period
26
+ when 60..3599
27
+ (@period / 60).to_s + "m"
28
+ when 3600..86_399
29
+ (@period / 3600).to_s + "h"
30
+ when 86_400..1_209_599
31
+ (@period / 86_400).to_s + "d"
32
+ else
33
+ ErrorHandler.error("Invalid period")
34
+ end
35
+ end
36
+
37
+ def url
38
+ "#{BASE_DOMAIN}/#{namespace}/#{limit}/#{formatted_period}/#{identifier}"
39
+ end
40
+
41
+ def request
42
+ HTTP.get(url, params: { token: token})
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+ require "logger"
3
+
4
+ module Limiter
5
+ class ErrorHandler
6
+ def self.error(error)
7
+ new(error).handle_error
8
+ end
9
+
10
+ def initialize(error)
11
+ @error = error
12
+ end
13
+
14
+ def handle_error
15
+ if !production?
16
+ raise Error, @error
17
+ else
18
+ log @error
19
+ end
20
+ end
21
+
22
+ def production?
23
+ if defined?(Rails)
24
+ Rails.env.production?
25
+ else
26
+ (ENV["RACK_ENV"] || ENV["RAILS_ENV"] ) == "production"
27
+ end
28
+ end
29
+
30
+ def log(error)
31
+ @logger ||= Logger.new(STDOUT)
32
+ @logger.error(error)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Limiter
4
+ class RateLimitResponse
5
+
6
+ attr_reader :response
7
+
8
+ def initialize(response)
9
+ @response = response
10
+ end
11
+
12
+ def exhausted?
13
+ signed_request? && @response.status == 429
14
+ end
15
+
16
+ def allowed?
17
+ signed_request? && @response.status == 200
18
+ end
19
+
20
+ def resets_in
21
+ if signed_request? && !resets_at.nil?
22
+ (Time.parse(resets_at) - Time.now).to_i
23
+ else
24
+ 0
25
+ end
26
+ end
27
+
28
+ def signed_request?
29
+ @response.headers["X-Limiter-Signed"].to_s == "true"
30
+ end
31
+
32
+ private
33
+ def rate_limit_data
34
+ @_body ||= @response.parse
35
+ end
36
+
37
+ def resets_at
38
+ rate_limit_data["resetsAt"]
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Limiter
4
+ VERSION = "0.1.0"
5
+ end
data/lib/limiter.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "http"
4
+ require_relative "limiter/client"
5
+ require_relative "limiter/rate_limit_response"
6
+ require_relative "limiter/error_handler"
7
+ require_relative "limiter/version"
8
+
9
+ module Limiter
10
+ class Error < StandardError; end
11
+ end
data/limiter.gemspec ADDED
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/limiter/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "limiter-ruby"
7
+ spec.version = Limiter::VERSION
8
+ spec.authors = ["Bilal Budhani"]
9
+ spec.email = ["bilal@bilalbudhani.com"]
10
+
11
+ spec.summary = "Easily Build & Track Rate Limits"
12
+ spec.description = "Limiter enables building rate limits for your application with ease. It provides a simple interface to define rate limits and track usage."
13
+ spec.homepage = "https://limiter.dev"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/bilalbudhani/limiter-ruby"
19
+ spec.metadata["changelog_uri"] = "https://github.com/bilalbudhani/limiter-ruby"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (File.expand_path(f) == __FILE__) ||
26
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
27
+ end
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ # Uncomment to register a new dependency of your gem
34
+ spec.add_dependency "http", "~> 5.0"
35
+
36
+ # For more information and examples about making a new gem, check out our
37
+ # guide at: https://bundler.io/guides/creating_gem.html
38
+ end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: limiter-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bilal Budhani
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-05-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: http
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '5.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.0'
27
+ description: Limiter enables building rate limits for your application with ease.
28
+ It provides a simple interface to define rate limits and track usage.
29
+ email:
30
+ - bilal@bilalbudhani.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rspec"
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - lib/limiter.rb
41
+ - lib/limiter/client.rb
42
+ - lib/limiter/error_handler.rb
43
+ - lib/limiter/rate_limit_response.rb
44
+ - lib/limiter/version.rb
45
+ - limiter.gemspec
46
+ homepage: https://limiter.dev
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://limiter.dev
51
+ source_code_uri: https://github.com/bilalbudhani/limiter-ruby
52
+ changelog_uri: https://github.com/bilalbudhani/limiter-ruby
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 2.6.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.5.3
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: Easily Build & Track Rate Limits
72
+ test_files: []