restep 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,469 @@
1
+ module Restep
2
+ # Reserved parameters (§5.3) and the query profile (§6): parsing, errors in order, and SQL.
3
+ class Query
4
+ RESERVED = %w[filter sort fields include count limit cursor since languages].freeze
5
+ MAX_IN = 500
6
+ SQL_OPS = { "eq" => "=", "ne" => "<>", "lt" => "<", "le" => "<=", "gt" => ">", "ge" => ">=" }.freeze
7
+
8
+ Filter = Struct.new(:field, :op, :value, :raw, :name, keyword_init: true)
9
+ Named = Struct.new(:name, :value, :raw, keyword_init: true)
10
+
11
+ attr_reader :collection, :filters, :named, :sort, :fields, :limit, :count, :cursor_payload, :pairs
12
+
13
+ # kind: :root, :collection or :item; method: the request's.
14
+ def initialize(collection, kind, method, pairs)
15
+ @collection, @kind, @method, @pairs = collection, kind, method, pairs
16
+ @filters, @named, @sort, @fields = [], [], [], nil
17
+ @switched_off = [] # default switches the request turns off with filter[name]=false (§6.1)
18
+ @limit = collection&.default_limit
19
+ @count = false
20
+ @issues = [] # [category (0 unsupported, 1 invalid), position, name, detail]
21
+ analyze
22
+ end
23
+
24
+ def supported
25
+ safe = %w[GET HEAD].include?(@method)
26
+ return [] unless safe
27
+ case @kind
28
+ when :collection then %w[filter sort fields limit cursor count]
29
+ when :item, :singleton then %w[fields]
30
+ else []
31
+ end
32
+ end
33
+
34
+ def unsupported(i, name, detail) = @issues << [0, i, name, detail]
35
+ def invalid(i, name, detail) = @issues << [1, i, name, detail]
36
+
37
+ def analyze
38
+ sup = supported
39
+ seen = {}
40
+ raw_cursor = nil
41
+ @pairs.each_with_index do |p, i|
42
+ name = p.name
43
+ base = name[/\A[^\[]*/]
44
+ # §5.3 and §11.1 (draft 7): a GET action without params is one with "params": {}, so it
45
+ # answers any query parameter, reserved or not, with unsupported_parameter. This gem does
46
+ # not declare params, so that is every GET action.
47
+ if get_action?
48
+ unsupported(i, name, "The #{name} parameter is not declared: this action takes no query parameters.")
49
+ next
50
+ end
51
+ next unless RESERVED.include?(base) || name.start_with?("$")
52
+ if name.start_with?("$") || !sup.include?(base)
53
+ unsupported(i, name, unsupported_detail(base))
54
+ next
55
+ end
56
+ if base == "filter"
57
+ analyze_filter(p, i, seen)
58
+ next
59
+ end
60
+ if name != base
61
+ unsupported(i, name, "The #{name} form is not supported; use #{base}=… without brackets.")
62
+ next
63
+ end
64
+ if seen[base]
65
+ invalid(i, name, "#{name} is repeated; give it once.")
66
+ next
67
+ end
68
+ seen[base] = true
69
+ case base
70
+ when "sort" then analyze_sort(p, i)
71
+ when "fields" then analyze_fields(p, i)
72
+ when "limit" then analyze_limit(p, i)
73
+ when "count" then analyze_count(p, i)
74
+ when "cursor"
75
+ if p.value.nil? || p.value.empty? then invalid(i, name, "cursor cannot be empty.")
76
+ else raw_cursor = [p.value, i]
77
+ end
78
+ end
79
+ end
80
+ apply_defaults_and_required if list?
81
+ raise_first!
82
+ check_cursor(*raw_cursor) if raw_cursor
83
+ raise_first!
84
+ end
85
+
86
+ def list? = @kind == :collection && %w[GET HEAD].include?(@method)
87
+
88
+ # A POST action answers a GET with 405 before the query is read, so here it is a GET action.
89
+ def get_action? = %i[item_action collection_action].include?(@kind) && %w[GET HEAD].include?(@method)
90
+
91
+ # §6.1 (draft 7): a default switch applies to every list request that does not turn it off,
92
+ # and a list request without a required filter gives invalid_parameter naming it. Neither
93
+ # applies to reading an item.
94
+ def apply_defaults_and_required
95
+ collection.named_filters.each do |name, nf|
96
+ next unless nf["default"] && !@switched_off.include?(name) && @named.none? { |n| n.name == name }
97
+ @named << Named.new(name: name, value: nil, raw: "")
98
+ end
99
+ given = @pairs.filter_map { |p| p.name[/\Afilter\[([^\[\]]+)\]/, 1] }
100
+ missing = collection.filters.select { |_, d| d["required"] }.keys +
101
+ collection.named_filters.select { |_, d| d["required"] }.keys
102
+ missing.reject { |f| given.include?(f) }.each do |f|
103
+ invalid(@pairs.size, "filter[#{f}]", "filter[#{f}] is required on this collection.")
104
+ end
105
+ end
106
+
107
+ def unsupported_detail(base)
108
+ case @kind
109
+ when :root then "The API root takes no reserved parameters."
110
+ when :item, :singleton then @method == "GET" || @method == "HEAD" ? "Here only fields is supported." : "#{@method} takes no reserved parameters."
111
+ else
112
+ if %w[GET HEAD].include?(@method)
113
+ "#{base} is not supported here; this collection supports filter, sort, fields, limit, cursor and count."
114
+ else
115
+ "#{@method} takes no reserved parameters."
116
+ end
117
+ end
118
+ end
119
+
120
+ def raise_first!
121
+ return if @issues.empty?
122
+ cat, _i, name, detail = @issues.min_by { |c, i, *| [c, i] }
123
+ raise Problem.param(cat.zero? ? "unsupported_parameter" : "invalid_parameter", name, detail)
124
+ end
125
+
126
+ # ---- filter -----------------------------------------------------------------------------
127
+
128
+ def analyze_filter(p, i, seen)
129
+ m = /\Afilter\[([^\[\]]+)\](?:\[([^\[\]]+)\])?\z/.match(p.name)
130
+ unless m
131
+ return unsupported(i, p.name, "Only filter[field]=value and filter[field][op]=value are supported (no filter-expr).")
132
+ end
133
+ field, op = m[1], m[2]
134
+ if (decl = collection.filters[field])
135
+ op_eff = op || "eq"
136
+ unless decl["ops"].include?(op_eff)
137
+ return unsupported(i, p.name, "Operator #{op_eff} is not declared for #{field}; it takes: #{decl["ops"].join(", ")}.")
138
+ end
139
+ key = [:f, field, op_eff]
140
+ return invalid(i, p.name, "The filter #{field} #{op_eff} is given twice.") if seen[key]
141
+ seen[key] = true
142
+ value = parse_filter_operand(decl, op_eff, p, i)
143
+ # §6.1 (draft 7): operands equal under the field's type are the same filter, also for the
144
+ # cursor, so the cursor is bound to their canonical form, not to the text received.
145
+ unless value == :error
146
+ raw = op_eff == "null" || !value.is_a?(Array) ? Query.canonical(decl["type"], value) : value.map { |v| Query.canonical(decl["type"], v) }
147
+ @filters << Filter.new(field: field, op: op_eff, value: value, raw: raw, name: p.name)
148
+ end
149
+ elsif (nf = collection.named_filters[field])
150
+ return unsupported(i, p.name, "#{field} is a named filter and takes no operators.") if op
151
+ key = [:n, field]
152
+ return invalid(i, p.name, "The named filter #{field} is given twice.") if seen[key]
153
+ seen[key] = true
154
+ if nf["type"].nil? && nf["default"] && p.value == "false"
155
+ # §6.1: false turns a default switch off; it does not negate it.
156
+ @switched_off << field
157
+ elsif nf["type"].nil?
158
+ unless p.value.nil? || p.value.empty?
159
+ hint = nf["default"] ? " or filter[#{field}]=false to turn it off" : " without a value"
160
+ return invalid(i, p.name, "#{field} is a switch: use filter[#{field}]#{hint}.")
161
+ end
162
+ @named << Named.new(name: field, value: nil, raw: "")
163
+ else
164
+ return invalid(i, p.name, "#{field} needs a value of type #{nf["type"]}.") if p.value.nil? || p.value.empty?
165
+ return invalid(i, p.name, over_limit_detail) if nf["type"] == "integer" && Types.integer_over_limit?(p.value)
166
+ parsed = Types.parse_filter_value(nf["type"], p.value, nf["values"])
167
+ return invalid(i, p.name, "#{field} needs a value of type #{nf["type"]}.") unless parsed
168
+ @named << Named.new(name: field, value: parsed[1], raw: Query.canonical(nf["type"], parsed[1]))
169
+ end
170
+ else
171
+ named = collection.named_filters.empty? ? "" : "; named filters: #{collection.named_filters.keys.join(", ")}"
172
+ unsupported(i, p.name, "#{field} cannot be filtered here. Filters: #{collection.filters.keys.join(", ")}#{named}.")
173
+ end
174
+ end
175
+
176
+ def parse_filter_operand(decl, op, p, i)
177
+ type = decl["type"]
178
+ if op == "null"
179
+ return p.value == "true" if %w[true false].include?(p.value)
180
+ invalid(i, p.name, "The null operator takes true or false.")
181
+ return :error
182
+ end
183
+ if %w[prefix contains].include?(op) && (p.value.nil? || p.value.empty?)
184
+ invalid(i, p.name, "The #{op} operand cannot be empty.")
185
+ return :error
186
+ end
187
+ if %w[in nin].include?(op)
188
+ if p.value.nil? || p.value.empty?
189
+ invalid(i, p.name, "The #{op} list cannot be empty.")
190
+ return :error
191
+ end
192
+ raw_vals = p.value.split(",", -1)
193
+ if raw_vals.size > MAX_IN
194
+ # §5.3 (draft 6): an undeclared limit gives invalid_parameter, never part of the result.
195
+ invalid(i, p.name, "An #{op} list takes at most #{MAX_IN} values.")
196
+ return :error
197
+ end
198
+ if type == "integer" && raw_vals.any? { |x| Types.integer_over_limit?(x) }
199
+ invalid(i, p.name, over_limit_detail)
200
+ return :error
201
+ end
202
+ vals = raw_vals.map { |x| Types.parse_filter_value(type, x, decl["values"]) }
203
+ if vals.any?(&:nil?)
204
+ invalid(i, p.name, "Every value of the #{op} list must be of type #{type}#{enum_hint(decl)}#{leap_hint(type)}.")
205
+ return :error
206
+ end
207
+ return vals.map(&:last)
208
+ end
209
+ if type == "integer" && Types.integer_over_limit?(p.value)
210
+ invalid(i, p.name, over_limit_detail)
211
+ return :error
212
+ end
213
+ parsed = Types.parse_filter_value(type, p.value, decl["values"])
214
+ unless parsed
215
+ invalid(i, p.name, "#{p.value.inspect} is not a valid #{type}#{enum_hint(decl)}#{leap_hint(type)}.")
216
+ return :error
217
+ end
218
+ parsed[1]
219
+ end
220
+
221
+ # §5.3 and §6.1 (council round 4, decision 6): an operand over the limit names it in detail.
222
+ def over_limit_detail = "An integer operand may have at most #{Types::MAX_INTEGER_DIGITS} digits, this server's limit; it is compared exactly, never replaced by another value."
223
+
224
+ def enum_hint(decl) = decl["values"] ? " (one of: #{decl["values"].join(", ")})" : ""
225
+
226
+ def leap_hint(type)
227
+ case type
228
+ when "datetime" then "; a leap second (:60) is not accepted"
229
+ when "integer" then "; write it as a JSON number with a whole value (20, 20.0 and 2e1 are the same; +20, 020 and .5 are not JSON numbers), of at most #{Types::MAX_INTEGER_DIGITS} digits"
230
+ else ""
231
+ end
232
+ end
233
+
234
+ # A filter operand in a canonical text form: the same for operands equal under the field's
235
+ # type (20 and 20.0, 007 and 7, two offsets of one instant), as §6.1 and §6.4 require of the
236
+ # cursor.
237
+ def self.canonical(type, v)
238
+ case v
239
+ when BigDecimal then v.zero? ? "0" : v.to_s("F").sub(/\.0\z/, "")
240
+ when Rational then "#{v.numerator}/#{v.denominator}"
241
+ when Date then v.iso8601
242
+ else v.to_s
243
+ end
244
+ end
245
+
246
+ # ---- sort, fields, limit, count ---------------------------------------------------------
247
+
248
+ def analyze_sort(p, i)
249
+ return invalid(i, p.name, "sort cannot be empty.") if p.value.nil? || p.value.empty?
250
+ keys = []
251
+ p.value.split(",", -1).each do |tok|
252
+ desc = tok.start_with?("-")
253
+ key = desc ? tok[1..] : tok
254
+ return invalid(i, p.name, "sort has an empty key.") if key.empty?
255
+ unless collection.sort.key?(key)
256
+ return unsupported(i, p.name, "#{key} is not a sort key here; keys: #{collection.sort.keys.join(", ")}.")
257
+ end
258
+ return invalid(i, p.name, "#{key} appears twice in sort.") if keys.any? { |k, _| k == key }
259
+ keys << [key, desc]
260
+ end
261
+ @sort = keys
262
+ end
263
+
264
+ def analyze_fields(p, i)
265
+ return invalid(i, p.name, "fields cannot be empty.") if p.value.nil? || p.value.empty?
266
+ list = p.value.split(",", -1)
267
+ return invalid(i, p.name, "fields has an empty name.") if list.any?(&:empty?)
268
+ unknown = list.reject { |f| collection.fields.key?(f) }
269
+ return invalid(i, p.name, "Unknown field#{"s" if unknown.size > 1}: #{unknown.join(", ")}. Fields: #{collection.fields.keys.join(", ")}.") unless unknown.empty?
270
+ @fields = list
271
+ end
272
+
273
+ def analyze_limit(p, i)
274
+ v = p.value.to_s
275
+ unless v.match?(/\A[0-9]{1,9}\z/) && (1..collection.max_limit).cover?(v.to_i)
276
+ return invalid(i, p.name, "limit must be an integer between 1 and #{collection.max_limit}.")
277
+ end
278
+ @limit = v.to_i
279
+ end
280
+
281
+ def analyze_count(p, i)
282
+ return invalid(i, p.name, "count takes true or false.") unless %w[true false].include?(p.value)
283
+ @count = p.value == "true"
284
+ end
285
+
286
+ # ---- cursor -------------------------------------------------------------------------------
287
+
288
+ def binding_payload
289
+ f = @filters.map { |x| ["f", x.field, x.op, x.raw] } + @named.map { |x| ["n", x.name, x.raw] }
290
+ { "c" => collection.name, "f" => Digest::SHA256.hexdigest(JSON.generate(f.sort))[0, 22],
291
+ "s" => @sort.map { |k, d| d ? "-#{k}" : k }.join(","), "p" => PRINCIPAL }
292
+ end
293
+
294
+ def check_cursor(token, i)
295
+ payload = Cursor.read(token)
296
+ b = binding_payload
297
+ if payload.nil?
298
+ invalid(i, "cursor", "The cursor was not issued by this server or has been altered.")
299
+ elsif b.any? { |k, v| payload[k] != v }
300
+ invalid(i, "cursor", "The cursor belongs to another collection, other filters or another sort; start again without it.")
301
+ else
302
+ @cursor_payload = payload
303
+ end
304
+ end
305
+
306
+ # ---- SQL ----------------------------------------------------------------------------------
307
+
308
+ def where_clauses
309
+ clauses = @filters.map { |f| filter_sql(collection.filters[f.field], f.op, f.value) }
310
+ clauses += @named.map { |n| sanitize(collection.named_filters[n.name][:sql].call(n.value)) }
311
+ clauses
312
+ end
313
+
314
+ def sanitize(arr) = ActiveRecord::Base.sanitize_sql_array(arr)
315
+
316
+ def q(v) = ActiveRecord::Base.connection.quote(v)
317
+
318
+ def literal(type, v)
319
+ case type
320
+ when "integer" then Types::BIGINT.cover?(v) ? "#{v}::bigint" : "#{q(v.to_s)}::numeric"
321
+ when "decimal" then "#{q(v.to_s("F"))}::numeric"
322
+ when "date" then "#{q(v.iso8601)}::date"
323
+ when "boolean" then v ? "TRUE" : "FALSE"
324
+ else q(v)
325
+ end
326
+ end
327
+
328
+ def filter_sql(decl, op, value)
329
+ col = decl[:sql]
330
+ return value ? "#{col} IS NULL" : "#{col} IS NOT NULL" if op == "null"
331
+ return id_filter_sql(col, op, value) if decl[:id_like]
332
+ return datetime_filter_sql(col, op, value) if decl["type"] == "datetime"
333
+ return text_match_sql(col, op, value) if %w[prefix contains].include?(op)
334
+ if op == "in"
335
+ "#{col} IN (#{value.map { |v| literal(decl["type"], v) }.join(", ")})"
336
+ elsif op == "nin"
337
+ # §6.1: nin, like every operator but null, never matches an absent or null value.
338
+ "#{col} IS NOT NULL AND #{col} NOT IN (#{value.map { |v| literal(decl["type"], v) }.join(", ")})"
339
+ else
340
+ "#{col} #{SQL_OPS.fetch(op)} #{literal(decl["type"], value)}"
341
+ end
342
+ end
343
+
344
+ # §6.1 (draft 7): prefix and contains by code points, which is what the declared collation
345
+ # says for these columns (COLLATE "C" on PostgreSQL; SQLite compares bytes).
346
+ def text_match_sql(col, op, value)
347
+ lit = q(value)
348
+ postgres = ActiveRecord::Base.connection.adapter_name.match?(/postg/i)
349
+ if op == "prefix"
350
+ postgres ? "starts_with(#{col}, #{lit})" : "substr(#{col}, 1, length(#{lit})) = #{lit}"
351
+ else
352
+ postgres ? "strpos(#{col}, #{lit}) > 0" : "instr(#{col}, #{lit}) > 0"
353
+ end
354
+ end
355
+
356
+ # The id is a string (§3): only the canonical strings of a bigint can match.
357
+ def id_filter_sql(col, op, value)
358
+ canon = ->(s) { s.match?(/\A[1-9][0-9]{0,17}\z/) ? s.to_i : nil }
359
+ case op
360
+ when "eq" then (n = canon.(value)) ? "#{col} = #{n}" : "FALSE"
361
+ when "ne" then (n = canon.(value)) ? "#{col} <> #{n}" : "#{col} IS NOT NULL"
362
+ when "in"
363
+ ns = value.filter_map { |v| canon.(v) }
364
+ ns.empty? ? "FALSE" : "#{col} IN (#{ns.join(", ")})"
365
+ when "nin"
366
+ ns = value.filter_map { |v| canon.(v) }
367
+ ns.empty? ? "#{col} IS NOT NULL" : "#{col} NOT IN (#{ns.join(", ")})"
368
+ end
369
+ end
370
+
371
+ # Exact comparison of instants even if the value has more precision than the microseconds
372
+ # PostgreSQL stores (which would round): see the journal.
373
+ def datetime_filter_sql(col, op, r)
374
+ if %w[in nin].include?(op)
375
+ exact = r.select { |x| Types.micro_exact?(x) }
376
+ return op == "in" ? "FALSE" : "#{col} IS NOT NULL" if exact.empty?
377
+ list = exact.map { |x| "#{q(Types.sql_instant(x))}::timestamptz" }.join(", ")
378
+ return op == "in" ? "#{col} IN (#{list})" : "#{col} IS NOT NULL AND #{col} NOT IN (#{list})"
379
+ end
380
+ lit = ->(mode) { "#{q(Types.sql_instant(r, mode))}::timestamptz" }
381
+ if Types.micro_exact?(r)
382
+ "#{col} #{SQL_OPS.fetch(op)} #{lit.(:floor)}"
383
+ else
384
+ case op
385
+ when "eq" then "FALSE"
386
+ when "ne" then "#{col} IS NOT NULL"
387
+ when "lt", "le" then "#{col} <= #{lit.(:floor)}"
388
+ when "gt", "ge" then "#{col} >= #{lit.(:ceil)}"
389
+ end
390
+ end
391
+ end
392
+
393
+ def order_sql
394
+ parts = @sort.map { |k, desc| "#{collection.sort[k][:sql]} #{desc ? "DESC" : "ASC"} NULLS LAST" }
395
+ (parts + ["id ASC"]).join(", ")
396
+ end
397
+
398
+ # "After the last row" condition with nulls last in both directions. SQL's row comparison,
399
+ # (a, id) > (x, y), does not work with nulls.
400
+ def keyset_sql(keys, last_id)
401
+ ors = []
402
+ eqs = []
403
+ @sort.each_with_index do |(k, desc), idx|
404
+ d = collection.sort[k]
405
+ v = keys[idx]
406
+ lit = v.nil? ? nil : sort_literal(d[:type], v)
407
+ unless v.nil?
408
+ ors << (eqs + ["(#{d[:sql]} #{desc ? "<" : ">"} #{lit} OR #{d[:sql]} IS NULL)"]).join(" AND ")
409
+ end
410
+ eqs << (v.nil? ? "#{d[:sql]} IS NULL" : "#{d[:sql]} = #{lit}")
411
+ end
412
+ ors << (eqs + ["id > #{Integer(last_id)}"]).join(" AND ")
413
+ "(" + ors.map { |o| "(#{o})" }.join(" OR ") + ")"
414
+ end
415
+
416
+ def sort_literal(type, v)
417
+ case type
418
+ when "datetime" then "#{q(v)}::timestamptz"
419
+ when "decimal" then "#{q(v)}::numeric"
420
+ when "date" then "#{q(v)}::date"
421
+ when "integer" then "#{Integer(v)}::bigint"
422
+ else q(v)
423
+ end
424
+ end
425
+
426
+ def sort_value(rec, key)
427
+ d = collection.sort[key]
428
+ v = rec[d[:sql]]
429
+ case v
430
+ when nil then nil
431
+ when Time, ActiveSupport::TimeWithZone then v.utc.strftime("%Y-%m-%dT%H:%M:%S.%6NZ")
432
+ when BigDecimal then v.to_s("F")
433
+ when Date then v.iso8601
434
+ else v
435
+ end
436
+ end
437
+
438
+ # Runs the query and returns [records, next cursor or nil, total or nil].
439
+ def run
440
+ model = collection.model
441
+ scope = model.all
442
+ where_clauses.each { |c| scope = scope.where(Arel.sql(c)) }
443
+ total = @count ? scope.count : nil
444
+ if @cursor_payload
445
+ scope = scope.where(Arel.sql(keyset_sql(@cursor_payload["k"], @cursor_payload["i"])))
446
+ end
447
+ rows = scope.order(Arel.sql(order_sql)).limit(@limit + 1).to_a
448
+ next_token = nil
449
+ if rows.size > @limit
450
+ rows = rows.first(@limit)
451
+ last = rows.last
452
+ next_token = Cursor.issue(binding_payload.merge("k" => @sort.map { |k, _| sort_value(last, k) }, "i" => last.id))
453
+ end
454
+ [rows, next_token, total]
455
+ end
456
+
457
+ # §6.4: next carries the cursor and leaves the other parameters as they arrived.
458
+ def next_link(path, token)
459
+ kept = @pairs.reject { |p| p.name == "cursor" }.map { |p| QueryString.link_form(p.raw) }
460
+ "#{path}?#{(kept + ["cursor=#{QueryString.encode_component(token)}"]).join("&")}"
461
+ end
462
+
463
+ def project(rep)
464
+ return rep unless @fields
465
+ rep.select { |k, _| k == "id" || k.start_with?("_") || @fields.include?(k) }
466
+ end
467
+ end
468
+
469
+ end
@@ -0,0 +1,37 @@
1
+ module Restep
2
+ # Parses QUERY_STRING by hand. Rack::QueryParser loses repeated parameters (it keeps the last
3
+ # one) and turns brackets into nested hashes, so neither §5.3 (repeated names, name "exactly as
4
+ # received after percent-decoding") nor §6.1 (filter[x] versus filter[x][eq]) can be met.
5
+ module QueryString
6
+ Pair = Struct.new(:name, :value, :raw, keyword_init: true) # value is nil when there is no "="
7
+
8
+ module_function
9
+
10
+ def parse(qs)
11
+ return [] if qs.nil? || qs.empty?
12
+ qs.split("&").reject(&:empty?).map do |seg|
13
+ name, value = seg.split("=", 2)
14
+ Pair.new(name: decode(name), value: value.nil? ? nil : decode(value), raw: seg)
15
+ end
16
+ end
17
+
18
+ # "+" is decoded as a space, as forms and URLSearchParams do (see the journal).
19
+ def decode(s)
20
+ out = s.tr("+", " ").gsub(/%([0-9A-Fa-f]{2})/) { $1.hex.chr }.force_encoding(Encoding::UTF_8)
21
+ raise Problem.new(400, "bad_request", detail: "The query string is not valid UTF-8 after percent-decoding.") unless out.valid_encoding?
22
+ out
23
+ end
24
+
25
+ # §5.2 (draft 7): a parameter as received, ready for a link the server builds. Whatever RFC 3986
26
+ # (section 3.4) does not allow unencoded in a query, [ and ] among them, is percent-encoded; a
27
+ # % that starts no escape becomes %25. The rest stays as received, + (a space) included, since
28
+ # encoding again does not change a parameter.
29
+ def link_form(raw)
30
+ raw.b.gsub(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@\/?%]/n) { |c| format("%%%02X", c.ord) }
31
+ end
32
+
33
+ def encode_component(s)
34
+ s.b.gsub(/[^A-Za-z0-9\-._~]/) { |c| format("%%%02X", c.ord) }
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,59 @@
1
+ module Restep
2
+ # Restep server as a Rack application with a single entry point: it resolves the resource
3
+ # itself and applies the error order of §5.4 from start to finish. It is mounted behind
4
+ # Restep::Envelope (501, profile and CORS):
5
+ #
6
+ # use Restep::Envelope
7
+ # run Restep::RackApp.new
8
+ class RackApp
9
+ def initialize(logger: nil) = @logger = logger
10
+
11
+ def call(env)
12
+ request = Request.new(env)
13
+ status, headers, body = handle(request)
14
+ finish(request, status, headers, body)
15
+ rescue Problem => e
16
+ finish(request, *Operations.problem_response(e))
17
+ rescue StandardError => e
18
+ @logger&.error("#{e.class}: #{e.message}\n#{e.backtrace&.first(12)&.join("\n")}")
19
+ finish(request, *Operations.problem_response(Problem.new(500, "internal", detail: "Unexpected server failure.")))
20
+ end
21
+
22
+ private
23
+
24
+ def handle(request)
25
+ path = request.path
26
+ Context.check_uri_length!(request) unless [Restep.url("/status"), Restep.url("/docs")].include?(path)
27
+ kind, coll, rec, action = Resolver.resolve(path, method: request.method, # 1. 404
28
+ idempotency_key: request.header("Idempotency-Key"))
29
+ unless Resolver.allowed(kind, action).include?(request.method) # 2. 405
30
+ raise Resolver.method_not_allowed(kind, path, action)
31
+ end
32
+ return Operations.status if kind == :status
33
+ return Operations.docs if kind == :docs
34
+
35
+ ctx = Context.new(request, kind: kind, collection: coll, record: rec, action: action) # 3 and 4
36
+ case [kind, request.method]
37
+ in [:item_action | :collection_action, _] then Operations.action(ctx)
38
+ in [:root, _] then Operations.discovery(ctx)
39
+ in [:collection, "GET" | "HEAD"] then Operations.list(ctx)
40
+ in [:collection, "POST"] then Operations.create(ctx)
41
+ in [:item | :singleton, "GET" | "HEAD"] then Operations.show(ctx)
42
+ in [:item | :singleton, "PATCH"] then Operations.update(ctx)
43
+ in [:item, "DELETE"] then Operations.destroy(ctx)
44
+ end
45
+ end
46
+
47
+ def finish(request, status, headers, body)
48
+ headers = headers.dup
49
+ if body.nil?
50
+ headers.delete("content-type")
51
+ [status, headers, []]
52
+ else
53
+ headers["content-type"] ||= "application/json"
54
+ headers["content-length"] = body.bytesize.to_s
55
+ [status, headers, request&.head? ? [] : [body]]
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,83 @@
1
+ require "restep"
2
+ require "active_support/concern"
3
+
4
+ module Restep
5
+ module Rails
6
+ # Concern for a Rails controller that serves Restep resources. The Rails router does step 1
7
+ # of §5.4 (which resource) and each resource's controller looks up the item in a
8
+ # before_action (404). What has no route goes to a fallback controller that tells 404 from
9
+ # 405 with Restep::Resolver. Steps 3 and 4 (400, 415, 413, 406) are done by restep_context;
10
+ # the rest, by Restep::Operations.
11
+ #
12
+ # Parameters do not come from `params`: Restep::Envelope empties Rails' caches so it does not
13
+ # parse the query or the body (§5.3 asks to see them raw). Only the route's remain.
14
+ module Controller
15
+ extend ActiveSupport::Concern
16
+
17
+ # For config.exceptions_app: what fails before reaching a controller. A path with an
18
+ # invalid encoding (/stations/%FF) makes the router fail; it names no resource, so it is a
19
+ # 404, as in Restep::RackApp. Anything else, 500.
20
+ def self.exceptions_app
21
+ lambda do |env|
22
+ e = env["action_dispatch.exception"]
23
+ if e.is_a?(ActionController::BadRequest) && e.message.start_with?("Invalid path parameters")
24
+ Restep::Problem.rack(404, "not_found", detail: "Nothing here. The API root (/) lists the collections.")
25
+ else
26
+ Restep::Problem.rack(500, "internal", detail: "Unexpected server failure.")
27
+ end
28
+ end
29
+ end
30
+
31
+ included do
32
+ # rescue_from checks the last one declared first: Problem before StandardError.
33
+ rescue_from StandardError, with: :restep_internal_error
34
+ rescue_from Restep::Problem, with: :restep_problem
35
+ before_action :restep_check_uri_length
36
+ before_action :restep_check_exact_path
37
+ end
38
+
39
+ private
40
+
41
+ def restep_request = @restep_request ||= Restep::Request.new(request.env)
42
+
43
+ def restep_check_uri_length = Restep::Context.check_uri_length!(restep_request)
44
+
45
+ # The Rails router normalizes the path before looking it up (it drops the trailing slash and
46
+ # merges doubled ones), so "/stations/7/" and "//stations" would reach the action of
47
+ # "/stations/7" and "/stations". §3 compares the path segment by segment: neither exists.
48
+ def restep_check_exact_path
49
+ path = restep_request.path
50
+ return if path == "/" || path == "#{Restep.config.root_path}/"
51
+ return unless path.end_with?("/") || path.include?("//")
52
+ raise Restep::Problem.new(404, "not_found", detail: "Nothing here. The API root lists the collections.")
53
+ end
54
+
55
+ def restep_context(kind:, collection: nil, record: nil, action: nil)
56
+ Restep::Context.new(restep_request, kind: kind, collection: collection, record: record, action: action)
57
+ end
58
+
59
+ # Writes [status, headers, body] as is: Restep sets its own validators, content types and
60
+ # caches, so neither render nor fresh_when is used.
61
+ def render_restep(result)
62
+ status, headers, body = result
63
+ self.status = status
64
+ headers.each { |k, v| response.headers[k] = v }
65
+ if body.nil?
66
+ response.headers.delete("content-type")
67
+ self.response_body = ""
68
+ else
69
+ response.headers["content-type"] = headers["content-type"] || "application/json"
70
+ response.headers["content-length"] = body.bytesize.to_s
71
+ self.response_body = request.head? ? "" : body
72
+ end
73
+ end
74
+
75
+ def restep_problem(e) = render_restep(Restep::Operations.problem_response(e))
76
+
77
+ def restep_internal_error(e)
78
+ logger&.error("#{e.class}: #{e.message}\n#{e.backtrace&.first(12)&.join("\n")}")
79
+ restep_problem(Restep::Problem.new(500, "internal", detail: "Unexpected server failure."))
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,33 @@
1
+ require "action_dispatch"
2
+
3
+ module Restep
4
+ module Rails
5
+ # Action routes (§11.1) for config/routes.rb. Restep puts the action name after a colon, in
6
+ # the same segment (/stations/7:deactivate, /readings:summary), and also accepts %3A. The
7
+ # Rails router does not work for that as is: ":" marks a parameter and cannot be escaped
8
+ # ("readings:summary" is "readings" and the parameter :summary). So each action is a route
9
+ # with the whole segment as a parameter and a constraint that requires the name after ":" or
10
+ # "%3A". The constraints look at the undecoded path; the parameter arrives decoded.
11
+ #
12
+ # restep_action :stations, :deactivate # POST /stations/:id:deactivate
13
+ # restep_action :readings, :summary, on: :collection, via: :get
14
+ module Routes
15
+ COLON = "(?::|%3[Aa])".freeze
16
+ # An id with no colon, encoded or not: for show, update and destroy, so that
17
+ # /stations/7:deactivate does not reach show with the id "7:deactivate".
18
+ ID = /(?:(?!%3[Aa])[^\/:])+/
19
+
20
+ def restep_action(resource, name, on: :member, via: :post)
21
+ if on == :member
22
+ match "#{resource}/:id", to: "#{resource}##{name}", via: via, as: nil, format: false,
23
+ constraints: { id: /(?:(?!%3[Aa])[^\/:])+#{COLON}#{name}/ }
24
+ else
25
+ match ":restep_target", to: "#{resource}##{name}", via: via, as: nil, format: false,
26
+ constraints: { restep_target: /#{resource}#{COLON}#{name}/ }
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+
33
+ ActionDispatch::Routing::Mapper.include(Restep::Rails::Routes)