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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +224 -0
- data/lib/restep/body.rb +142 -0
- data/lib/restep/collection.rb +378 -0
- data/lib/restep/conditional.rb +56 -0
- data/lib/restep/context.rb +42 -0
- data/lib/restep/cursor.rb +55 -0
- data/lib/restep/discovery.rb +109 -0
- data/lib/restep/envelope.rb +41 -0
- data/lib/restep/idempotency.rb +92 -0
- data/lib/restep/operations.rb +289 -0
- data/lib/restep/problem.rb +105 -0
- data/lib/restep/query.rb +469 -0
- data/lib/restep/query_string.rb +37 -0
- data/lib/restep/rack_app.rb +59 -0
- data/lib/restep/rails/controller.rb +83 -0
- data/lib/restep/rails/routes.rb +33 -0
- data/lib/restep/request.rb +42 -0
- data/lib/restep/resolver.rb +84 -0
- data/lib/restep/types.rb +147 -0
- data/lib/restep/version.rb +3 -0
- data/lib/restep.rb +57 -0
- metadata +95 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: e45951953989197708a197ecd79a9f9db28ec86798354bf6c93e96ec51407449
|
|
4
|
+
data.tar.gz: 9a8365b9a307fe04e16fa8542f932e885d15dc88e480ab5e0a7f76e3820409fd
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: b63bee607cd69270a03a450b54e56e2c5194379deaec33db31135a51693d385d2d7bdf2171fad1a0530740878886106eb2fb9cb82ec4cdd3f521019f4b11bb65
|
|
7
|
+
data.tar.gz: 4110306bac6c2f758eabdc320d6a6e0f53d9746b48086dd944c06b08839f72e8e998ba4e4eace369dc182769ef9f8fbe39cbcee463eba3942c0e90b27fc99067
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Manuel Albarran
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# restep (Ruby)
|
|
2
|
+
|
|
3
|
+
[Restep 1](https://w3id.org/restep/1/) for Ruby (draft 7: discovery declares
|
|
4
|
+
`"restep": "1.0-draft.7"`), on Rack and Active Record. It is the protocol part, with no domain:
|
|
5
|
+
you declare your collections and their Active Record models; the gem parses the request in the
|
|
6
|
+
order of §5.4 and answers discovery, lists with filters, sort and cursors, reads, writes, ETags and
|
|
7
|
+
conditional requests, idempotency and problem+json errors. Use it as a single Rack application or
|
|
8
|
+
inside Rails controllers.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
gem install restep
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
or in your `Gemfile`:
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
gem "restep"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Ruby 3.4 or later, Rack 3 and Active Record 8. The SQL it writes is for **PostgreSQL** (see
|
|
21
|
+
[Limits](#limits)).
|
|
22
|
+
|
|
23
|
+
## Declare the collections
|
|
24
|
+
|
|
25
|
+
```ruby
|
|
26
|
+
require "restep"
|
|
27
|
+
|
|
28
|
+
GENRES = %w[essay novel poetry].freeze
|
|
29
|
+
|
|
30
|
+
BOOKS = Restep::Collection.new(
|
|
31
|
+
name: "books", path: "/books", model: "Book", # the Active Record model, by name
|
|
32
|
+
description: "Books in the library.",
|
|
33
|
+
max_limit: 50, default_limit: 20,
|
|
34
|
+
fields: [
|
|
35
|
+
Restep::Fields.f(name: "id", type: "id", read_only: true),
|
|
36
|
+
Restep::Fields.f(name: "title", type: "string", required: true, max_length: 120),
|
|
37
|
+
Restep::Fields.f(name: "genre", type: "enum", values: GENRES, required: true),
|
|
38
|
+
Restep::Fields.f(name: "pages", type: "integer", required: true, range: 1..5000),
|
|
39
|
+
Restep::Fields.f(name: "created_at", type: "datetime", read_only: true),
|
|
40
|
+
Restep::Fields.f(name: "updated_at", type: "datetime", read_only: true)
|
|
41
|
+
],
|
|
42
|
+
filters: {
|
|
43
|
+
"title" => { "type" => "string", "ops" => %w[eq ne lt le gt ge in], sql: "title" },
|
|
44
|
+
"genre" => { "type" => "enum", "values" => GENRES, "ops" => %w[eq ne in], sql: "genre" }
|
|
45
|
+
},
|
|
46
|
+
sort: { "title" => { sql: "title", type: "string" } }
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
Restep.configure do |c|
|
|
50
|
+
c.collections = { "books" => BOOKS }
|
|
51
|
+
c.idempotency_model = "IdempotencyKey" # table of Idempotency-Key records (§7.1)
|
|
52
|
+
c.cursor_key_path = "config/cursor.key" # created on first use; or set RESTEP_CURSOR_SECRET
|
|
53
|
+
c.docs_path = "DOCS.md" # served at /docs, linked from discovery (optional)
|
|
54
|
+
c.root_path = "/v1" # API root; links include it, discovery paths do not
|
|
55
|
+
end
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The model needs `created_at` and `updated_at`; the gem sets them. Field types: `id`, `string`,
|
|
59
|
+
`enum`, `integer`, `decimal` (with `scale`), `boolean`, `date`, `datetime` and `relation` (to-one,
|
|
60
|
+
with `relation:` naming the target collection and `column:` the foreign key).
|
|
61
|
+
|
|
62
|
+
## With Rack
|
|
63
|
+
|
|
64
|
+
```ruby
|
|
65
|
+
# config.ru
|
|
66
|
+
require_relative "app" # the declarations above and the Active Record connection
|
|
67
|
+
|
|
68
|
+
use Restep::Envelope # 501 for unknown methods, CORS preflight, profile link and CORS headers
|
|
69
|
+
run Restep::RackApp.new(logger: Logger.new($stderr))
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`Restep::RackApp` is a single entry point: it resolves the resource itself and reports errors
|
|
73
|
+
within the precedences of §5.4 (404, 405, 400, 415, 413, 406, then 412, 422 and 409; a replay or a
|
|
74
|
+
409 `request_in_progress` in place of 412 and of the errors that depend on the stored item).
|
|
75
|
+
|
|
76
|
+
## With Rails
|
|
77
|
+
|
|
78
|
+
```ruby
|
|
79
|
+
# config/application.rb
|
|
80
|
+
require "restep/rails/controller"
|
|
81
|
+
require "restep/rails/routes"
|
|
82
|
+
|
|
83
|
+
config.middleware.delete Rack::ETag # Restep sets its own validators
|
|
84
|
+
config.middleware.delete Rack::ConditionalGet
|
|
85
|
+
config.middleware.insert_before 0, Restep::Envelope
|
|
86
|
+
config.exceptions_app = Restep::Rails::Controller.exceptions_app
|
|
87
|
+
|
|
88
|
+
# app/controllers/books_controller.rb
|
|
89
|
+
class BooksController < ApplicationController
|
|
90
|
+
include Restep::Rails::Controller
|
|
91
|
+
before_action :set_record, only: %i[show update destroy]
|
|
92
|
+
before_action { @restep = restep_context(kind: @record ? :item : :collection, collection: BOOKS, record: @record) }
|
|
93
|
+
|
|
94
|
+
def index = render_restep(Restep::Operations.list(@restep))
|
|
95
|
+
def show = render_restep(Restep::Operations.show(@restep))
|
|
96
|
+
def create = render_restep(Restep::Operations.create(@restep))
|
|
97
|
+
def update = render_restep(Restep::Operations.update(@restep))
|
|
98
|
+
def destroy = render_restep(Restep::Operations.destroy(@restep))
|
|
99
|
+
|
|
100
|
+
private
|
|
101
|
+
|
|
102
|
+
def set_record = @record = Restep::Resolver.find!(BOOKS, params[:id])
|
|
103
|
+
end
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The concern adds the 414 and exact-path checks as `before_action`s, turns `Restep::Problem` and any
|
|
107
|
+
other exception into problem+json, and writes the operation's status, headers and body as they are
|
|
108
|
+
(`render_restep`). Restep reads the raw query string and body, not `params`. In
|
|
109
|
+
`config/routes.rb`, `restep_action :books, :archive` routes a §11.1 action (`/books/7:archive`),
|
|
110
|
+
which the Rails router cannot express on its own; anything without a route should go to a fallback
|
|
111
|
+
controller that calls `Restep::Resolver.resolve` and raises `Restep::Resolver.method_not_allowed`,
|
|
112
|
+
so that 404 comes before 405.
|
|
113
|
+
|
|
114
|
+
## API
|
|
115
|
+
|
|
116
|
+
### `Restep.configure`
|
|
117
|
+
|
|
118
|
+
| Option | What it is |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `collections` | `{ "name" => Restep::Collection }`: the collections of the API |
|
|
121
|
+
| `singletons` | `{ "name" => Restep::Collection }` built with `singleton: true` (§5.9) |
|
|
122
|
+
| `reasons` | Catalogue of domain reasons for 409 and 422 (§5.4), published in discovery |
|
|
123
|
+
| `idempotency_model` | Active Record model, or its name, that stores `Idempotency-Key` records (§7.1) |
|
|
124
|
+
| `cursor_key_path` | File with the cursor secret, created if missing. `RESTEP_CURSOR_SECRET` takes precedence |
|
|
125
|
+
| `docs_path` | Human documentation, served at `/docs` with `rel="service-doc"` (§4.2) |
|
|
126
|
+
| `root_path` | Path of the API root without the final slash: `""` (default) or `"/v1"` (§2) |
|
|
127
|
+
|
|
128
|
+
### `Restep::Collection.new`
|
|
129
|
+
|
|
130
|
+
| Argument | What it is |
|
|
131
|
+
|---|---|
|
|
132
|
+
| `name`, `path`, `description` | Name in discovery, path relative to the API root, description |
|
|
133
|
+
| `model` | Name of the Active Record model, resolved on first use |
|
|
134
|
+
| `fields` | `Restep::Fields.f(name:, type:, ...)`: `column`, `values`, `nullable`, `required`, `default`, `read_only` (a field only the server sets, other than `id`: a POST ignores it whatever its value, a PATCH accepts only its current value, so no request sets it, §5.1), `max_length`, `pattern`, `range`, `scale`, `relation`, `description` |
|
|
135
|
+
| `filters` | `{ "field" => { "type", "ops", sql: "column" } }`; `id_like: true` for ids compared as strings; `"required" => true` for a filter every list request must carry (§6.1). Operators: `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `in`, `nin`, `null`, and `prefix` and `contains` on strings (by code points) |
|
|
136
|
+
| `named_filters` | `{ "name" => { "description", sql: ->(value) { ["SQL ?", value] } } }` (§6.1); a switch (no `"type"`) may declare `"default" => true`, which applies to every list request unless it sends `filter[name]=false`, and any named filter `"required" => true` |
|
|
137
|
+
| `sort` | `{ "field" => { sql: "column", type: "string" } }` |
|
|
138
|
+
| `max_limit`, `default_limit` | Page size limits (§6.4) |
|
|
139
|
+
| `conflicts` | `{ unique: ->(rec) { Problem }, foreign_key: ->(rec) { Problem } }`: the 409 for a database constraint |
|
|
140
|
+
| `actions` | `Restep::Fields.action(name, on: "item" \| "collection", method:, safe:, idempotent:, input:, output:, effects:, available:, unavailable:, run:)` (§11.1) |
|
|
141
|
+
| `singleton` | `true` for a singleton |
|
|
142
|
+
| `method_effects` | Only on a singleton: the effects of its `PATCH`, `{ "PATCH" => [] }` or a list out of `destroys`, `external` and `charges` (§4.3, §5.9); left out, a client counts all three |
|
|
143
|
+
|
|
144
|
+
### Actions (§11.1)
|
|
145
|
+
|
|
146
|
+
`Restep::Fields.action` checks the declaration when the domain loads: only a safe action uses
|
|
147
|
+
`GET`, a safe one is also idempotent, `new` is reserved for the safe `GET` collection action that
|
|
148
|
+
gives the starting values of a new item, `changes` is reserved, and `effects` takes `destroys`,
|
|
149
|
+
`external` and `charges` (a safe action, only `charges`). `output` is the schema of a safe action's
|
|
150
|
+
result. At run time:
|
|
151
|
+
|
|
152
|
+
- an item action's `run` changes the item, and the gem answers 200 with the item, its new `ETag` and
|
|
153
|
+
`Content-Location`, or, with `Prefer: return=minimal`, 204 without `ETag`;
|
|
154
|
+
- a collection action's `run` returns `[status, body]`: an unsafe one answers 201 or 204, a safe one
|
|
155
|
+
200 only with a declared `output` (anything else is a 500, as a programming error);
|
|
156
|
+
- an action declared `idempotent: true` ignores `Idempotency-Key`, a malformed one too;
|
|
157
|
+
- a `GET` action takes no `params`, so it answers any query parameter with `400
|
|
158
|
+
unsupported_parameter` (§5.3, §11.1);
|
|
159
|
+
- a replay of an action's `200` (or of a `201`) after the item changed carries the item's current
|
|
160
|
+
representation, with its `ETag`, `_etag` and `Content-Location`, never the stored body with
|
|
161
|
+
validators that are no longer true (§7.1);
|
|
162
|
+
- a replay of a response without a body (a `201` with `Prefer: return=minimal`) keeps its status
|
|
163
|
+
and `Location` but carries no `ETag`, even when the item still exists: the client reads the item
|
|
164
|
+
at `Location` (§7.3).
|
|
165
|
+
|
|
166
|
+
Integer filter operands follow the number grammar of RFC 8259 §6, exponent included: `20`, `20.0`
|
|
167
|
+
and `2e1` are the same operand, and `+20`, `.5`, `020`, `0x14` and `20.5` give `400
|
|
168
|
+
invalid_parameter` (§6.1). An operand of more than 8192 digits is over the gem's limit (§5.3) and
|
|
169
|
+
gives `invalid_parameter` too, with the limit in `detail`; it is never replaced by another value.
|
|
170
|
+
Within it, an operand is compared exactly, even outside the field's range.
|
|
171
|
+
|
|
172
|
+
### Pieces
|
|
173
|
+
|
|
174
|
+
| Constant | What it does |
|
|
175
|
+
|---|---|
|
|
176
|
+
| `Restep::RackApp` | Single-entry-point Rack application |
|
|
177
|
+
| `Restep::Envelope` | Outer middleware: 501, CORS preflight, profile link and CORS on every response |
|
|
178
|
+
| `Restep::Rails::Controller` | Concern for Rails controllers: `restep_context`, `render_restep`, `rescue_from`, `exceptions_app` |
|
|
179
|
+
| `Restep::Rails::Routes` | `restep_action` for `config/routes.rb` |
|
|
180
|
+
| `Restep::Operations` | `discovery`, `list`, `show`, `create`, `update`, `destroy`, `action`, `status`, `docs`: each returns `[status, headers, body]` |
|
|
181
|
+
| `Restep::Resolver` | Steps 1 and 2 of §5.4: which resource a path names (404) and which methods it allows (405) |
|
|
182
|
+
| `Restep::Context` | Steps 3 and 4: reserved parameters, headers, body and `Accept` (400, 415, 413, 406), and 414 |
|
|
183
|
+
| `Restep::Problem` | A Restep error; `raise Restep::Problem.new(409, "conflict", reason: "...", detail: "...")`. The codes are the closed table of §5.4 (`Restep::Problem::CODES`); a status it does not list takes `http_` and its digits (`Restep::Problem.new(431, nil)`), and a code that does not go with its status raises `ArgumentError`. Every problem is `no-store` and never carries `CDN-Cache-Control` |
|
|
184
|
+
| `Restep::Query`, `Restep::Cursor`, `Restep::Conditional`, `Restep::Idempotency`, `Restep::Discovery` | Query parsing and SQL, encrypted keyset cursor, preconditions, idempotency, discovery |
|
|
185
|
+
|
|
186
|
+
## Limits
|
|
187
|
+
|
|
188
|
+
- **PostgreSQL.** Filters and cursors write PostgreSQL casts (`::bigint`, `::numeric`, `::date`,
|
|
189
|
+
`::timestamptz`), and idempotency locks its record with `FOR UPDATE NOWAIT`. Text columns should
|
|
190
|
+
use `COLLATE "C"`, because discovery declares the `codepoint` collation for string filters and
|
|
191
|
+
sorts. On SQLite, string and enum filters (`prefix` and `contains` included), sort, cursors, reads and writes without
|
|
192
|
+
`Idempotency-Key` work (that is what the tests use); integer, decimal, date and datetime filters
|
|
193
|
+
and idempotency do not.
|
|
194
|
+
- Profiles `core`, `query`, `writes` and `cache`, and the `actions` extension. No `include`,
|
|
195
|
+
subcollections, `sync`, `batch`, `filter-expr`, `query-method`, `oauth` or `inherit`; no language
|
|
196
|
+
maps or localized fields, local date-times, durations, `upload`, `upsert` or `reusable_ids`;
|
|
197
|
+
filters do not go through to-many relationships (`quantifier`); actions take no `params`.
|
|
198
|
+
- One anonymous principal: no authentication.
|
|
199
|
+
- Ids are generated by the database (`id_from` is `server`).
|
|
200
|
+
|
|
201
|
+
## Tests
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
bundle install
|
|
205
|
+
bundle exec rake test
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
The tests serve a small API (books, plus journals for what draft 7 added) on an in-memory SQLite database with
|
|
209
|
+
`Restep::Envelope` and `Restep::RackApp`, and check discovery, lists, filters, sort, cursors,
|
|
210
|
+
errors, ETags with `If-None-Match` and `If-Match`, and writes. `test/config.ru` serves the same API
|
|
211
|
+
to run [restep-check](https://w3id.org/restep/tools/restep-check/) against it:
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
RESTEP_TEST_DATABASE=/tmp/restep-test.sqlite3 bundle exec puma test/config.ru # needs puma
|
|
215
|
+
npx restep-check http://localhost:9292/
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Code and issues
|
|
219
|
+
|
|
220
|
+
Code and issues: <https://github.com/restep-spec/restep-ruby>. That repository is generated from the Restep
|
|
221
|
+
site, where the tool is developed alongside the [specification](https://w3id.org/restep/1/) and the reference
|
|
222
|
+
server.
|
|
223
|
+
|
|
224
|
+
MIT licensed.
|
data/lib/restep/body.rb
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
module Restep
|
|
2
|
+
# Request headers and body, in the order of §5.4: 400 (headers), 415, 406, 413, 400 (body),
|
|
3
|
+
# with the shortcuts it allows ("need not parse a body whose media type it rejects, read past
|
|
4
|
+
# its size limit").
|
|
5
|
+
module Body
|
|
6
|
+
MAX_BYTES = 64 * 1024
|
|
7
|
+
|
|
8
|
+
# A body with an unpaired surrogate (§3): JSON, but not an I-JSON message. Its 422 waits for
|
|
9
|
+
# object!, as that of a body that is not an object does. It hashes as its own marker for the
|
|
10
|
+
# Idempotency-Key fingerprint.
|
|
11
|
+
Unpaired = Struct.new(:problem) do
|
|
12
|
+
def to_json(*) = JSON.generate("$unpaired-surrogate")
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
def media_type(content_type)
|
|
18
|
+
return nil if content_type.nil? || content_type.strip.empty?
|
|
19
|
+
type, *params = content_type.split(";")
|
|
20
|
+
charset = params.map { |x| x.strip.split("=", 2) }.find { |k, _| k&.downcase == "charset" }&.last
|
|
21
|
+
[type.strip.downcase, charset&.delete('"')&.downcase]
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Accepts the JSON response if Accept admits application/json (or there is no Accept, or it
|
|
25
|
+
# is malformed: RFC 9110 allows ignoring it).
|
|
26
|
+
def accepts_json?(accept)
|
|
27
|
+
return true if accept.nil? || accept.strip.empty?
|
|
28
|
+
ranges = accept.split(",").map do |r|
|
|
29
|
+
type, *params = r.split(";").map(&:strip)
|
|
30
|
+
q = params.map { |x| x.split("=", 2) }.find { |k, _| k&.downcase == "q" }&.last
|
|
31
|
+
qv = q.nil? ? 1.0 : (q.match?(/\A(0(\.[0-9]{0,3})?|1(\.0{0,3})?)\z/) ? q.to_f : nil)
|
|
32
|
+
return true if qv.nil? # malformed range: the whole header is ignored
|
|
33
|
+
[type.to_s.downcase, qv]
|
|
34
|
+
end
|
|
35
|
+
best = ->(t) { ranges.select { |rt, _| rt == t }.map(&:last).max }
|
|
36
|
+
q = best.("application/json") || best.("application/*") || best.("*/*")
|
|
37
|
+
!q.nil? && q.positive?
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Returns the body's JSON value (an object or not: see object!) or raises 415, 413 or 400, in
|
|
41
|
+
# that order. Before the 413, the 406 has to be checked, as it comes first in §5.4: the caller
|
|
42
|
+
# does it by passing accept_ok.
|
|
43
|
+
# empty_is_object: §11.1, a POST action takes an empty body, with or without Content-Type,
|
|
44
|
+
# as "{}" sent as application/json.
|
|
45
|
+
def read(request, allowed_types, accept_ok:, empty_is_object: false)
|
|
46
|
+
raw = request.raw_body
|
|
47
|
+
if empty_is_object && raw.empty?
|
|
48
|
+
raise not_acceptable unless accept_ok
|
|
49
|
+
return {}
|
|
50
|
+
end
|
|
51
|
+
mt = media_type(request.content_type)
|
|
52
|
+
# §3 (draft 6): an empty body is also a body; without Content-Type it gives 415, and empty
|
|
53
|
+
# with application/json, 400 (JSON.parse rejects it further down).
|
|
54
|
+
if mt.nil? || !allowed_types.include?(mt[0]) || (mt[1] && mt[1] != "utf-8")
|
|
55
|
+
raise Problem.new(415, "unsupported_media_type",
|
|
56
|
+
detail: "Send the body as #{allowed_types.join(" or ")} (UTF-8).",
|
|
57
|
+
headers: allowed_types.include?("application/merge-patch+json") ? { "accept-patch" => "application/merge-patch+json, application/json" } : {})
|
|
58
|
+
end
|
|
59
|
+
if raw.bytesize > MAX_BYTES
|
|
60
|
+
raise not_acceptable unless accept_ok
|
|
61
|
+
raise Problem.new(413, "content_too_large", detail: "The body takes at most #{MAX_BYTES} bytes.")
|
|
62
|
+
end
|
|
63
|
+
raise Problem.new(400, "bad_request", detail: "The request needs a JSON object as its body.") if raw.empty?
|
|
64
|
+
raw = raw.dup.force_encoding(Encoding::UTF_8)
|
|
65
|
+
raise Problem.new(400, "bad_request", detail: "The body is not valid UTF-8.") unless raw.valid_encoding?
|
|
66
|
+
# §3 (draft 7): a body is an I-JSON message. Duplicate member names give 400 bad_request,
|
|
67
|
+
# because the meaning would depend on the parser; an unpaired surrogate, which the parser
|
|
68
|
+
# refuses, gives the 422 invalid with a format entry that §3 allows.
|
|
69
|
+
doc = begin
|
|
70
|
+
JSON.parse(raw, decimal_class: BigDecimal, allow_nan: false, allow_duplicate_key: false)
|
|
71
|
+
rescue JSON::ParserError => e
|
|
72
|
+
unpaired = nil
|
|
73
|
+
message = e.message.lines.first.to_s.strip
|
|
74
|
+
if message.include?("duplicate key")
|
|
75
|
+
raise Problem.new(400, "bad_request", detail: "The body repeats a member name in an object: #{message[0, 120]}")
|
|
76
|
+
end
|
|
77
|
+
# Deferred like a body that is not an object: object! raises it after the preconditions
|
|
78
|
+
# (§5.4: no 422 from the content while 412 applies).
|
|
79
|
+
if message.include?("surrogate")
|
|
80
|
+
# §3 and §5.4 (draft 7): a body that also has a JSON syntax error (or a duplicate member
|
|
81
|
+
# name) gets 400 bad_request. The parser stops at the first surrogate, so the rest is
|
|
82
|
+
# checked again with the unpaired ones replaced.
|
|
83
|
+
syntax_error!(raw)
|
|
84
|
+
unpaired = Unpaired.new(Problem.invalid([{ "pointer" => "", "code" => "format", "detail" => "The body has an unpaired surrogate." }],
|
|
85
|
+
detail: "The body is not an I-JSON message: it has an unpaired surrogate."))
|
|
86
|
+
end
|
|
87
|
+
unpaired or raise Problem.new(400, "bad_request", detail: "The body is not valid JSON: #{message[0, 120]}")
|
|
88
|
+
end
|
|
89
|
+
# §5.1 and §4.3: a JSON value that is not an object is kept as is; it gives 422 through
|
|
90
|
+
# object!, which the operation calls after the preconditions (§5.4: the 412 comes before the
|
|
91
|
+
# content's 422).
|
|
92
|
+
raise not_acceptable unless accept_ok
|
|
93
|
+
doc
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# A \u escape of a surrogate pair, of a lone surrogate, or any other escape (so that "\\ud800",
|
|
97
|
+
# an escaped backslash followed by text, is not taken for one).
|
|
98
|
+
ESCAPE = /\\u[dD][89abAB][0-9a-fA-F]{2}\\u[dD][c-fC-F][0-9a-fA-F]{2}|\\u[dD][89a-fA-F][0-9a-fA-F]{2}|\\./m
|
|
99
|
+
|
|
100
|
+
# Parses the body again with every unpaired surrogate escape replaced by U+FFFD and raises
|
|
101
|
+
# 400 bad_request if it is still not valid JSON. The pointer of the 422 stays "": §3 allows
|
|
102
|
+
# it when the server cannot locate the string, and the parser does not say where it is.
|
|
103
|
+
def syntax_error!(raw)
|
|
104
|
+
patched = raw.gsub(ESCAPE) { |e| e.length == 6 && e[1] == "u" ? "\\ufffd" : e }
|
|
105
|
+
JSON.parse(patched, decimal_class: BigDecimal, allow_nan: false, allow_duplicate_key: false)
|
|
106
|
+
rescue JSON::ParserError => e
|
|
107
|
+
message = e.message.lines.first.to_s.strip
|
|
108
|
+
what = message.include?("duplicate key") ? "repeats a member name in an object" : "is not valid JSON"
|
|
109
|
+
raise Problem.new(400, "bad_request", detail: "The body #{what}: #{message[0, 120]}")
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# §5.1 and §4.3: a body that is a JSON value but not an object gives 422 invalid, with a
|
|
113
|
+
# type entry at "".
|
|
114
|
+
def object!(doc)
|
|
115
|
+
return doc if doc.is_a?(Hash)
|
|
116
|
+
raise doc.problem if doc.is_a?(Unpaired)
|
|
117
|
+
raise Problem.new(422, "invalid", detail: "The body must be a JSON object.",
|
|
118
|
+
errors: [{ "pointer" => "", "code" => "type", "detail" => "Not a JSON object." }])
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def not_acceptable
|
|
122
|
+
Problem.new(406, "not_acceptable", detail: "This API only produces application/json (and application/problem+json for errors).")
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Idempotency-Key: a Structured Fields string (RFC 9651 §3.3.3), without parameters.
|
|
126
|
+
SF_STRING = /\A[ ]*"((?:[\x20\x21\x23-\x5b\x5d-\x7e]|\\["\\])*)"[ ]*\z/n
|
|
127
|
+
|
|
128
|
+
def idempotency_key(value)
|
|
129
|
+
return nil if value.nil?
|
|
130
|
+
m = SF_STRING.match(value.b)
|
|
131
|
+
unless m && !m[1].empty?
|
|
132
|
+
raise Problem.new(400, "bad_request", detail: "Idempotency-Key must be a Structured Fields string, such as \"8e03978e-40d5\".",
|
|
133
|
+
errors: [{ "header" => "Idempotency-Key", "code" => "format", "detail" => "Not a quoted string." }])
|
|
134
|
+
end
|
|
135
|
+
m[1].gsub(/\\(["\\])/, '\1')
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def prefers_minimal?(prefer_headers)
|
|
139
|
+
prefer_headers.to_s.split(",").any? { |p| p.split(";").first.to_s.strip.downcase.gsub(/\s/, "") == "return=minimal" }
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
end
|