/
limiter.rb
210 lines (194 loc) · 5.96 KB
/
limiter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
module Rack; module Throttle
##
# This is the base class for rate limiter implementations.
#
# @example Defining a rate limiter subclass
# class MyLimiter < Limiter
# def allowed?(request)
# # TODO: custom logic goes here
# end
# end
#
class Limiter
attr_reader :app
attr_reader :options
##
# @param [#call] app
# @param [Hash{Symbol => Object}] options
# @option options [String] :cache (Hash.new)
# @option options [String] :key (nil)
# @option options [String] :key_prefix (nil)
# @option options [Integer] :code (403)
# @option options [String] :message ("Rate Limit Exceeded")
# @option options [String] :type ("text/plain; charset=utf-8")
def initialize(app, options = {})
@app, @options = app, options
end
##
# @param [Hash{String => String}] env
# @return [Array(Integer, Hash, #each)]
# @see http://rack.rubyforge.org/doc/SPEC.html
def call(env)
request = Rack::Request.new(env)
allowed?(request) ? app.call(env) : rate_limit_exceeded(request)
end
##
# Returns `false` if the rate limit has been exceeded for the given
# `request`, or `true` otherwise.
#
# Override this method in subclasses that implement custom rate limiter
# strategies.
#
# @param [Rack::Request] request
# @return [Boolean]
def allowed?(request)
case
when whitelisted?(request) then true
when blacklisted?(request) then false
else true # override in subclasses
end
end
##
# Returns `true` if the originator of the given `request` is whitelisted
# (not subject to further rate limits).
#
# The default implementation always returns `false`. Override this
# method in a subclass to implement custom whitelisting logic.
#
# @param [Rack::Request] request
# @return [Boolean]
# @abstract
def whitelisted?(request)
false
end
##
# Returns `true` if the originator of the given `request` is blacklisted
# (not honoring rate limits, and thus permanently forbidden access
# without the need to maintain further rate limit counters).
#
# The default implementation always returns `false`. Override this
# method in a subclass to implement custom blacklisting logic.
#
# @param [Rack::Request] request
# @return [Boolean]
# @abstract
def blacklisted?(request)
false
end
protected
##
# @return [Hash]
def cache
case cache = (options[:cache] ||= {})
when Proc then cache.call
else cache
end
end
##
# @param [String] key
def cache_has?(key)
case
when cache.respond_to?(:has_key?)
cache.has_key?(key)
when cache.respond_to?(:get)
cache.get(key) rescue false
else false
end
end
##
# @param [String] key
# @return [Object]
def cache_get(key, default = nil)
case
when cache.respond_to?(:[])
cache[key] || default
when cache.respond_to?(:get)
cache.get(key) || default
end
end
##
# @param [String] key
# @param [Object] value
# @return [void]
def cache_set(key, value)
case
when cache.respond_to?(:[]=)
begin
cache[key] = value
rescue TypeError
# GDBM throws a "TypeError: can't convert Float into String"
# exception when trying to store a Float. On the other hand, we
# don't want to unnecessarily coerce the value to a String for
# any stores that do support other data types (e.g. in-memory
# hash objects). So, this is a compromise.
cache[key] = value.to_s
end
when cache.respond_to?(:set)
cache.set(key, value)
end
end
##
# @param [Rack::Request] request
# @return [String]
def cache_key(request)
id = client_identifier(request)
case
when options.has_key?(:key)
options[:key].call(request)
when options.has_key?(:key_prefix)
[options[:key_prefix], id].join(':')
else id
end
end
##
# @param [Rack::Request] request
# @return [String]
def client_identifier(request)
request.ip.to_s
end
##
# @param [Rack::Request] request
# @return [Float]
def request_start_time(request)
# Check whether HTTP_X_REQUEST_START or HTTP_X_QUEUE_START exist and parse its value (for
# example, when having nginx in your stack, it's going to be in the "t=\d+" format).
if val = (request.env['HTTP_X_REQUEST_START'] || request.env['HTTP_X_QUEUE_START'])
val[/(?:^t=)?(\d+)/, 1].to_f / 1000
else
Time.now.to_f
end
end
##
# Outputs a `Rate Limit Exceeded` error.
#
# @return [Array(Integer, Hash, #each)]
def rate_limit_exceeded(request)
options[:rate_limit_exceeded_callback].call(request) if options[:rate_limit_exceeded_callback]
headers = respond_to?(:retry_after) ? {'Retry-After' => retry_after.to_f.ceil.to_s} : {}
http_error(options[:code] || 403, options[:message] || 'Rate Limit Exceeded', headers)
end
##
# Outputs an HTTP `4xx` or `5xx` response.
#
# @param [Integer] code
# @param [String, #to_s] message
# @param [Hash{String => String}] headers
# @return [Array(Integer, Hash, #each)]
def http_error(code, message = nil, headers = {})
contentType = 'text/plain; charset=utf-8'
if options[:type]
contentType = options[:type]
end
[code, {'Content-Type' => contentType}.merge(headers),
[message]]
end
##
# Returns the standard HTTP status message for the given status `code`.
#
# @param [Integer] code
# @return [String]
def http_status(code)
[code, Rack::Utils::HTTP_STATUS_CODES[code]].join(' ')
end
end
end; end