yiffspace-ratelimiter 0.0.1

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: d90413425c9ac0bbcaa583ed3f4102a71249cee040461a9b8aaf587448335366
4
+ data.tar.gz: 16bcebba650dbb82e3b576ce2f23a1a9bca0f4b9e620d868b5dff806dce3b4db
5
+ SHA512:
6
+ metadata.gz: f5421c5a9af0734e8d0a5c17eae108c114654e63409e6921064eba26cd87ed6c919a59096027603a4674aa3133c63b4d51af5fb7590cc29a3fde7ec27e2f3065
7
+ data.tar.gz: 9e13aae859c9acd87bf3c27354706653029efbee7dda0475fb42b7132e53805a84113062cf73cdfb64f0ad86d1c4b0fbf016f2871b290274b0cfbb6ced39ba0a
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## Unreleased
2
+
3
+ - Initial release.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright Donovan_DMC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # YiffSpace::RateLimiter
2
+
3
+ A client for [envoyproxy/ratelimit](https://github.com/envoyproxy/ratelimit). It asks the service whether a request
4
+ can go out yet, and doesn't send anything itself. The limits live in the service's config, so every app sharing one
5
+ doesn't need to know what they are. No dependency on the rest of `yiffspace`.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem "yiffspace-ratelimiter"
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ ```bash
18
+ $ bundle install
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ limiter = YiffSpace::RateLimiter.new(url: "http://ratelimit.local")
25
+
26
+ # waits until it's allowed, then runs the block
27
+ limiter.run("https://e621.net/posts.json") { Net::HTTP.get(URI("https://e621.net/posts.json")) }
28
+
29
+ # or on its own
30
+ limiter.wait("e621.net")
31
+
32
+ # or just ask, an allowed check counts as the request
33
+ check = limiter.check("e621.net")
34
+ check.allowed? # => false
35
+ check.remaining # => 0, nil when nothing limits it
36
+ check.retry_after # => 0.42, in seconds
37
+ ```
38
+
39
+ A url or hostname is checked as `{ host: <hostname> }`. Anything else can be checked with descriptors, in the order
40
+ they're nested in the service's config:
41
+
42
+ ```ruby
43
+ limiter.check({ host: "e621.net", user: "123" })
44
+ # several at once, allowed only if every one is
45
+ limiter.check([{ host: "e621.net" }, { host: "e621.net", window: "second" }])
46
+ ```
47
+
48
+ ### Options
49
+
50
+ | Option | Default | |
51
+ |-------------|------------|------------------------------------------------------------------------------------------------------|
52
+ | `url` | | The service's http port |
53
+ | `domain` | `outbound` | The domain the limits are under in the service's config |
54
+ | `timeout` | `5` | How long to wait for the service, in seconds |
55
+ | `fail_open` | `false` | Let requests go when the service can't be reached, instead of raising `YiffSpace::RateLimiter::Error` |
56
+
57
+ ### Waiting
58
+
59
+ The service only says how long is left in whole seconds, so for second, minute, hour and day limits the wait is worked
60
+ out from the window instead. Those line up with the unix epoch, a per second limit resets on every whole second.
61
+ Everything else waits for what the service says.
62
+
63
+ ## Contributing
64
+
65
+ Go away
66
+
67
+ ## License
68
+
69
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require("bundler/gem_tasks")
4
+ require("minitest/test_task")
5
+
6
+ Minitest::TestTask.create
7
+
8
+ # CI releases from an already-tagged, already-pushed commit checked out at a detached HEAD, so
9
+ # the default release task's git tag/push step has nothing to do and fails trying to push a
10
+ # branch ref that does not exist in that checkout.
11
+ Rake::Task["release"].clear
12
+ task("release" => "release:rubygem_push")
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YiffSpace
4
+ class RateLimiter
5
+ # remaining is what's left in the current window, nil when nothing limits it.
6
+ # retry_after is how long until it's worth checking again in seconds, 0 when allowed
7
+ Check = Data.define(:allowed, :remaining, :retry_after) do
8
+ alias_method(:allowed?, :allowed)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YiffSpace
4
+ class RateLimiter
5
+ class Error < StandardError; end
6
+ end
7
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YiffSpace
4
+ class RateLimiter
5
+ VERSION = "0.0.1"
6
+ end
7
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require("json")
4
+ require("net/http")
5
+ require("openssl")
6
+ require("uri")
7
+ require("zeitwerk")
8
+
9
+ module YiffSpace
10
+ # Asks envoyproxy/ratelimit whether a request can go out yet, it doesn't send anything itself
11
+ class RateLimiter
12
+ # windows line up with the unix epoch, so these can say exactly when the next one starts. the service only gives whole seconds
13
+ UNITS = { "SECOND" => 1, "MINUTE" => 60, "HOUR" => 3600, "DAY" => 86_400 }.freeze
14
+ # a little past the edge, so a slightly slow clock here doesn't land in the old window
15
+ MARGIN = 0.005
16
+ NETWORK_ERRORS = [SystemCallError, IOError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
17
+
18
+ attr_reader(:url, :domain, :timeout, :fail_open)
19
+
20
+ # url is the service's http port, like http://ratelimit.local. timeout is in seconds.
21
+ # fail_open lets requests go when the service can't be reached, instead of raising
22
+ def initialize(url:, domain: "outbound", timeout: 5, fail_open: false)
23
+ @url = URI.join(url, "/json")
24
+ @domain = domain
25
+ @timeout = timeout
26
+ @fail_open = fail_open
27
+ end
28
+
29
+ # Whether a request can go now. An allowed check counts as the request.
30
+ # A url or hostname is checked as { host: <hostname> }, anything else as descriptors, one hash each
31
+ def check(target)
32
+ response = post(descriptors(target))
33
+ return open_check if response.nil?
34
+
35
+ statuses = JSON.parse(response.body).fetch("statuses", [])
36
+ limited = statuses.select { |status| status["currentLimit"] }
37
+ remaining = limited.empty? ? nil : limited.map { |status| status.fetch("limitRemaining", 0) }.min
38
+ return Check.new(allowed: true, remaining: remaining, retry_after: 0) if response.code == "200"
39
+
40
+ now = Time.now.to_f
41
+ over = statuses.select { |status| status["code"] == "OVER_LIMIT" }
42
+ Check.new(allowed: false, remaining: remaining, retry_after: over.map { |status| wait_for(status, now) }.max || 1)
43
+ end
44
+
45
+ # Check until it's allowed. That last check counts as the request, so make it straight after
46
+ def wait(target)
47
+ loop do
48
+ result = check(target)
49
+ return result if result.allowed?
50
+
51
+ sleep(result.retry_after)
52
+ end
53
+ end
54
+
55
+ # Wait until it's allowed, then run the block
56
+ def run(target)
57
+ wait(target)
58
+ yield
59
+ end
60
+
61
+ private
62
+
63
+ def descriptors(target)
64
+ case target
65
+ when Array then target
66
+ when Hash then [target]
67
+ when URI::Generic then [{ host: target.host }]
68
+ else [{ host: host_of(target.to_s) }]
69
+ end
70
+ end
71
+
72
+ def host_of(target)
73
+ URI.parse(target).host || target
74
+ rescue URI::InvalidURIError
75
+ target
76
+ end
77
+
78
+ def post(descriptors)
79
+ body = { domain: domain, descriptors: descriptors.map { |descriptor| { entries: descriptor.map { |key, value| { key: key.to_s, value: value.to_s } } } } }
80
+ response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == "https", open_timeout: timeout, read_timeout: timeout, write_timeout: timeout) do |http|
81
+ http.post(url.path, JSON.generate(body), "Content-Type" => "application/json")
82
+ end
83
+ return response if %w[200 429].include?(response.code)
84
+ return nil if fail_open
85
+
86
+ raise(Error, "#{url} returned #{response.code}: #{response.body}")
87
+ rescue *NETWORK_ERRORS => e
88
+ return nil if fail_open
89
+
90
+ raise(Error, "couldn't reach #{url}: #{e.message}")
91
+ end
92
+
93
+ def open_check
94
+ Check.new(allowed: true, remaining: nil, retry_after: 0)
95
+ end
96
+
97
+ def wait_for(status, now)
98
+ unit = UNITS[status.dig("currentLimit", "unit")]
99
+ return unit - (now % unit) + MARGIN if unit
100
+
101
+ Float(status["durationUntilReset"].to_s.delete_suffix("s"), exception: false) || 1
102
+ end
103
+ end
104
+ end
105
+
106
+ loader = Zeitwerk::Loader.for_gem_extension(YiffSpace)
107
+ loader.inflector.inflect({ "ratelimiter" => "RateLimiter" })
108
+ loader.setup
metadata ADDED
@@ -0,0 +1,69 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yiffspace-ratelimiter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Donovan_DMC
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-12-05 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: zeitwerk
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '2.6'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '2.6'
26
+ description: A client for envoyproxy/ratelimit, to check whether a request can go
27
+ out yet
28
+ email:
29
+ - hewwo@yiff.rocks
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - CHANGELOG.md
35
+ - LICENSE
36
+ - README.md
37
+ - Rakefile
38
+ - lib/yiffspace/ratelimiter.rb
39
+ - lib/yiffspace/ratelimiter/check.rb
40
+ - lib/yiffspace/ratelimiter/error.rb
41
+ - lib/yiffspace/ratelimiter/version.rb
42
+ homepage: https://yiff.space
43
+ licenses:
44
+ - MIT
45
+ metadata:
46
+ allowed_push_host: https://rubygems.org
47
+ homepage_uri: https://yiff.space
48
+ source_code_uri: https://github.com/YiffSpace/Gem/tree/master/packages/yiffspace-ratelimiter
49
+ changelog_uri: https://github.com/YiffSpace/Gem/blob/master/packages/yiffspace-ratelimiter/CHANGELOG.md
50
+ rubygems_mfa_required: 'true'
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: 3.4.1
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubygems_version: 3.6.2
66
+ specification_version: 4
67
+ summary: A client for envoyproxy/ratelimit, to check whether a request can go out
68
+ yet
69
+ test_files: []