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,42 @@
1
+ module Restep
2
+ # The request as it arrives in the Rack environment, without going through any framework's
3
+ # parameter parsing: §5.3 asks to read the query string raw (repeated names, bracket forms)
4
+ # and §5.4 fixes which error comes first.
5
+ class Request
6
+ attr_reader :env
7
+
8
+ def initialize(env) = @env = env
9
+
10
+ def method = env["REQUEST_METHOD"].to_s
11
+ def safe? = %w[GET HEAD].include?(method)
12
+ def head? = method == "HEAD"
13
+ # The path as it arrived. The Rails router rewrites PATH_INFO already normalized (no trailing
14
+ # slash, doubled slashes merged); Rails keeps the original in ORIGINAL_FULLPATH.
15
+ def path
16
+ original = env["ORIGINAL_FULLPATH"]
17
+ original ? original.split("?", 2).first : "#{env["SCRIPT_NAME"]}#{env["PATH_INFO"]}"
18
+ end
19
+ def query_string = env["QUERY_STRING"].to_s
20
+ def content_type = env["CONTENT_TYPE"]
21
+
22
+ # Header by its HTTP name ("If-Match").
23
+ def header(name)
24
+ key = name.upcase.tr("-", "_")
25
+ env[%w[CONTENT_TYPE CONTENT_LENGTH].include?(key) ? key : "HTTP_#{key}"]
26
+ end
27
+
28
+ def raw_body
29
+ @raw_body ||= begin
30
+ io = env["rack.input"]
31
+ if io
32
+ io.rewind if io.respond_to?(:rewind)
33
+ data = io.read.to_s
34
+ io.rewind if io.respond_to?(:rewind)
35
+ data
36
+ else
37
+ ""
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,84 @@
1
+ module Restep
2
+ # Step 1 of §5.4: which resource the path names, before looking at the method (a PUT to an
3
+ # item that does not exist is 404, not 405). Returns [kind, collection, item, action] or raises 404.
4
+ # An action (§11.1) goes after a colon, which may also arrive as %3A:
5
+ # /stations/7:deactivate on an item, /readings:summary on the collection.
6
+ module Resolver
7
+ ALLOW = { root: %w[GET HEAD], collection: %w[GET HEAD POST], item: %w[GET HEAD PATCH DELETE],
8
+ singleton: %w[GET HEAD PATCH], status: %w[GET HEAD], docs: %w[GET HEAD] }.freeze
9
+ NOT_FOUND = "Nothing here. The API root lists the collections.".freeze
10
+
11
+ module_function
12
+
13
+ # path: the whole request path; outside the API root (config.root_path) it is 404.
14
+ # method and idempotency_key (the header as it arrives) only matter on an item action
15
+ # (action_target!).
16
+ def resolve(path, method: nil, idempotency_key: nil)
17
+ root = Restep.config.root_path
18
+ unless root.empty?
19
+ raise Problem.new(404, "not_found", detail: NOT_FOUND) unless path == root || path.start_with?("#{root}/")
20
+ path = path.delete_prefix(root)
21
+ path = "/" if path.empty?
22
+ end
23
+ return [:root, nil, nil, nil] if path == "/"
24
+ return [:status, nil, nil, nil] if path == "/status"
25
+ return [:docs, nil, nil, nil] if path == "/docs"
26
+ if (single = Restep.singleton_by_path(path))
27
+ return [:singleton, single, find_singleton!(single), nil]
28
+ end
29
+ segs = path.split("/", -1)
30
+ raise Problem.new(404, "not_found", detail: NOT_FOUND) unless segs.size.between?(2, 3) && segs[0].empty?
31
+ last = (QueryString.decode(segs[-1]) rescue nil) or raise Problem.new(404, "not_found", detail: NOT_FOUND)
32
+ head, colon, name = last.rpartition(":")
33
+ if segs.size == 2
34
+ coll = Restep.collection_by_path("/#{colon.empty? ? last : head}")
35
+ raise Problem.new(404, "not_found", detail: NOT_FOUND) unless coll
36
+ return [:collection, coll, nil, nil] if colon.empty?
37
+ return [:collection_action, coll, nil, declared!(coll, name, "collection")]
38
+ end
39
+ coll = Restep.collection_by_path("/#{segs[1]}")
40
+ raise Problem.new(404, "not_found", detail: NOT_FOUND) unless coll
41
+ return [:item, coll, find!(coll, last), nil] if colon.empty?
42
+ action = declared!(coll, name, "item")
43
+ [:item_action, coll, action_target!(coll, head, action, method, idempotency_key), action]
44
+ end
45
+
46
+ # The item of an action. §5.4, rule 3, and §7.1: in a POST action that is not idempotent and
47
+ # carries Idempotency-Key, the item no longer existing does not give 404 yet, because a replay
48
+ # takes its place (whether the first request or another one deleted it). It then returns a
49
+ # Missing with its id; Operations.action looks for the stored response first and, if there is
50
+ # none, gives the 404 when it goes to read the item (current! and lock!).
51
+ Missing = Struct.new(:id)
52
+
53
+ def action_target!(coll, id, action, method, idempotency_key)
54
+ rec = id && coll.find(id)
55
+ return rec if rec
56
+ return Missing.new(id) if id && method == "POST" && action.method == "POST" && !action.idempotent && !idempotency_key.nil?
57
+ find!(coll, id)
58
+ end
59
+
60
+ # §11.1: an action that is not declared, or declared on the other kind of resource, gives 404.
61
+ def declared!(coll, name, on)
62
+ action = coll.actions[name]
63
+ return action if action && action.on == on
64
+ raise Problem.new(404, "not_found", detail: "#{coll.name} has no #{on} action named #{name.inspect}.")
65
+ end
66
+
67
+ def find!(coll, id)
68
+ rec = id && coll.find(id)
69
+ rec or raise Problem.new(404, "not_found", detail: "There is no #{coll.name} item with id #{id.inspect}.")
70
+ end
71
+
72
+ def find_singleton!(single)
73
+ single.find_singleton or raise Problem.new(404, "not_found", detail: "The #{single.name} singleton is not set up.")
74
+ end
75
+
76
+ def allowed(kind, action = nil) = action ? action.allowed_methods : ALLOW.fetch(kind)
77
+
78
+ # Step 2 of §5.4.
79
+ def method_not_allowed(kind, path, action = nil)
80
+ allow = allowed(kind, action).join(", ")
81
+ Problem.new(405, "method_not_allowed", detail: "#{path} supports #{allow}.", headers: { "allow" => allow })
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,147 @@
1
+ module Restep
2
+ # Types of §4.2: parsing of filter values (text) and body values (JSON), and rendering.
3
+ module Types
4
+ DECIMAL_RE = /\A-?[0-9]+(\.[0-9]+)?\z/
5
+ # number of RFC 8259 §6: no "+", no leading zeros, digits on both sides of ".", optional exponent.
6
+ NUMBER_RE = /\A(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?\z/
7
+ MAX_INTEGER_DIGITS = 8 * 1024
8
+ DATE_RE = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/
9
+ # RFC 3339 date-time with a mandatory offset. T and Z may be lowercase (RFC 3339 §5.6).
10
+ DATETIME_RE = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|[+-][0-9]{2}:[0-9]{2})\z/
11
+ BIGINT = (-(2**63))..(2**63 - 1)
12
+ # Unicode noncharacters: U+FDD0..U+FDEF and the last two code points of every plane (§3, I-JSON).
13
+ NONCHARACTER = /[\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/
14
+
15
+ module_function
16
+
17
+ def noncharacter?(s) = s.valid_encoding? && NONCHARACTER.match?(s)
18
+
19
+ def parse_date(s)
20
+ m = DATE_RE.match(s) or return nil
21
+ y, mo, d = m[1].to_i, m[2].to_i, m[3].to_i
22
+ Date.valid_date?(y, mo, d) ? Date.new(y, mo, d) : nil
23
+ end
24
+
25
+ # Returns the instant as seconds since the epoch, as an exact Rational (without going through
26
+ # floating point or PostgreSQL's microsecond precision).
27
+ # leap: whether a leap second (:60) is accepted, only to recognize one (leap_second?). Draft
28
+ # 7: a filter operand with one gives invalid_parameter (6.1), and a request body with one,
29
+ # 422 with a format entry (3).
30
+ def parse_datetime(s, leap: false)
31
+ m = DATETIME_RE.match(s) or return nil
32
+ y, mo, d, h, mi, se = (1..6).map { |i| m[i].to_i }
33
+ return nil unless Date.valid_date?(y, mo, d) && h <= 23 && mi <= 59 && se <= (leap ? 60 : 59)
34
+ frac = m[7] ? Rational(m[7][1..].to_i, 10**(m[7].length - 1)) : 0
35
+ off = 0
36
+ if m[8] =~ /\A([+-])([0-9]{2}):([0-9]{2})\z/
37
+ oh, om = $2.to_i, $3.to_i
38
+ return nil if oh > 23 || om > 59
39
+ off = ($1 == "-" ? -1 : 1) * (oh * 3600 + om * 60)
40
+ end
41
+ # With leap: true, a leap second (:60) is the first instant of the next minute.
42
+ Rational(Time.utc(y, mo, d, h, mi, 0).to_i) + se + frac - off
43
+ end
44
+
45
+ # Whether s is an RFC 3339 date-time that is valid only as a leap second (:60). §3 (draft 7):
46
+ # a server never writes one and rejects it in a request body with a format entry; §6.1: a
47
+ # filter operand with one gives invalid_parameter.
48
+ def leap_second?(s)
49
+ s.is_a?(String) && (m = DATETIME_RE.match(s)) && m[6] == "60" && !parse_datetime(s, leap: true).nil?
50
+ end
51
+
52
+ def micro_exact?(r)
53
+ (r * 1_000_000).denominator == 1
54
+ end
55
+
56
+ # Instant (Rational) to text that PostgreSQL understands, rounded to microseconds down or up.
57
+ def sql_instant(r, mode = :floor)
58
+ us = mode == :ceil ? (r * 1_000_000).ceil : (r * 1_000_000).floor
59
+ t = Time.at(us.div(1_000_000), us % 1_000_000, :usec, in: "UTC")
60
+ t.strftime("%Y-%m-%dT%H:%M:%S.%6NZ")
61
+ end
62
+
63
+ # Filter value (URL text) according to the declared type. Returns [:ok, value] or nil.
64
+ def parse_filter_value(type, raw, values = nil)
65
+ raw = "" if raw.nil?
66
+ case type
67
+ when "string" then [:ok, raw]
68
+ when "enum" then values.include?(raw) ? [:ok, raw] : nil
69
+ when "integer" then parse_integer_operand(raw)
70
+ when "decimal" then DECIMAL_RE.match?(raw) ? [:ok, BigDecimal(raw)] : nil
71
+ when "boolean" then %w[true false].include?(raw) ? [:ok, raw == "true"] : nil
72
+ when "date" then (d = parse_date(raw)) ? [:ok, d] : nil
73
+ when "datetime" then (t = parse_datetime(raw)) ? [:ok, t] : nil
74
+ end
75
+ end
76
+
77
+ # §6.1 (draft 7, council round 3, decision 7): an integer operand is written with the number
78
+ # grammar of RFC 8259 §6, exponent included, and matches its type when its exact value has no
79
+ # fractional part: 20.0 and 2e1 are the operand 20 (and bind the cursor as 20); 20.5, 2e-1,
80
+ # +20, .5, 020 and 0x14 are invalid. The value is computed from the digits and the exponent
81
+ # as integers, never through BigDecimal, which turns 1e-99999999999999999999 into 0.
82
+ # An operand of more than MAX_INTEGER_DIGITS digits is outside this server's undeclared limit
83
+ # (§5.3: invalid_parameter): in plain digits the query string (8 KiB) could not hold it either.
84
+ def parse_integer_operand(raw)
85
+ parts = integer_parts(raw) or return nil
86
+ sign, stripped, shift = parts
87
+ return [:ok, 0] if stripped.empty?
88
+ return nil if shift.negative?
89
+ return nil if stripped.length + shift > MAX_INTEGER_DIGITS
90
+ value = Integer(stripped, 10) * (10**shift)
91
+ [:ok, sign == "-" ? -value : value]
92
+ end
93
+
94
+ # §6.1 (draft 7, council round 4, decision 6): whether raw is a whole JSON number whose value
95
+ # has more than MAX_INTEGER_DIGITS digits. It is over this server's §5.3 limit, so it gives
96
+ # invalid_parameter with the limit in detail; it is never replaced by another value.
97
+ def integer_over_limit?(raw)
98
+ parts = integer_parts(raw.to_s) or return false
99
+ _, stripped, shift = parts
100
+ !stripped.empty? && !shift.negative? && stripped.length + shift > MAX_INTEGER_DIGITS
101
+ end
102
+
103
+ # The sign, the significant digits without trailing zeros and the power of ten of a JSON
104
+ # number, computed as integers (never through BigDecimal or a float), or nil.
105
+ def integer_parts(raw)
106
+ m = NUMBER_RE.match(raw) or return nil
107
+ sign, int, frac, exp = m[1], m[2], m[3].to_s, m[4].to_s
108
+ digits = (int + frac).sub(/\A0+/, "")
109
+ return [sign, "", 0] if digits.empty?
110
+ stripped = digits.sub(/0+\z/, "")
111
+ [sign, stripped, Integer(exp.empty? ? "0" : exp, 10) - frac.length + (digits.length - stripped.length)]
112
+ end
113
+
114
+ def render_decimal(bd, scale)
115
+ return nil if bd.nil?
116
+ s = bd.round(scale).to_s("F") # "12.5", "-0.5", "12.0"
117
+ neg = s.start_with?("-")
118
+ int, frac = s.delete_prefix("-").split(".")
119
+ frac = (frac || "").ljust(scale, "0")[0, scale]
120
+ out = scale.zero? ? int : "#{int}.#{frac}"
121
+ out = "-#{out}" if neg && out =~ /[1-9]/
122
+ out
123
+ end
124
+
125
+ def render_datetime(t)
126
+ return nil if t.nil?
127
+ t = t.utc
128
+ s = t.strftime("%Y-%m-%dT%H:%M:%S")
129
+ s << format(".%06d", t.usec).sub(/0+\z/, "") if t.usec.positive?
130
+ s << "Z"
131
+ end
132
+
133
+ # Canonical form to compare bodies "equal as JSON values" (§7.1): sorted keys and normalized
134
+ # exact numbers (1, 1.0 and 1e0 are the same number).
135
+ def canonical_json(v)
136
+ case v
137
+ when Hash then "{" + v.keys.sort.map { |k| "#{JSON.generate(k)}:#{canonical_json(v[k])}" }.join(",") + "}"
138
+ when Array then "[" + v.map { |x| canonical_json(x) }.join(",") + "]"
139
+ when Integer then v.to_s
140
+ when BigDecimal, Float
141
+ bd = BigDecimal(v.to_s)
142
+ bd.frac.zero? ? bd.to_i.to_s : bd.to_s("F")
143
+ else JSON.generate(v)
144
+ end
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,3 @@
1
+ module Restep
2
+ VERSION = "0.1.0".freeze
3
+ end
data/lib/restep.rb ADDED
@@ -0,0 +1,57 @@
1
+ require "json"
2
+ require "bigdecimal"
3
+ require "date"
4
+ require "digest"
5
+ require "openssl"
6
+ require "base64"
7
+ require "securerandom"
8
+ require "rack"
9
+ require "active_record"
10
+
11
+ # Restep 1 (draft 7) for Ruby: the protocol part, with no domain and no framework. Two servers
12
+ # use it over the same domain: tools/restep-rack (plain Rack, a single entry point,
13
+ # Restep::RackApp) and tools/restep-rails (idiomatic Rails, one controller per resource with
14
+ # Restep::Rails::Controller). Both call Restep::Operations with a Restep::Context.
15
+ module Restep
16
+ PROFILE_URI = "https://w3id.org/restep/1/".freeze # identifier: profile link and error types
17
+ PROFILE_LINK = %(<#{PROFILE_URI}>; rel="profile").freeze
18
+ PRINCIPAL = "anonymous".freeze # no authentication: a single principal
19
+
20
+ # What the application supplies: its catalog and where it keeps its data.
21
+ class Config
22
+ attr_accessor :collections, # { "stations" => Collection, ... }
23
+ :singletons, # { "network" => Collection (singleton), ... }
24
+ :reasons, # catalog of domain reasons (§5.4)
25
+ :idempotency_model, # Active Record model for the keys (§7.1)
26
+ :cursor_key_path, # file holding the cursor secret (§6.4)
27
+ :docs_path, # human-readable documentation, served at /docs (§4.2)
28
+ :root_path, # path of the API root, no trailing slash: "" or "/v1" (§2)
29
+ :logger
30
+
31
+ def initialize
32
+ @collections, @singletons, @reasons = {}, {}, {}
33
+ @root_path = ""
34
+ end
35
+ end
36
+
37
+ class << self
38
+ def config = @config ||= Config.new
39
+ def configure = yield(config)
40
+
41
+ def collections = config.collections
42
+ def singletons = config.singletons
43
+ # §2: the discovery paths are relative to the API root; the links in bodies and headers
44
+ # (href, next, Location, Link) are absolute paths that include it.
45
+ def url(path) = "#{config.root_path}#{path}"
46
+
47
+ def collection_by_path(path) = collections.values.find { |c| c.path == path }
48
+ def singleton_by_path(path) = singletons.values.find { |c| c.path == path }
49
+ end
50
+ end
51
+
52
+ require_relative "restep/version"
53
+
54
+ %w[problem query_string types collection envelope conditional cursor query body idempotency
55
+ discovery request resolver context operations rack_app].each do |f|
56
+ require_relative "restep/#{f}"
57
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: restep
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - wubytes
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rack
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '3.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: activerecord
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '8.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '8.0'
40
+ description: Query parsing, filters and SQL, cursors, ETags and conditional requests,
41
+ idempotency, discovery and errors of Restep 1, with a Rack application and a Rails
42
+ concern.
43
+ executables: []
44
+ extensions: []
45
+ extra_rdoc_files: []
46
+ files:
47
+ - LICENSE
48
+ - README.md
49
+ - lib/restep.rb
50
+ - lib/restep/body.rb
51
+ - lib/restep/collection.rb
52
+ - lib/restep/conditional.rb
53
+ - lib/restep/context.rb
54
+ - lib/restep/cursor.rb
55
+ - lib/restep/discovery.rb
56
+ - lib/restep/envelope.rb
57
+ - lib/restep/idempotency.rb
58
+ - lib/restep/operations.rb
59
+ - lib/restep/problem.rb
60
+ - lib/restep/query.rb
61
+ - lib/restep/query_string.rb
62
+ - lib/restep/rack_app.rb
63
+ - lib/restep/rails/controller.rb
64
+ - lib/restep/rails/routes.rb
65
+ - lib/restep/request.rb
66
+ - lib/restep/resolver.rb
67
+ - lib/restep/types.rb
68
+ - lib/restep/version.rb
69
+ homepage: https://w3id.org/restep/tools/restep-ruby/
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ homepage_uri: https://w3id.org/restep/tools/restep-ruby/
74
+ source_code_uri: https://github.com/restep-spec/restep-ruby
75
+ bug_tracker_uri: https://github.com/restep-spec/restep-ruby/issues
76
+ documentation_uri: https://w3id.org/restep/1/
77
+ rubygems_mfa_required: 'true'
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '3.4'
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubygems_version: 4.0.14
93
+ specification_version: 4
94
+ summary: 'Restep 1 for Ruby: the protocol on Rack and Active Record'
95
+ test_files: []