whoosh 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 +7 -0
- data/CHANGELOG.md +18 -0
- data/LICENSE +21 -0
- data/README.md +209 -0
- data/lib/generators/whoosh/install/install_generator.rb +30 -0
- data/lib/generators/whoosh/install/templates/application_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/initializer.rb.tt +25 -0
- data/lib/generators/whoosh/install/templates/status_api.rb.tt +11 -0
- data/lib/generators/whoosh/install/templates/status_schema.rb.tt +4 -0
- data/lib/whoosh/api.rb +134 -0
- data/lib/whoosh/app.rb +280 -0
- data/lib/whoosh/configuration.rb +76 -0
- data/lib/whoosh/context.rb +56 -0
- data/lib/whoosh/endpoint.rb +168 -0
- data/lib/whoosh/errors.rb +62 -0
- data/lib/whoosh/idempotency.rb +70 -0
- data/lib/whoosh/json.rb +43 -0
- data/lib/whoosh/lazy_app.rb +28 -0
- data/lib/whoosh/openapi.rb +181 -0
- data/lib/whoosh/pagination.rb +109 -0
- data/lib/whoosh/railtie.rb +19 -0
- data/lib/whoosh/rate_limiter.rb +31 -0
- data/lib/whoosh/request.rb +120 -0
- data/lib/whoosh/router.rb +90 -0
- data/lib/whoosh/schema.rb +375 -0
- data/lib/whoosh/stores/cache.rb +40 -0
- data/lib/whoosh/stores/memory.rb +76 -0
- data/lib/whoosh/types.rb +153 -0
- data/lib/whoosh/version.rb +3 -0
- data/lib/whoosh.rb +72 -0
- metadata +92 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Idempotency keys for unsafe endpoints (payments, orders). The first
|
|
3
|
+
# request with a key runs; repeats with the same key and body get the
|
|
4
|
+
# stored response; the same key with a different body is rejected.
|
|
5
|
+
class Idempotency
|
|
6
|
+
HEADER = "idempotency-key"
|
|
7
|
+
KEY_FORMAT = /\A[\w\-.:]{8,255}\z/
|
|
8
|
+
# How long a running request holds its key. If the process dies, retries
|
|
9
|
+
# work again after this instead of after the full TTL.
|
|
10
|
+
# ponytail: fixed 60 s, so a handler slower than that can run twice; make it configurable if one ever is.
|
|
11
|
+
LOCK_TTL = 60
|
|
12
|
+
|
|
13
|
+
def initialize(store, ttl:)
|
|
14
|
+
@store = store
|
|
15
|
+
@ttl = ttl
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Yields when the request should run. Returns a Rack triplet: either the
|
|
19
|
+
# replayed response or the one the block produced.
|
|
20
|
+
def call(request, scope:, client:, required:)
|
|
21
|
+
key = request.header(HEADER)
|
|
22
|
+
if key.nil? || key.empty?
|
|
23
|
+
raise BadRequest.new("Send an Idempotency-Key header with this request.", code: "idempotency_key_missing") if required
|
|
24
|
+
|
|
25
|
+
return yield
|
|
26
|
+
end
|
|
27
|
+
raise BadRequest.new("The Idempotency-Key header is invalid.", code: "idempotency_key_invalid") unless key.match?(KEY_FORMAT)
|
|
28
|
+
|
|
29
|
+
store_key = "idem:#{scope}:#{client}:#{Digest::SHA256.hexdigest(key)}"
|
|
30
|
+
fingerprint = Digest::SHA256.hexdigest("#{request.request_method} #{request.path}\n#{request.raw_body}")
|
|
31
|
+
|
|
32
|
+
existing = @store.read(store_key)
|
|
33
|
+
return replay(existing, fingerprint) if existing
|
|
34
|
+
|
|
35
|
+
unless @store.write_unless_exists(store_key, { "state" => "processing", "fingerprint" => fingerprint }, ttl: [LOCK_TTL, @ttl].min)
|
|
36
|
+
return replay(@store.read(store_key), fingerprint)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
begin
|
|
40
|
+
status, headers, body = yield
|
|
41
|
+
rescue StandardError
|
|
42
|
+
@store.delete(store_key)
|
|
43
|
+
raise
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
if status >= 500
|
|
47
|
+
@store.delete(store_key)
|
|
48
|
+
else
|
|
49
|
+
@store.write(store_key, { "state" => "done", "fingerprint" => fingerprint,
|
|
50
|
+
"status" => status, "headers" => headers.slice("content-type", "location"),
|
|
51
|
+
"body" => body.join }, ttl: @ttl)
|
|
52
|
+
end
|
|
53
|
+
[status, headers, body]
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
def replay(record, fingerprint)
|
|
59
|
+
raise Conflict.new("A request with this Idempotency-Key is still being processed.", code: "idempotency_in_progress") if record.nil? || record["state"] == "processing"
|
|
60
|
+
|
|
61
|
+
if record["fingerprint"] != fingerprint
|
|
62
|
+
raise UnprocessableEntity.new("This Idempotency-Key was already used with a different request.",
|
|
63
|
+
code: "idempotency_key_reused")
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
headers = record["headers"].merge("idempotent-replayed" => "true")
|
|
67
|
+
[record["status"], headers, [record["body"]]]
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
data/lib/whoosh/json.rb
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# JSON encoding and decoding. Uses Oj when the app has it loaded; falls back
|
|
3
|
+
# to the stdlib json gem. Parsing never creates arbitrary objects.
|
|
4
|
+
module JSON
|
|
5
|
+
module_function
|
|
6
|
+
|
|
7
|
+
def dump(value)
|
|
8
|
+
if defined?(::Oj)
|
|
9
|
+
::Oj.dump(value, mode: :compat)
|
|
10
|
+
else
|
|
11
|
+
::JSON.generate(value)
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def parse(string, max_depth:)
|
|
16
|
+
::JSON.parse(string, max_nesting: max_depth, allow_nan: false)
|
|
17
|
+
rescue ::JSON::NestingError
|
|
18
|
+
raise BadRequest.new("The JSON body is nested too deeply.")
|
|
19
|
+
rescue ::JSON::ParserError
|
|
20
|
+
raise BadRequest.new("The JSON body is malformed.")
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Counts keys and array items so a small body can't expand into a huge
|
|
24
|
+
# structure. Raises when over the limit.
|
|
25
|
+
def check_size!(value, max_keys)
|
|
26
|
+
count = 0
|
|
27
|
+
stack = [value]
|
|
28
|
+
until stack.empty?
|
|
29
|
+
current = stack.pop
|
|
30
|
+
case current
|
|
31
|
+
when Hash
|
|
32
|
+
count += current.size
|
|
33
|
+
stack.concat(current.values)
|
|
34
|
+
when Array
|
|
35
|
+
count += current.size
|
|
36
|
+
stack.concat(current)
|
|
37
|
+
end
|
|
38
|
+
raise BadRequest.new("The JSON body has too many keys or items.") if count > max_keys
|
|
39
|
+
end
|
|
40
|
+
value
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Resolves API classes by name on each request, so Rails code reloading
|
|
3
|
+
# picks up edited API files without restarting the server. Rebuilds the
|
|
4
|
+
# router only when a class was actually reloaded.
|
|
5
|
+
#
|
|
6
|
+
# mount Whoosh.app("OrdersApi", "CustomersApi"), at: "/api"
|
|
7
|
+
class LazyApp
|
|
8
|
+
def initialize(names, **options)
|
|
9
|
+
@names = names.map(&:to_s)
|
|
10
|
+
@options = options
|
|
11
|
+
@mutex = Mutex.new
|
|
12
|
+
@apis = nil
|
|
13
|
+
@app = nil
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def call(env)
|
|
17
|
+
current = @names.map { |n| Object.const_get(n) }
|
|
18
|
+
app = @mutex.synchronize do
|
|
19
|
+
if @apis.nil? || current.zip(@apis).any? { |a, b| !a.equal?(b) }
|
|
20
|
+
@apis = current
|
|
21
|
+
@app = App.new(current, **@options)
|
|
22
|
+
end
|
|
23
|
+
@app
|
|
24
|
+
end
|
|
25
|
+
app.call(env)
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Builds an OpenAPI 3.1 document from endpoint definitions. Named schema
|
|
3
|
+
# classes become reusable components; inline ones are expanded in place.
|
|
4
|
+
class OpenAPI
|
|
5
|
+
def initialize(apis, server_url: nil, title: nil, version: nil)
|
|
6
|
+
@apis = apis
|
|
7
|
+
@server_url = server_url
|
|
8
|
+
@title = title
|
|
9
|
+
@version = version
|
|
10
|
+
@components = {}
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def document
|
|
14
|
+
paths = {}
|
|
15
|
+
@apis.each do |api|
|
|
16
|
+
api.endpoints.each do |endpoint|
|
|
17
|
+
key = endpoint.path.gsub(Endpoint::PATH_PARAM) { "{#{Regexp.last_match(1)}}" }
|
|
18
|
+
(paths[key] ||= {})[endpoint.verb.downcase] = operation(endpoint)
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
info = @apis.map(&:info).reduce({}, :merge)
|
|
23
|
+
doc = {
|
|
24
|
+
"openapi" => "3.1.0",
|
|
25
|
+
"info" => {
|
|
26
|
+
"title" => @title || info["title"] || "API",
|
|
27
|
+
"version" => @version || info["version"] || "1.0.0"
|
|
28
|
+
},
|
|
29
|
+
"paths" => paths,
|
|
30
|
+
"components" => {
|
|
31
|
+
"schemas" => @components.merge("Error" => error_schema),
|
|
32
|
+
"securitySchemes" => { "bearer" => { "type" => "http", "scheme" => "bearer" } }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
doc["info"]["description"] = info["description"] if info["description"]
|
|
36
|
+
doc["servers"] = [{ "url" => @server_url }] if @server_url && !@server_url.empty?
|
|
37
|
+
doc
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def operation(endpoint)
|
|
43
|
+
op = {
|
|
44
|
+
"operationId" => operation_id(endpoint),
|
|
45
|
+
"responses" => responses(endpoint)
|
|
46
|
+
}
|
|
47
|
+
op["summary"] = endpoint.docs[:summary] if endpoint.docs[:summary]
|
|
48
|
+
op["description"] = endpoint.docs[:description] if endpoint.docs[:description]
|
|
49
|
+
op["tags"] = endpoint.docs[:tags] if endpoint.docs[:tags]
|
|
50
|
+
op["deprecated"] = true if endpoint.docs[:deprecated]
|
|
51
|
+
op["security"] = endpoint.public? ? [] : [{ "bearer" => [] }]
|
|
52
|
+
|
|
53
|
+
parameters, body = split_params(endpoint)
|
|
54
|
+
parameters += pagination_parameters(endpoint) if endpoint.pagination
|
|
55
|
+
if endpoint.idempotency
|
|
56
|
+
parameters << { "name" => "Idempotency-Key", "in" => "header", "required" => endpoint.idempotency[:required],
|
|
57
|
+
"schema" => { "type" => "string", "minLength" => 8, "maxLength" => 255 } }
|
|
58
|
+
end
|
|
59
|
+
op["parameters"] = parameters unless parameters.empty?
|
|
60
|
+
if body
|
|
61
|
+
op["requestBody"] = { "required" => body.key?("required"),
|
|
62
|
+
"content" => { "application/json" => { "schema" => body } } }
|
|
63
|
+
end
|
|
64
|
+
op
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Path params go in the path; for GET/DELETE the rest are query params,
|
|
68
|
+
# otherwise they're the JSON body.
|
|
69
|
+
def split_params(endpoint)
|
|
70
|
+
schema = endpoint.params_schema
|
|
71
|
+
return [[], nil] unless schema
|
|
72
|
+
|
|
73
|
+
json = schema.to_json_schema(ref: method(:ref))
|
|
74
|
+
path_names = endpoint.path_params
|
|
75
|
+
parameters = path_names.map do |name|
|
|
76
|
+
{ "name" => name, "in" => "path", "required" => true, "schema" => json["properties"][name] || { "type" => "string" } }
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
rest = json["properties"].reject { |k, _| path_names.include?(k) }
|
|
80
|
+
required = Array(json["required"]) - path_names
|
|
81
|
+
return [parameters, nil] if rest.empty?
|
|
82
|
+
|
|
83
|
+
if %w[GET DELETE].include?(endpoint.verb)
|
|
84
|
+
rest.each do |name, prop|
|
|
85
|
+
parameters << { "name" => name, "in" => "query", "required" => required.include?(name), "schema" => prop }
|
|
86
|
+
end
|
|
87
|
+
[parameters, nil]
|
|
88
|
+
else
|
|
89
|
+
body = { "type" => "object", "properties" => rest }
|
|
90
|
+
body["required"] = required unless required.empty?
|
|
91
|
+
[parameters, body]
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def pagination_parameters(endpoint)
|
|
96
|
+
second = endpoint.pagination.style == :cursor ? { "name" => "cursor", "schema" => { "type" => "string" } } : { "name" => "page", "schema" => { "type" => "integer", "minimum" => 1 } }
|
|
97
|
+
[
|
|
98
|
+
{ "name" => "limit", "in" => "query", "schema" => { "type" => "integer", "minimum" => 1 } },
|
|
99
|
+
second.merge("in" => "query")
|
|
100
|
+
]
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def responses(endpoint)
|
|
104
|
+
out = {}
|
|
105
|
+
if endpoint.no_content?
|
|
106
|
+
out[endpoint.status.to_s] = { "description" => "No content" }
|
|
107
|
+
else
|
|
108
|
+
data = ref(endpoint.returns_schema)
|
|
109
|
+
data = { "type" => "array", "items" => data } if endpoint.many?
|
|
110
|
+
props = { "data" => data }
|
|
111
|
+
if endpoint.pagination
|
|
112
|
+
props["meta"] = { "type" => "object", "properties" => pagination_meta(endpoint) }
|
|
113
|
+
end
|
|
114
|
+
out[endpoint.status.to_s] = {
|
|
115
|
+
"description" => "Success",
|
|
116
|
+
"content" => { "application/json" => { "schema" => { "type" => "object", "properties" => props, "required" => ["data"] } } }
|
|
117
|
+
}
|
|
118
|
+
end
|
|
119
|
+
error_codes(endpoint).each do |code, description|
|
|
120
|
+
out[code] = { "description" => description,
|
|
121
|
+
"content" => { "application/json" => { "schema" => { "$ref" => "#/components/schemas/Error" } } } }
|
|
122
|
+
end
|
|
123
|
+
out
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def pagination_meta(endpoint)
|
|
127
|
+
base = { "limit" => { "type" => "integer" } }
|
|
128
|
+
if endpoint.pagination.style == :cursor
|
|
129
|
+
base.merge("next_cursor" => { "type" => %w[string null] })
|
|
130
|
+
else
|
|
131
|
+
base.merge("page" => { "type" => "integer" }, "next_page" => { "type" => %w[integer null] })
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def error_codes(endpoint)
|
|
136
|
+
codes = {}
|
|
137
|
+
codes["401"] = "Not signed in" unless endpoint.public?
|
|
138
|
+
codes["403"] = "Not allowed" if endpoint.authorizer
|
|
139
|
+
codes["404"] = "Not found" unless endpoint.many? || endpoint.no_content?
|
|
140
|
+
codes["422"] = "Invalid input" if endpoint.params_schema || endpoint.pagination
|
|
141
|
+
codes["429"] = "Rate limited" if endpoint.effective_rate_limit(Whoosh.config)
|
|
142
|
+
codes
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def ref(schema)
|
|
146
|
+
name = schema.schema_name
|
|
147
|
+
return schema.to_json_schema(ref: method(:ref)) if name.nil? || schema.name.nil?
|
|
148
|
+
|
|
149
|
+
key = name.gsub("::", "")
|
|
150
|
+
unless @components.key?(key)
|
|
151
|
+
@components[key] = {} # placeholder stops recursion on self-referencing schemas
|
|
152
|
+
@components[key] = schema.to_json_schema(ref: method(:ref))
|
|
153
|
+
end
|
|
154
|
+
{ "$ref" => "#/components/schemas/#{key}" }
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def operation_id(endpoint)
|
|
158
|
+
parts = endpoint.path.split("/").reject(&:empty?).map { |s| s.start_with?(":") ? "by_#{s[1..]}" : s }
|
|
159
|
+
([endpoint.verb.downcase] + parts).join("_").gsub(/[^a-zA-Z0-9_]/, "_")
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def error_schema
|
|
163
|
+
{
|
|
164
|
+
"type" => "object",
|
|
165
|
+
"required" => ["error"],
|
|
166
|
+
"properties" => {
|
|
167
|
+
"error" => {
|
|
168
|
+
"type" => "object",
|
|
169
|
+
"required" => %w[code message request_id],
|
|
170
|
+
"properties" => {
|
|
171
|
+
"code" => { "type" => "string" },
|
|
172
|
+
"message" => { "type" => "string" },
|
|
173
|
+
"details" => { "type" => "object" },
|
|
174
|
+
"request_id" => { "type" => "string" }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
end
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Pagination without COUNT(*).
|
|
3
|
+
#
|
|
4
|
+
# :cursor (default) - keyset pagination on a unique, ordered column.
|
|
5
|
+
# Query: ?limit=25&cursor=<opaque>. Stable under inserts and fast at any depth.
|
|
6
|
+
# :offset - ?limit=25&page=2, for small tables and admin-style UIs.
|
|
7
|
+
#
|
|
8
|
+
# Works with Active Record relations and plain arrays.
|
|
9
|
+
class Pagination
|
|
10
|
+
Page = Struct.new(:records, :meta)
|
|
11
|
+
|
|
12
|
+
attr_reader :style, :by, :order
|
|
13
|
+
|
|
14
|
+
def initialize(style = :cursor, by: :id, order: :asc)
|
|
15
|
+
raise DefinitionError, "paginate: style must be :cursor or :offset" unless %i[cursor offset].include?(style)
|
|
16
|
+
raise DefinitionError, "paginate: order must be :asc or :desc" unless %i[asc desc].include?(order)
|
|
17
|
+
|
|
18
|
+
@style = style
|
|
19
|
+
@by = by.to_sym
|
|
20
|
+
@order = order
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def query_fields
|
|
24
|
+
style == :cursor ? %w[limit cursor] : %w[limit page]
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def call(collection, query, config)
|
|
28
|
+
limit = parse_limit(query["limit"], config)
|
|
29
|
+
style == :cursor ? cursor_page(collection, query["cursor"], limit) : offset_page(collection, query["page"], limit)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
private
|
|
33
|
+
|
|
34
|
+
def parse_limit(value, config)
|
|
35
|
+
return config.default_page_size if value.nil? || value == ""
|
|
36
|
+
|
|
37
|
+
limit = Types.integer(value)
|
|
38
|
+
raise Types::Invalid, "must be between 1 and #{config.max_page_size}" unless limit.between?(1, config.max_page_size)
|
|
39
|
+
|
|
40
|
+
limit
|
|
41
|
+
rescue Types::Invalid => e
|
|
42
|
+
raise ValidationError.new({ "limit" => [e.message] })
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def cursor_page(collection, cursor, limit)
|
|
46
|
+
after = decode_cursor(cursor)
|
|
47
|
+
rows =
|
|
48
|
+
if relation?(collection)
|
|
49
|
+
rel = collection.reorder(by => order)
|
|
50
|
+
if after
|
|
51
|
+
column = collection.klass.arel_table[by]
|
|
52
|
+
rel = rel.where(order == :asc ? column.gt(after) : column.lt(after))
|
|
53
|
+
end
|
|
54
|
+
rel.limit(limit + 1).to_a
|
|
55
|
+
else
|
|
56
|
+
list = Array(collection).sort_by { |r| value_of(r) }
|
|
57
|
+
list.reverse! if order == :desc
|
|
58
|
+
list = list.select { |r| order == :asc ? value_of(r) > after : value_of(r) < after } if after
|
|
59
|
+
list.first(limit + 1)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
more = rows.size > limit
|
|
63
|
+
rows = rows.first(limit)
|
|
64
|
+
next_cursor = more && rows.any? ? encode_cursor(value_of(rows.last)) : nil
|
|
65
|
+
Page.new(rows, { "limit" => limit, "next_cursor" => next_cursor })
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def offset_page(collection, page, limit)
|
|
69
|
+
page = page.nil? || page == "" ? 1 : Types.integer(page)
|
|
70
|
+
raise Types::Invalid, "must be 1 or more" if page < 1 || page > 10_000
|
|
71
|
+
|
|
72
|
+
offset = (page - 1) * limit
|
|
73
|
+
rows = if relation?(collection) then collection.offset(offset).limit(limit + 1).to_a
|
|
74
|
+
else Array(collection)[offset, limit + 1] || []
|
|
75
|
+
end
|
|
76
|
+
more = rows.size > limit
|
|
77
|
+
Page.new(rows.first(limit), { "limit" => limit, "page" => page, "next_page" => more ? page + 1 : nil })
|
|
78
|
+
rescue Types::Invalid => e
|
|
79
|
+
raise ValidationError.new({ "page" => [e.message] })
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def relation?(collection)
|
|
83
|
+
collection.respond_to?(:klass) && collection.respond_to?(:reorder) && collection.respond_to?(:where)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def value_of(record)
|
|
87
|
+
record.is_a?(Hash) ? (record[by] || record[by.to_s]) : record.public_send(by)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def encode_cursor(value)
|
|
91
|
+
# Times keep their full precision; JSON alone would cut them to whole seconds.
|
|
92
|
+
payload = value.is_a?(Time) ? ["t", value.iso8601(9)] : [value]
|
|
93
|
+
[::JSON.generate(payload)].pack("m0").tr("+/", "-_").delete("=") # urlsafe base64; the base64 gem left stdlib in 3.4
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def decode_cursor(cursor)
|
|
97
|
+
return nil if cursor.nil? || cursor == ""
|
|
98
|
+
raise ArgumentError if cursor.length > 512
|
|
99
|
+
|
|
100
|
+
payload = ::JSON.parse(cursor.tr("-_", "+/").unpack1("m"))
|
|
101
|
+
value = payload.length == 2 && payload[0] == "t" ? Time.iso8601(payload[1]) : payload.first
|
|
102
|
+
raise ArgumentError unless value.is_a?(Integer) || value.is_a?(String) || value.is_a?(Time)
|
|
103
|
+
|
|
104
|
+
value
|
|
105
|
+
rescue ArgumentError, TypeError, ::JSON::ParserError, NoMethodError
|
|
106
|
+
raise ValidationError.new({ "cursor" => ["is invalid"] })
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
class Railtie < ::Rails::Railtie
|
|
3
|
+
initializer "whoosh.defaults" do
|
|
4
|
+
Whoosh.config.logger ||= Rails.logger
|
|
5
|
+
Whoosh.config.expose_errors = true if Rails.env.development?
|
|
6
|
+
end
|
|
7
|
+
|
|
8
|
+
config.after_initialize do
|
|
9
|
+
# Share rate limits and idempotency keys across Puma workers and hosts.
|
|
10
|
+
if Whoosh.config.store.is_a?(Whoosh::Stores::Memory) && !Rails.env.test? && Rails.cache
|
|
11
|
+
Whoosh.config.store = Whoosh::Stores::Cache.new(Rails.cache)
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
generators do
|
|
16
|
+
require "generators/whoosh/install/install_generator"
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# Fixed-window rate limiting, keyed by endpoint and client (the signed-in
|
|
3
|
+
# user when there is one, otherwise the IP address).
|
|
4
|
+
class RateLimiter
|
|
5
|
+
Result = Struct.new(:limit, :remaining, :reset_in)
|
|
6
|
+
|
|
7
|
+
def initialize(store, clock: -> { Time.now.to_i })
|
|
8
|
+
@store = store
|
|
9
|
+
@clock = clock
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Returns a Result, or raises TooManyRequests.
|
|
13
|
+
def check!(scope, client, limit:, per:)
|
|
14
|
+
now = @clock.call
|
|
15
|
+
window = now / per
|
|
16
|
+
reset_in = per - (now % per)
|
|
17
|
+
count = @store.increment("rl:#{scope}:#{client}:#{window}", ttl: per + 1)
|
|
18
|
+
remaining = [limit - count, 0].max
|
|
19
|
+
|
|
20
|
+
if count > limit
|
|
21
|
+
raise TooManyRequests.new(headers: {
|
|
22
|
+
"retry-after" => reset_in.to_s,
|
|
23
|
+
"x-ratelimit-limit" => limit.to_s,
|
|
24
|
+
"x-ratelimit-remaining" => "0"
|
|
25
|
+
})
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
Result.new(limit, remaining, reset_in)
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
module Whoosh
|
|
2
|
+
# A thin, lazy wrapper over the Rack env. Reads and parses only what an
|
|
3
|
+
# endpoint needs, and enforces body size and content-type rules.
|
|
4
|
+
class Request
|
|
5
|
+
SAFE_REQUEST_ID = /\A[\w\-.:]{1,128}\z/
|
|
6
|
+
JSON_TYPE = %r{\Aapplication/([\w.+-]+\+)?json\s*(;|\z)}i
|
|
7
|
+
|
|
8
|
+
attr_reader :env
|
|
9
|
+
attr_accessor :user_id_for_limits
|
|
10
|
+
|
|
11
|
+
def initialize(env, config = Whoosh.config)
|
|
12
|
+
@env = env
|
|
13
|
+
@config = config
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def request_method = @env["REQUEST_METHOD"].to_s.upcase
|
|
17
|
+
def head? = request_method == "HEAD"
|
|
18
|
+
def https? = @env["rack.url_scheme"] == "https" || @env["HTTP_X_FORWARDED_PROTO"] == "https"
|
|
19
|
+
|
|
20
|
+
# Path relative to where the app is mounted (Rails/Sinatra strip the
|
|
21
|
+
# mount point into SCRIPT_NAME).
|
|
22
|
+
def path
|
|
23
|
+
@path ||= begin
|
|
24
|
+
p = @env["PATH_INFO"].to_s
|
|
25
|
+
p = "/#{p}" unless p.start_with?("/")
|
|
26
|
+
p.length > 1 ? p.chomp("/") : p
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def script_name = @env["SCRIPT_NAME"].to_s
|
|
31
|
+
|
|
32
|
+
def header(name)
|
|
33
|
+
key = name.to_s.upcase.tr("-", "_")
|
|
34
|
+
return @env["CONTENT_TYPE"] if key == "CONTENT_TYPE"
|
|
35
|
+
return @env["CONTENT_LENGTH"] if key == "CONTENT_LENGTH"
|
|
36
|
+
|
|
37
|
+
@env["HTTP_#{key}"]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def origin = header("origin")
|
|
41
|
+
def content_type = @env["CONTENT_TYPE"].to_s
|
|
42
|
+
|
|
43
|
+
def request_id
|
|
44
|
+
@request_id ||= begin
|
|
45
|
+
incoming = header(@config.request_id_header) || @env["action_dispatch.request_id"]
|
|
46
|
+
incoming.is_a?(String) && incoming.match?(SAFE_REQUEST_ID) ? incoming : SecureRandom.uuid
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Client address. Trusts Rails' RemoteIp result when mounted in Rails,
|
|
51
|
+
# otherwise the socket address; never reads X-Forwarded-For directly.
|
|
52
|
+
def ip
|
|
53
|
+
(@env["action_dispatch.remote_ip"] || @env["REMOTE_ADDR"]).to_s
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# "Authorization: Bearer <token>" -> "<token>"
|
|
57
|
+
def bearer_token
|
|
58
|
+
value = header("authorization").to_s
|
|
59
|
+
match = value.match(/\ABearer\s+([A-Za-z0-9\-._~+\/]+=*)\s*\z/)
|
|
60
|
+
match && match[1]
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Query string as a Hash. `a=1&b[]=2&b[]=3` -> {"a"=>"1", "b"=>["2","3"]}.
|
|
64
|
+
# Bracketed keys other than [] aren't expanded into nested hashes.
|
|
65
|
+
def query
|
|
66
|
+
@query ||= begin
|
|
67
|
+
out = {}
|
|
68
|
+
qs = @env["QUERY_STRING"].to_s
|
|
69
|
+
raise BadRequest.new("The query string is too long.") if qs.bytesize > 16_384
|
|
70
|
+
|
|
71
|
+
URI.decode_www_form(qs).each do |key, value|
|
|
72
|
+
if key.end_with?("[]")
|
|
73
|
+
(out[key.delete_suffix("[]")] ||= []) << value
|
|
74
|
+
else
|
|
75
|
+
out[key] = value
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
raise BadRequest.new("The query string has too many parameters.") if out.size > 200
|
|
79
|
+
|
|
80
|
+
out
|
|
81
|
+
rescue ArgumentError
|
|
82
|
+
raise BadRequest.new("The query string is malformed.")
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def raw_body
|
|
87
|
+
return @raw_body if defined?(@raw_body)
|
|
88
|
+
|
|
89
|
+
max = @config.max_body_size
|
|
90
|
+
length = @env["CONTENT_LENGTH"].to_s
|
|
91
|
+
raise PayloadTooLarge if length.match?(/\A\d+\z/) && length.to_i > max
|
|
92
|
+
|
|
93
|
+
input = @env["rack.input"]
|
|
94
|
+
body = input ? input.read(max + 1).to_s : ""
|
|
95
|
+
input.rewind if input.respond_to?(:rewind)
|
|
96
|
+
raise PayloadTooLarge if body.bytesize > max
|
|
97
|
+
|
|
98
|
+
@raw_body = body
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Parsed JSON body. Must be an object. Empty bodies parse as {}.
|
|
102
|
+
def json
|
|
103
|
+
return @json if defined?(@json)
|
|
104
|
+
|
|
105
|
+
body = raw_body
|
|
106
|
+
if body.strip.empty?
|
|
107
|
+
@json = {}
|
|
108
|
+
else
|
|
109
|
+
raise UnsupportedMediaType unless content_type.match?(JSON_TYPE)
|
|
110
|
+
|
|
111
|
+
parsed = Whoosh::JSON.parse(body, max_depth: @config.max_json_depth)
|
|
112
|
+
raise BadRequest.new("The JSON body must be an object.") unless parsed.is_a?(Hash)
|
|
113
|
+
|
|
114
|
+
@json = Whoosh::JSON.check_size!(parsed, @config.max_json_keys)
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def body? = %w[POST PUT PATCH DELETE].include?(request_method)
|
|
119
|
+
end
|
|
120
|
+
end
|