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.
@@ -0,0 +1,90 @@
1
+ module Whoosh
2
+ # A segment tree built once at boot. Static segments win over parameters,
3
+ # so `/orders/stats` and `/orders/:id` can coexist.
4
+ class Router
5
+ Node = Struct.new(:static, :param_name, :param_node, :endpoints) do
6
+ def initialize = super({}, nil, nil, {})
7
+ end
8
+
9
+ PARAM_VALUE = %r{\A[^/]{1,512}\z}
10
+
11
+ def initialize
12
+ @root = Node.new
13
+ end
14
+
15
+ def add(verb, path, endpoint)
16
+ node = @root
17
+ segments(path).each do |segment|
18
+ if segment.start_with?(":")
19
+ name = segment.delete_prefix(":")
20
+ if node.param_node && node.param_name != name
21
+ raise DefinitionError, "#{verb} #{path}: :#{name} conflicts with :#{node.param_name} at the same position"
22
+ end
23
+ node.param_name = name
24
+ node = (node.param_node ||= Node.new)
25
+ else
26
+ node = (node.static[segment] ||= Node.new)
27
+ end
28
+ end
29
+ if node.endpoints.key?(verb)
30
+ raise DefinitionError, "#{verb} #{path} is defined twice"
31
+ end
32
+
33
+ node.endpoints[verb] = endpoint
34
+ end
35
+
36
+ # Returns [endpoint, path_params], [:method_not_allowed, allowed_verbs] or nil.
37
+ def match(verb, path)
38
+ params = {}
39
+ node = find(@root, segments(path), 0, params)
40
+ return nil unless node && !node.endpoints.empty?
41
+
42
+ verb = "GET" if verb == "HEAD"
43
+ endpoint = node.endpoints[verb]
44
+ endpoint ? [endpoint, params] : [:method_not_allowed, node.endpoints.keys]
45
+ end
46
+
47
+ def routes
48
+ collect(@root, "", [])
49
+ end
50
+
51
+ private
52
+
53
+ def find(node, segs, index, params)
54
+ return(node.endpoints.empty? ? nil : node) if index == segs.size
55
+
56
+ segment = segs[index]
57
+ if (child = node.static[segment]) && (found = find(child, segs, index + 1, params))
58
+ return found
59
+ end
60
+ if node.param_node && segment.match?(PARAM_VALUE)
61
+ found = find(node.param_node, segs, index + 1, params)
62
+ if found
63
+ params[node.param_name] = unescape(segment)
64
+ return found
65
+ end
66
+ end
67
+ nil
68
+ end
69
+
70
+ def unescape(segment)
71
+ return segment unless segment.include?("%")
72
+
73
+ value = URI.decode_www_form_component(segment.gsub("+", "%2B"))
74
+ value.valid_encoding? ? value : segment
75
+ rescue ArgumentError
76
+ segment
77
+ end
78
+
79
+ def segments(path)
80
+ path.to_s.split("/").reject(&:empty?)
81
+ end
82
+
83
+ def collect(node, prefix, out)
84
+ node.endpoints.each { |verb, ep| out << [verb, prefix.empty? ? "/" : prefix, ep] }
85
+ node.static.each { |seg, child| collect(child, "#{prefix}/#{seg}", out) }
86
+ collect(node.param_node, "#{prefix}/:#{node.param_name}", out) if node.param_node
87
+ out
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,375 @@
1
+ module Whoosh
2
+ # Describes the shape of input or output. The same schema validates and
3
+ # coerces request input, serializes responses (only declared fields ever
4
+ # leave the server), and documents both in OpenAPI.
5
+ #
6
+ # class LineItemSchema < Whoosh::Schema
7
+ # field :product_id, :integer, required: true
8
+ # field :quantity, :integer, required: true, min: 1, max: 999
9
+ # end
10
+ #
11
+ # class OrderSchema < Whoosh::Schema
12
+ # field :id, :integer
13
+ # field :number, :string
14
+ # field :total, :decimal
15
+ # field :status, :string, enum: %w[pending paid cancelled]
16
+ # field :customer, CustomerSchema
17
+ # field :items, :array, of: LineItemSchema, from: :line_items
18
+ # end
19
+ class Schema
20
+ # Largest array accepted on input when a field doesn't set max_items.
21
+ DEFAULT_MAX_ITEMS = 100
22
+ FIELD_OPTIONS = %i[required default nullable enum min max min_length max_length min_items max_items
23
+ format of from description example deprecated].freeze
24
+
25
+ class Field
26
+ attr_reader :name, :key, :type, :schema, :options
27
+
28
+ def initialize(name, type, options)
29
+ @name = name.to_sym
30
+ @key = name.to_s
31
+ @options = options
32
+ if type.is_a?(Class) && type <= Schema
33
+ @type = :object
34
+ @schema = type
35
+ else
36
+ @type = type.to_sym
37
+ @schema = options[:schema]
38
+ end
39
+ end
40
+
41
+ def required? = !!options[:required]
42
+ def nullable? = !!options[:nullable]
43
+ def default? = options.key?(:default)
44
+
45
+ def default
46
+ value = options[:default]
47
+ value.respond_to?(:call) ? value.call : value
48
+ end
49
+
50
+ def item_type = options[:of]
51
+ def item_schema? = item_type.is_a?(Class) && item_type <= Schema
52
+ end
53
+
54
+ class << self
55
+ def fields
56
+ @fields ||= {}
57
+ end
58
+
59
+ def inherited(subclass)
60
+ super
61
+ subclass.instance_variable_set(:@fields, fields.dup)
62
+ subclass.instance_variable_set(:@reject_unknown, @reject_unknown)
63
+ end
64
+
65
+ # Build an anonymous schema from a block.
66
+ def build(name = nil, &block)
67
+ klass = Class.new(self)
68
+ klass.instance_variable_set(:@anonymous_name, name)
69
+ klass.class_eval(&block) if block
70
+ klass
71
+ end
72
+
73
+ def schema_name
74
+ name || @anonymous_name
75
+ end
76
+
77
+ # field :email, :email, required: true
78
+ # field :address, :object do
79
+ # field :city, :string
80
+ # end
81
+ # field :tags, :array, of: :string, max_items: 10
82
+ def field(name, type = :string, **options, &block)
83
+ unknown = options.keys - FIELD_OPTIONS - [:schema]
84
+ raise DefinitionError, "#{self.name || 'Schema'}.#{name}: unknown option(s) #{unknown.join(', ')}" if unknown.any?
85
+
86
+ if block
87
+ nested = Schema.build("#{schema_name}#{name.to_s.split('_').map(&:capitalize).join}", &block)
88
+ if type.to_sym == :array
89
+ options = options.merge(of: nested)
90
+ else
91
+ type = nested
92
+ end
93
+ end
94
+ validate_type!(name, type, options)
95
+ fields[name.to_sym] = Field.new(name, type, options)
96
+ end
97
+
98
+ def required(name, type = :string, **options, &block)
99
+ field(name, type, **options, required: true, &block)
100
+ end
101
+
102
+ def optional(name, type = :string, **options, &block)
103
+ field(name, type, **options, required: false, &block)
104
+ end
105
+
106
+ # Respond 422 when the input has keys the schema doesn't declare.
107
+ # By default unknown keys are silently dropped.
108
+ def reject_unknown!
109
+ @reject_unknown = true
110
+ end
111
+
112
+ def reject_unknown? = !!@reject_unknown
113
+
114
+ # ---- input -----------------------------------------------------------
115
+
116
+ # Validates and coerces a Hash of input. Returns a frozen Hash with
117
+ # symbol keys, or raises ValidationError with every problem found.
118
+ def parse(input)
119
+ errors = {}
120
+ result = parse_object(input, "", errors)
121
+ raise ValidationError.new(errors) unless errors.empty?
122
+
123
+ result
124
+ end
125
+
126
+ def parse_object(input, path, errors)
127
+ unless input.is_a?(Hash)
128
+ add_error(errors, path, "must be an object")
129
+ return nil
130
+ end
131
+
132
+ if reject_unknown?
133
+ (input.keys.map(&:to_s) - fields.keys.map(&:to_s)).each do |key|
134
+ add_error(errors, join(path, key), "is not allowed")
135
+ end
136
+ end
137
+
138
+ result = {}
139
+ fields.each_value do |field|
140
+ present = input.key?(field.key) || input.key?(field.name)
141
+ raw = input.key?(field.key) ? input[field.key] : input[field.name]
142
+
143
+ unless present
144
+ if field.default? then result[field.name] = field.default
145
+ elsif field.required? then add_error(errors, join(path, field.key), "is required")
146
+ end
147
+ next
148
+ end
149
+
150
+ if raw.nil? || (raw == "" && field.type != :string && field.type != :text)
151
+ if field.nullable? || (!field.required? && raw.nil?)
152
+ result[field.name] = nil if field.nullable?
153
+ else
154
+ add_error(errors, join(path, field.key), field.required? ? "is required" : "can't be null")
155
+ end
156
+ next
157
+ end
158
+
159
+ value = parse_value(field, raw, join(path, field.key), errors)
160
+ result[field.name] = value unless value.equal?(INVALID)
161
+ end
162
+ result.freeze
163
+ end
164
+
165
+ INVALID = Object.new.freeze
166
+
167
+ def parse_value(field, raw, path, errors)
168
+ value =
169
+ case field.type
170
+ when :object
171
+ return parse_nested(field.schema, raw, path, errors)
172
+ when :array
173
+ return parse_array(field, raw, path, errors)
174
+ else
175
+ Types.coerce(field.type, raw)
176
+ end
177
+ check_constraints(field, value, path, errors)
178
+ rescue Types::Invalid => e
179
+ add_error(errors, path, e.message)
180
+ INVALID
181
+ end
182
+
183
+ def parse_nested(schema, raw, path, errors)
184
+ before = errors.size
185
+ value = schema.parse_object(raw, path, errors)
186
+ errors.size == before ? value : INVALID
187
+ end
188
+
189
+ def parse_array(field, raw, path, errors)
190
+ raw = raw.values if raw.is_a?(Hash) && raw.keys.all? { |k| k.to_s.match?(/\A\d+\z/) } # form-style a[0]=..
191
+ unless raw.is_a?(Array)
192
+ add_error(errors, path, "must be a list")
193
+ return INVALID
194
+ end
195
+ max = field.options.fetch(:max_items, DEFAULT_MAX_ITEMS)
196
+ min = field.options[:min_items]
197
+ add_error(errors, path, "must have at most #{max} items") if raw.size > max
198
+ add_error(errors, path, "must have at least #{min} items") if min && raw.size < min
199
+ return INVALID if raw.size > max
200
+
201
+ before = errors.size
202
+ items = raw.each_with_index.map do |item, i|
203
+ item_path = "#{path}[#{i}]"
204
+ if field.item_schema?
205
+ field.item_type.parse_object(item, item_path, errors)
206
+ elsif field.item_type
207
+ begin
208
+ value = Types.coerce(field.item_type.to_sym, item)
209
+ check_constraints(field, value, item_path, errors, item: true)
210
+ rescue Types::Invalid => e
211
+ add_error(errors, item_path, e.message)
212
+ nil
213
+ end
214
+ else
215
+ raise DefinitionError, "#{schema_name}.#{field.name}: arrays need `of:` (a type or a schema)"
216
+ end
217
+ end
218
+ errors.size == before ? items.freeze : INVALID
219
+ end
220
+
221
+ def check_constraints(field, value, path, errors, item: false)
222
+ opts = field.options
223
+ enum = opts[:enum]
224
+ if enum && !enum.map(&:to_s).include?(value.to_s)
225
+ add_error(errors, path, "must be one of: #{enum.join(', ')}")
226
+ return INVALID
227
+ end
228
+
229
+ if value.is_a?(String)
230
+ max = opts[:max_length] || Types::DEFAULT_MAX_STRING
231
+ add_error(errors, path, "must be at most #{max} characters") if value.length > max
232
+ add_error(errors, path, "must be at least #{opts[:min_length]} characters") if opts[:min_length] && value.length < opts[:min_length]
233
+ add_error(errors, path, "has an invalid format") if opts[:format] && !value.match?(opts[:format])
234
+ elsif value.is_a?(Numeric)
235
+ add_error(errors, path, "must be at least #{opts[:min]}") if opts[:min] && value < opts[:min]
236
+ add_error(errors, path, "must be at most #{opts[:max]}") if opts[:max] && value > opts[:max]
237
+ end
238
+ _ = item
239
+ value
240
+ end
241
+
242
+ # ---- output ----------------------------------------------------------
243
+
244
+ # Serializes an object (or Hash) into a Hash with only the declared
245
+ # fields. Reads attributes with public_send, or `from:` (a method name
246
+ # or ->(object) { ... }).
247
+ def dump(object)
248
+ return nil if object.nil?
249
+
250
+ fields.each_value.with_object({}) do |field, out|
251
+ out[field.key] = dump_value(field, read(object, field))
252
+ end
253
+ end
254
+
255
+ def dump_many(objects)
256
+ objects.map { |o| dump(o) }
257
+ end
258
+
259
+ def read(object, field)
260
+ source = field.options[:from] || field.name
261
+ return source.call(object) if source.respond_to?(:call)
262
+
263
+ if object.is_a?(Hash)
264
+ object.fetch(source.to_s) { object[source.to_sym] }
265
+ elsif object.respond_to?(source)
266
+ object.public_send(source)
267
+ end
268
+ end
269
+
270
+ def dump_value(field, value)
271
+ return nil if value.nil?
272
+
273
+ case field.type
274
+ when :object then field.schema ? field.schema.dump(value) : Types.plain(value)
275
+ when :array
276
+ list = value.respond_to?(:to_a) ? value.to_a : Array(value)
277
+ if field.item_schema? then list.map { |v| field.item_type.dump(v) }
278
+ else list.map { |v| Types.dump(field.item_type&.to_sym || :json, v) }
279
+ end
280
+ else Types.dump(field.type, value)
281
+ end
282
+ end
283
+
284
+ # ---- OpenAPI ---------------------------------------------------------
285
+
286
+ def to_json_schema(ref: nil)
287
+ properties = {}
288
+ required = []
289
+ fields.each_value do |field|
290
+ properties[field.key] = field_json_schema(field, ref)
291
+ required << field.key if field.required?
292
+ end
293
+ schema = { "type" => "object", "properties" => properties }
294
+ schema["required"] = required unless required.empty?
295
+ schema["additionalProperties"] = false if reject_unknown?
296
+ schema
297
+ end
298
+
299
+ private
300
+
301
+ def field_json_schema(field, ref)
302
+ schema =
303
+ case field.type
304
+ when :object
305
+ field.schema ? schema_ref(field.schema, ref) : { "type" => "object" }
306
+ when :array
307
+ items = if field.item_schema? then schema_ref(field.item_type, ref)
308
+ elsif field.item_type then scalar_json_schema(field.item_type.to_sym)
309
+ else {}
310
+ end
311
+ { "type" => "array", "items" => items, "maxItems" => field.options.fetch(:max_items, DEFAULT_MAX_ITEMS) }
312
+ else
313
+ scalar_json_schema(field.type)
314
+ end
315
+ o = field.options
316
+ schema = schema.merge("enum" => o[:enum].map(&:to_s)) if o[:enum]
317
+ schema["minimum"] = o[:min] if o[:min]
318
+ schema["maximum"] = o[:max] if o[:max]
319
+ schema["minLength"] = o[:min_length] if o[:min_length]
320
+ schema["maxLength"] = o[:max_length] if o[:max_length]
321
+ schema["minItems"] = o[:min_items] if o[:min_items]
322
+ schema["description"] = o[:description] if o[:description]
323
+ schema["example"] = o[:example] if o.key?(:example)
324
+ schema["deprecated"] = true if o[:deprecated]
325
+ schema["default"] = o[:default] if o.key?(:default) && !o[:default].respond_to?(:call)
326
+ schema = { "anyOf" => [schema, { "type" => "null" }] } if field.nullable? && schema.key?("$ref")
327
+ schema["type"] = [schema["type"], "null"] if field.nullable? && schema["type"].is_a?(String)
328
+ schema
329
+ end
330
+
331
+ def schema_ref(schema, ref)
332
+ ref ? ref.call(schema) : schema.to_json_schema
333
+ end
334
+
335
+ def scalar_json_schema(type)
336
+ case type
337
+ when :string, :text then { "type" => "string" }
338
+ when :integer then { "type" => "integer" }
339
+ when :float then { "type" => "number" }
340
+ when :decimal then { "type" => "string", "format" => "decimal" }
341
+ when :boolean then { "type" => "boolean" }
342
+ when :date then { "type" => "string", "format" => "date" }
343
+ when :datetime, :time then { "type" => "string", "format" => "date-time" }
344
+ when :uuid then { "type" => "string", "format" => "uuid" }
345
+ when :email then { "type" => "string", "format" => "email" }
346
+ when :url then { "type" => "string", "format" => "uri" }
347
+ else {}
348
+ end
349
+ end
350
+
351
+ def validate_type!(name, type, options)
352
+ return if type.is_a?(Class) && type <= Schema
353
+
354
+ sym = type.to_sym
355
+ unless Types::NAMES.include?(sym)
356
+ raise DefinitionError, "#{schema_name || 'Schema'}.#{name}: unknown type #{type.inspect}. " \
357
+ "Use one of #{Types::NAMES.join(', ')} or a Whoosh::Schema subclass"
358
+ end
359
+ if sym == :array && options[:of].nil?
360
+ raise DefinitionError, "#{schema_name || 'Schema'}.#{name}: arrays need `of:` (a type or a schema)"
361
+ end
362
+ if sym == :object && options[:schema].nil?
363
+ raise DefinitionError, "#{schema_name || 'Schema'}.#{name}: give objects a schema (a block or a Schema class), " \
364
+ "or use :json for free-form data"
365
+ end
366
+ end
367
+
368
+ def join(path, key) = path.empty? ? key.to_s : "#{path}.#{key}"
369
+
370
+ def add_error(errors, path, message)
371
+ (errors[path.empty? ? "base" : path] ||= []) << message
372
+ end
373
+ end
374
+ end
375
+ end
@@ -0,0 +1,40 @@
1
+ module Whoosh
2
+ module Stores
3
+ # Adapts an ActiveSupport::Cache store (Rails.cache: Solid Cache, Redis,
4
+ # Memcached) so limits and idempotency keys are shared across processes.
5
+ #
6
+ # config.store = Whoosh::Stores::Cache.new(Rails.cache)
7
+ class Cache
8
+ def initialize(cache, namespace: "whoosh")
9
+ @cache = cache
10
+ @namespace = namespace
11
+ end
12
+
13
+ def increment(key, ttl:)
14
+ k = namespaced(key)
15
+ count = @cache.increment(k, 1, expires_in: ttl)
16
+ return count if count
17
+
18
+ # Some stores return nil for a missing key; seed it and retry.
19
+ @cache.write(k, 1, expires_in: ttl, unless_exist: true, raw: true)
20
+ @cache.increment(k, 1, expires_in: ttl) || 1
21
+ end
22
+
23
+ def read(key) = @cache.read(namespaced(key))
24
+
25
+ def write(key, value, ttl:)
26
+ @cache.write(namespaced(key), value, expires_in: ttl)
27
+ end
28
+
29
+ def write_unless_exists(key, value, ttl:)
30
+ !!@cache.write(namespaced(key), value, expires_in: ttl, unless_exist: true)
31
+ end
32
+
33
+ def delete(key) = @cache.delete(namespaced(key))
34
+
35
+ private
36
+
37
+ def namespaced(key) = "#{@namespace}:#{key}"
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,76 @@
1
+ module Whoosh
2
+ module Stores
3
+ # In-process store for rate limits and idempotency keys. Fine for one
4
+ # process; use Stores::Cache with a shared cache when you run several.
5
+ class Memory
6
+ def initialize(clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
7
+ @data = {}
8
+ @mutex = Mutex.new
9
+ @clock = clock
10
+ @writes = 0
11
+ end
12
+
13
+ def increment(key, ttl:)
14
+ @mutex.synchronize do
15
+ prune
16
+ entry = live(key)
17
+ count = (entry ? entry[0] : 0) + 1
18
+ @data[key] = [count, entry ? entry[1] : now + ttl]
19
+ count
20
+ end
21
+ end
22
+
23
+ def read(key)
24
+ @mutex.synchronize { live(key)&.first }
25
+ end
26
+
27
+ def write(key, value, ttl:)
28
+ @mutex.synchronize do
29
+ prune
30
+ @data[key] = [value, now + ttl]
31
+ end
32
+ true
33
+ end
34
+
35
+ # Atomic "set if absent". Returns true when this call wrote the value.
36
+ def write_unless_exists(key, value, ttl:)
37
+ @mutex.synchronize do
38
+ return false if live(key)
39
+
40
+ @data[key] = [value, now + ttl]
41
+ true
42
+ end
43
+ end
44
+
45
+ def delete(key)
46
+ @mutex.synchronize { @data.delete(key) }
47
+ true
48
+ end
49
+
50
+ def clear
51
+ @mutex.synchronize { @data.clear }
52
+ end
53
+
54
+ private
55
+
56
+ def now = @clock.call
57
+
58
+ def live(key)
59
+ entry = @data[key]
60
+ return nil unless entry
61
+ return entry if entry[1] > now
62
+
63
+ @data.delete(key)
64
+ nil
65
+ end
66
+
67
+ def prune
68
+ @writes += 1
69
+ return unless (@writes % 1000).zero?
70
+
71
+ t = now
72
+ @data.delete_if { |_, (_, expires)| expires <= t }
73
+ end
74
+ end
75
+ end
76
+ end