yiffspace-ratelimiter 0.0.1 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d90413425c9ac0bbcaa583ed3f4102a71249cee040461a9b8aaf587448335366
4
- data.tar.gz: 16bcebba650dbb82e3b576ce2f23a1a9bca0f4b9e620d868b5dff806dce3b4db
3
+ metadata.gz: 77cf9f240dd1c4dacba019ebf2410b3e1e4a5adbabffddd26c9b5b2fec3f669a
4
+ data.tar.gz: 823f669e96903f3e6332113c9bf47352eefdc9867c649d3f32a47943955d5114
5
5
  SHA512:
6
- metadata.gz: f5421c5a9af0734e8d0a5c17eae108c114654e63409e6921064eba26cd87ed6c919a59096027603a4674aa3133c63b4d51af5fb7590cc29a3fde7ec27e2f3065
7
- data.tar.gz: 9e13aae859c9acd87bf3c27354706653029efbee7dda0475fb42b7132e53805a84113062cf73cdfb64f0ad86d1c4b0fbf016f2871b290274b0cfbb6ced39ba0a
6
+ metadata.gz: 6ae0d30b58efc6684c6d6a1ac240f73d536022361d57d101fe54b21b76db1cb2520986fd898be6ad2a0c5de06663d749c20c9f42d8241d1e57004a6e428e5677
7
+ data.tar.gz: 78253b0632fa61b436cde5318e3773dede6451497cc7c50eb06f11e80825d50f87e7f089e490d086776aeb65585006eb309af9f5c0e956dd119af56758df0a3d
data/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
- ## Unreleased
1
+ ## 0.1.0
2
+
3
+ - **Breaking:** talks to the new rate limit service in ServerConfig instead of envoyproxy/ratelimit. Checks take a
4
+ host or url only, descriptors and `domain:` are gone.
5
+ - Added `source:`, so the service can show who's using a limit.
6
+ - `retry_after` is exactly how long until the host is free, from the service, instead of worked out from the window.
7
+ - `Check#remaining` is replaced by `Check#limit`.
8
+
9
+ ## 0.0.1
2
10
 
3
11
  - Initial release.
data/README.md CHANGED
@@ -1,8 +1,11 @@
1
1
  # YiffSpace::RateLimiter
2
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`.
3
+ A client for a shared rate limit service. It asks the service whether a request to a host can go out yet, and
4
+ doesn't send anything itself. The limits live in the service's config, so every app sharing one doesn't need to know
5
+ what they are, and each says who it is so the service can show who's using a limit. No dependency on the rest of
6
+ `yiffspace`.
7
+
8
+ The service is in [DonovanDMC/ServerConfig](https://github.com/DonovanDMC/ServerConfig) under `stacks/ratelimit`.
6
9
 
7
10
  ## Installation
8
11
 
@@ -21,7 +24,7 @@ $ bundle install
21
24
  ## Usage
22
25
 
23
26
  ```ruby
24
- limiter = YiffSpace::RateLimiter.new(url: "http://ratelimit.local")
27
+ limiter = YiffSpace::RateLimiter.new(url: "http://ratelimit.local", source: "my-app")
25
28
 
26
29
  # waits until it's allowed, then runs the block
27
30
  limiter.run("https://e621.net/posts.json") { Net::HTTP.get(URI("https://e621.net/posts.json")) }
@@ -32,34 +35,21 @@ limiter.wait("e621.net")
32
35
  # or just ask, an allowed check counts as the request
33
36
  check = limiter.check("e621.net")
34
37
  check.allowed? # => false
35
- check.remaining # => 0, nil when nothing limits it
36
38
  check.retry_after # => 0.42, in seconds
39
+ check.limit # => #<data YiffSpace::RateLimiter::Limit rate=2, burst=1>, nil when the host isn't limited
37
40
  ```
38
41
 
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
- ```
42
+ A url is checked as its hostname. Hosts the service has no limit for are always allowed.
47
43
 
48
44
  ### Options
49
45
 
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 |
46
+ | Option | Default | |
47
+ |-------------|------------|-------------------------------------------------------------------------------------------------------|
48
+ | `url` | | The service's url |
49
+ | `source` | *(none)* | Who's asking, shown on the service's status. Shows as `unknown` without it |
50
+ | `timeout` | `5` | How long to wait for the service, in seconds |
55
51
  | `fail_open` | `false` | Let requests go when the service can't be reached, instead of raising `YiffSpace::RateLimiter::Error` |
56
52
 
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
53
  ## Contributing
64
54
 
65
55
  Go away
@@ -2,9 +2,8 @@
2
2
 
3
3
  module YiffSpace
4
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
5
+ # limit is the host's limit, nil when it isn't limited. retry_after is how long until it can go in seconds, 0 when allowed
6
+ Check = Data.define(:allowed, :limit, :retry_after) do
8
7
  alias_method(:allowed?, :allowed)
9
8
  end
10
9
  end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YiffSpace
4
+ class RateLimiter
5
+ # rate is requests a second, burst is how many can go at once after a quiet spell
6
+ Limit = Data.define(:rate, :burst)
7
+ end
8
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module YiffSpace
4
4
  class RateLimiter
5
- VERSION = "0.0.1"
5
+ VERSION = "0.1.0"
6
6
  end
7
7
  end
@@ -7,39 +7,33 @@ require("uri")
7
7
  require("zeitwerk")
8
8
 
9
9
  module YiffSpace
10
- # Asks envoyproxy/ratelimit whether a request can go out yet, it doesn't send anything itself
10
+ # Asks a shared rate limit service whether a request to a host can go out yet, it doesn't send anything itself
11
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
12
  NETWORK_ERRORS = [SystemCallError, IOError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
17
13
 
18
- attr_reader(:url, :domain, :timeout, :fail_open)
14
+ attr_reader(:url, :source, :timeout, :fail_open)
19
15
 
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
16
+ # url is the service's url, like http://ratelimit.local. source is who's asking, shown on the service's status.
17
+ # timeout is in seconds. fail_open lets requests go when the service can't be reached, instead of raising
18
+ def initialize(url:, source: nil, timeout: 5, fail_open: false)
19
+ @url = URI.join(url, "/check")
20
+ @source = source
25
21
  @timeout = timeout
26
22
  @fail_open = fail_open
27
23
  end
28
24
 
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
25
+ # Whether a request can go now. An allowed check counts as the request. A url is checked as its hostname
31
26
  def check(target)
32
- response = post(descriptors(target))
33
- return open_check if response.nil?
27
+ response = post(host_of(target))
28
+ return Check.new(allowed: true, limit: nil, retry_after: 0) if response.nil?
34
29
 
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"
30
+ body = parse(response.body)
31
+ limit = body["limit"] && Limit.new(rate: body["limit"]["rate"], burst: body["limit"]["burst"])
32
+ return Check.new(allowed: true, limit: limit, retry_after: 0) if response.code == "200"
39
33
 
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)
34
+ # a second if it didn't say, so a bad reply can't make wait spin
35
+ retry_after = body["retryAfter"].is_a?(Numeric) && body["retryAfter"].positive? ? body["retryAfter"] / 1000.0 : 1
36
+ Check.new(allowed: false, limit: limit, retry_after: retry_after)
43
37
  end
44
38
 
45
39
  # Check until it's allowed. That last check counts as the request, so make it straight after
@@ -60,25 +54,25 @@ module YiffSpace
60
54
 
61
55
  private
62
56
 
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
57
  def host_of(target)
73
- URI.parse(target).host || target
58
+ return target.host if target.is_a?(URI::Generic)
59
+
60
+ URI.parse(target.to_s).host || target.to_s
74
61
  rescue URI::InvalidURIError
75
- target
62
+ target.to_s
63
+ end
64
+
65
+ def parse(text)
66
+ parsed = JSON.parse(text)
67
+ parsed.is_a?(Hash) ? parsed : {}
68
+ rescue JSON::ParserError
69
+ {}
76
70
  end
77
71
 
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 } } } } }
72
+ def post(host)
73
+ body = JSON.generate({ host: host, source: source }.compact)
80
74
  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")
75
+ http.post(url.path, body, "Content-Type" => "application/json")
82
76
  end
83
77
  return response if %w[200 429].include?(response.code)
84
78
  return nil if fail_open
@@ -89,17 +83,6 @@ module YiffSpace
89
83
 
90
84
  raise(Error, "couldn't reach #{url}: #{e.message}")
91
85
  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
86
  end
104
87
  end
105
88
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yiffspace-ratelimiter
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Donovan_DMC
@@ -38,6 +38,7 @@ files:
38
38
  - lib/yiffspace/ratelimiter.rb
39
39
  - lib/yiffspace/ratelimiter/check.rb
40
40
  - lib/yiffspace/ratelimiter/error.rb
41
+ - lib/yiffspace/ratelimiter/limit.rb
41
42
  - lib/yiffspace/ratelimiter/version.rb
42
43
  homepage: https://yiff.space
43
44
  licenses: