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,41 @@
1
+ module Restep
2
+ # Outer middleware: runs before the whole stack (Rails', or Restep::RackApp directly).
3
+ # - A method the server does not know gives 501 not_implemented (§5.4). Without this, Rails
4
+ # raises ActionController::UnknownHttpMethod and answers 405 without problem+json.
5
+ # - OPTIONS only serves the CORS preflight (§5.8), with no Restep rules.
6
+ # - Profile header (§4.1) and CORS on every response, errors included.
7
+ class Envelope
8
+ KNOWN = %w[GET HEAD POST PUT PATCH DELETE OPTIONS TRACE CONNECT].freeze
9
+ # §5.8 (draft 7): Content-Location joins the list, for the 200 of an action (7.2), and
10
+ # Accept-Post, for the 415 of a collection that only takes uploads (5.1).
11
+ EXPOSE = "ETag, Location, Content-Location, Link, Allow, Accept-Patch, Accept-Post, Retry-After, Deprecation, Sunset, " \
12
+ "Idempotent-Replayed, Preference-Applied, Accept-Query, WWW-Authenticate"
13
+
14
+ def initialize(app) = @app = app
15
+
16
+ def call(env)
17
+ method = env["REQUEST_METHOD"].to_s
18
+ # Rails parses the query and the body as soon as anyone asks for `params`, and its own
19
+ # instrumentation (the "Parameters: ..." log line) asks for it before entering the action:
20
+ # with "filter[a]=1&filter[a][b]=2" it raises BadRequest before the application can give
21
+ # the 404 or the 405 that come first in §5.4. Its caches are filled with empty hashes so
22
+ # that it parses nothing; the application reads QUERY_STRING and the raw body.
23
+ env["action_dispatch.request.query_parameters"] = {}
24
+ env["action_dispatch.request.request_parameters"] = {}
25
+ status, headers, body =
26
+ if method == "OPTIONS"
27
+ [204, { "access-control-allow-methods" => "GET, HEAD, POST, PATCH, DELETE, QUERY",
28
+ "access-control-allow-headers" => "Content-Type, Content-Disposition, If-Match, If-None-Match, Idempotency-Key, Prefer, Authorization, DPoP",
29
+ "access-control-max-age" => "600" }, []]
30
+ elsif !KNOWN.include?(method)
31
+ Problem.rack(501, "not_implemented", detail: "This server does not implement the #{method} method.")
32
+ else
33
+ @app.call(env)
34
+ end
35
+ headers["link"] = [headers["link"], PROFILE_LINK].compact.reject(&:empty?).join(", ")
36
+ headers["access-control-allow-origin"] = "*"
37
+ headers["access-control-expose-headers"] = EXPOSE
38
+ [status, headers, body]
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,92 @@
1
+ module Restep
2
+ # §7.1 with PostgreSQL, valid with several processes.
3
+ #
4
+ # 1. The key's record (with the request hash) is inserted and committed right away, outside
5
+ # the effect's transaction, so another request with the same key sees it.
6
+ # 2. The effect runs in a transaction that first takes the key's row with
7
+ # FOR UPDATE NOWAIT. If another transaction holds it, the request is in progress: 409.
8
+ # 3. The effect and the stored response are committed in the same transaction (atomically). If
9
+ # the process dies halfway, the transaction rolls back and the row stays uncompleted and
10
+ # unlocked: the next retry takes it and runs the effect exactly once.
11
+ # 4. A rejected request (4xx) deletes the row: it does not spend the key.
12
+ module Idempotency
13
+ TTL = 86_400
14
+ REPLAY_HEADERS = %w[content-type location content-location etag preference-applied cache-group-invalidation].freeze
15
+
16
+ module_function
17
+
18
+ # By name or by class: with Rails autoloading, the model does not exist yet at configuration time.
19
+ def model
20
+ m = Restep.config.idempotency_model
21
+ m.is_a?(String) ? Object.const_get(m) : m
22
+ end
23
+
24
+ # precheck: the 409 of the stored state and If-Match/If-None-Match (412), which come before
25
+ # the 422 idempotency_mismatch.
26
+ # Returns [status, headers, body]; the block does the effect inside the transaction.
27
+ # current: the item of the stored response (the one in its body or, without a body, the one
28
+ # in its Location) as a read would give it now: its representation with _etag, nil if it can
29
+ # no longer be read, or :unknown if the response names no item. See replay.
30
+ def run(path:, key:, body:, query:, precheck:, current: ->(_body, _headers) { :unknown })
31
+ scope = { principal: PRINCIPAL, http_method: "POST", path: path, key: key }
32
+ request_hash = Digest::SHA256.hexdigest(Types.canonical_json({ "query" => query, "body" => body }))
33
+ 3.times do
34
+ model.where(scope).where("expires_at < now()").delete_all
35
+ model.insert_all([scope.merge(request_hash: request_hash, expires_at: Time.now.utc + TTL)],
36
+ unique_by: :index_idempotency_keys_unique)
37
+ row = model.find_by(scope)
38
+ next if row.nil? # a rejected request deleted it in between: try again
39
+
40
+ if row.request_hash != request_hash
41
+ precheck.call
42
+ raise Problem.new(422, "idempotency_mismatch",
43
+ detail: "This Idempotency-Key was already used with a different request body; use a new key.")
44
+ end
45
+
46
+ outcome = begin
47
+ model.transaction do
48
+ locked = model.lock("FOR UPDATE NOWAIT").find_by(id: row.id)
49
+ next :retry if locked.nil?
50
+ next replay(locked, current) if locked.completed
51
+ begin
52
+ status, headers, resp_body = yield
53
+ locked.update!(completed: true, status: status, body: resp_body,
54
+ headers: headers.slice(*REPLAY_HEADERS))
55
+ [status, headers, resp_body]
56
+ rescue Problem => e
57
+ locked.destroy!
58
+ e
59
+ end
60
+ end
61
+ rescue ActiveRecord::LockWaitTimeout
62
+ raise Problem.new(409, "request_in_progress",
63
+ detail: "A request with this Idempotency-Key is still running; retry it after Retry-After.",
64
+ headers: { "retry-after" => "1" })
65
+ end
66
+ next if outcome == :retry
67
+ raise outcome if outcome.is_a?(Problem)
68
+ return outcome
69
+ end
70
+ raise Problem.new(409, "request_in_progress", detail: "The Idempotency-Key is busy; retry.", headers: { "retry-after" => "1" })
71
+ end
72
+
73
+ # §7.1: the same status and Location, and a body that gives no more than a read would now.
74
+ # An item that can no longer be read gives no body or ETag. Draft 7: a replay whose body is not
75
+ # the item's current representation must not carry Content-Location, ETag or _etag, so when
76
+ # the item changed after the stored response (another write, or an action's 200 replayed
77
+ # later), the replay carries its current representation, whose validators are true. §7.3
78
+ # (council round 3, decision 5): a replay without a body (a 201 with return=minimal) carries
79
+ # no ETag, even when the item still exists: the stored one may no longer be current, and the
80
+ # current one was not produced by this request; a client that needs one reads Location.
81
+ def replay(row, current)
82
+ headers = (row.headers || {}).merge("idempotent-replayed" => "true")
83
+ rep = current.call(row.body, headers)
84
+ return [row.status, headers.except("content-type", "content-location", "etag"), nil] if rep.nil?
85
+ return [row.status, headers.except("etag"), nil] if row.body.nil?
86
+ return [row.status, headers, row.body] if rep == :unknown
87
+ stored_etag = (JSON.parse(row.body)["_etag"] rescue nil)
88
+ return [row.status, headers, row.body] if stored_etag && stored_etag == rep["_etag"]
89
+ [row.status, headers.merge("etag" => rep["_etag"], "content-type" => "application/json"), JSON.generate(rep)]
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,289 @@
1
+ module Restep
2
+ # What each operation does once steps 1 to 4 of §5.4 are done (Resolver and Context):
3
+ # preconditions (412), validation (422) and conflicts (409), and the response. Each method
4
+ # returns [status, headers, body] with the body as a string or nil; whoever writes it
5
+ # (Restep::RackApp or a Rails controller) drops the body on a HEAD.
6
+ module Operations
7
+ module_function
8
+
9
+ # ---- Reads --------------------------------------------------------------------------
10
+
11
+ # §4.2 (draft 6): the same for everyone, no credentials, so it can be public with max-age.
12
+ def discovery(ctx)
13
+ status, headers, body = read_response(ctx, JSON.generate(Discovery.document), groups: [],
14
+ cache_control: "public, max-age=60")
15
+ headers["link"] = %(<#{Restep.url("/docs")}>; rel="service-doc"; hreflang="es") if Restep.config.docs_path
16
+ [status, headers, body]
17
+ end
18
+
19
+ def list(ctx)
20
+ coll, q = ctx.collection, ctx.query
21
+ rows, token, total = q.run
22
+ items = rows.map { |r| q.project(coll.with_etag(coll.represent(r))) }
23
+ doc = { "items" => items, "next" => token ? q.next_link(ctx.path, token) : nil }
24
+ doc["total"] = total if q.count
25
+ read_response(ctx, JSON.generate(doc), groups: [coll.url] + rows.map { |r| coll.item_url(r.id) })
26
+ end
27
+
28
+ def show(ctx)
29
+ coll, rec = ctx.collection, ctx.record
30
+ rep = coll.with_etag(coll.represent(rec))
31
+ groups = [coll.item_url(rec.id)]
32
+ if ctx.query.fields
33
+ read_response(ctx, JSON.generate(ctx.query.project(rep)), groups: groups)
34
+ else
35
+ read_response(ctx, JSON.generate(rep), groups: groups, etag: rep["_etag"])
36
+ end
37
+ end
38
+
39
+ # §4.2: human-readable documentation, linked with rel="service-doc" (RFC 8631) from the
40
+ # discovery document.
41
+ def docs
42
+ @docs ||= File.read(Restep.config.docs_path).freeze
43
+ [200, { "content-type" => "text/markdown; charset=utf-8", "content-language" => "es",
44
+ "cache-control" => "public, max-age=3600" }, @docs]
45
+ end
46
+
47
+ def status
48
+ ok = begin
49
+ ActiveRecord::Base.connection.select_value("SELECT 1") == 1
50
+ rescue StandardError
51
+ false
52
+ end
53
+ [ok ? 200 : 503, { "content-type" => "application/health+json", "cache-control" => "no-store" },
54
+ JSON.generate({ "status" => ok ? "pass" : "fail" })]
55
+ end
56
+
57
+ # ---- Writes ------------------------------------------------------------------------
58
+
59
+ def create(ctx)
60
+ coll = ctx.collection
61
+ precheck = precheck_collection(ctx)
62
+ effect = lambda do
63
+ ActiveRecord::Base.transaction(requires_new: true) do
64
+ precheck.call
65
+ now = Time.now.utc.floor(6)
66
+ attrs = coll.attributes_for_create(Body.object!(ctx.body))
67
+ rec = coll.model.new(attrs.merge("created_at" => now, "updated_at" => now))
68
+ save_or_conflict(coll, rec)
69
+ rec.reload
70
+ write_result(ctx, 201, rec, coll.represent(rec), location: true)
71
+ end
72
+ end
73
+ return effect.call unless ctx.idempotency_key
74
+ # §7.1 (draft 6): the path is compared after decoding and the query counts toward "the same
75
+ # request".
76
+ Idempotency.run(path: QueryString.decode(ctx.path), key: ctx.idempotency_key, body: ctx.body,
77
+ query: idempotency_query(ctx), precheck: precheck, current: stored_item_current(coll), &effect)
78
+ end
79
+
80
+ def update(ctx)
81
+ coll = ctx.collection
82
+ ActiveRecord::Base.transaction do
83
+ # If-Match and write, atomic against other writes to the same item (§7.2).
84
+ rec = lock!(coll, ctx.record)
85
+ rep = coll.represent(rec)
86
+ Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(rep), safe: false)
87
+ changes = coll.changes_for_patch(rec, Body.object!(ctx.body))
88
+ unless changes.empty?
89
+ rec.assign_attributes(changes.merge("updated_at" => Time.now.utc))
90
+ save_or_conflict(coll, rec)
91
+ rec.reload
92
+ rep = coll.represent(rec)
93
+ end
94
+ write_result(ctx, 200, rec, rep, invalidate: !changes.empty?)
95
+ end
96
+ end
97
+
98
+ def destroy(ctx)
99
+ coll = ctx.collection
100
+ ActiveRecord::Base.transaction do
101
+ rec = lock!(coll, ctx.record)
102
+ Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(coll.represent(rec)), safe: false)
103
+ begin
104
+ ActiveRecord::Base.transaction(requires_new: true) { rec.delete }
105
+ rescue ActiveRecord::InvalidForeignKey
106
+ raise coll.conflict(:foreign_key, rec)
107
+ end
108
+ [204, { "cache-group-invalidation" => sf_list([coll.url, coll.item_url(rec.id)]) }, nil]
109
+ end
110
+ end
111
+
112
+ # ---- Actions (§11.1) ------------------------------------------------------------------
113
+
114
+ # Order of §5.4 within the action: 409 if the stored state does not allow it (it does not
115
+ # depend on the content, so it comes before the preconditions, RFC 9110 §13.2.1), 412 (against
116
+ # the item's ETag, §7.2), 422 on the input, and then the effect.
117
+ def action(ctx)
118
+ a = ctx.action
119
+ return safe_action(ctx, a) if a.method == "GET"
120
+ return collection_action(ctx, a) unless a.item?
121
+ coll = ctx.collection
122
+ precheck = lambda do
123
+ rec = current!(coll, ctx.record)
124
+ unless a.available?(rec)
125
+ raise(a.unavailable&.call(rec) ||
126
+ Problem.new(409, "conflict", detail: "The #{a.name} action is not available in the item's current state."))
127
+ end
128
+ next unless ctx.if_match || ctx.if_none_match
129
+ Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(coll.represent(rec)), safe: false)
130
+ end
131
+ effect = lambda do
132
+ ActiveRecord::Base.transaction(requires_new: true) do
133
+ rec = lock!(coll, ctx.record)
134
+ unless a.available?(rec)
135
+ raise(a.unavailable&.call(rec) ||
136
+ Problem.new(409, "conflict", detail: "The #{a.name} action is not available in the item's current state."))
137
+ end
138
+ Conditional.evaluate(ctx.if_match, ctx.if_none_match, coll.etag(coll.represent(rec)), safe: false)
139
+ input = coll.validate_input(a, Body.object!(ctx.body))
140
+ before = coll.represent(rec)
141
+ a.run.call(rec, input)
142
+ rec.reload
143
+ after = coll.represent(rec)
144
+ write_result(ctx, 200, rec, after, invalidate: after != before, action: true)
145
+ end
146
+ end
147
+ # §11.1: an idempotent action may ignore Idempotency-Key, because repeating it is already safe.
148
+ return effect.call if a.idempotent || ctx.idempotency_key.nil?
149
+ Idempotency.run(path: QueryString.decode(ctx.path), key: ctx.idempotency_key, body: ctx.body,
150
+ query: idempotency_query(ctx), precheck: precheck, current: stored_item_current(coll, ctx.record.id), &effect)
151
+ end
152
+
153
+ # §7.1: the item of a stored response as it is now (another request may have changed or
154
+ # deleted it): the one in its body or, with return=minimal and no body, the one its Location
155
+ # names, or else the action's target (a 204 without Location). Its representation with
156
+ # _etag, nil if it no longer exists, :unknown if the response names no item.
157
+ def stored_item_current(coll, target_id = nil)
158
+ lambda do |body, headers|
159
+ id = (JSON.parse(body)["id"] rescue nil) if body
160
+ id ||= headers["location"]&.split("/")&.last
161
+ id ||= target_id if body.nil?
162
+ next :unknown if id.nil?
163
+ rec = coll.find(id.to_s)
164
+ rec && coll.with_etag(coll.represent(rec))
165
+ end
166
+ end
167
+
168
+ # §7.1: the query of the fingerprint as [name, [values]], sorted by name (the order of
169
+ # different names does not count) and with each name's values in the order received (that
170
+ # one does).
171
+ def idempotency_query(ctx)
172
+ ctx.query.pairs.group_by(&:name).sort_by(&:first).map { |name, pairs| [name, pairs.map(&:value)] }
173
+ end
174
+
175
+ # A safe action with GET: no effects, with ETag and 304 like any read.
176
+ # §11.1 (draft 7): its 200 is the result that output declares; without output, a collection's
177
+ # safe action answers 204, never 200.
178
+ def safe_action(ctx, a)
179
+ target = a.item? ? ctx.record : ctx.collection.model
180
+ status, doc = a.run.call(target, {})
181
+ if !doc.nil? && a.output.nil? && !a.item?
182
+ raise ArgumentError, "the safe action #{a.name} on a collection answers 200 only with a declared output (11.1)"
183
+ end
184
+ return [status, { "cache-control" => "no-cache" }, nil] if doc.nil?
185
+ read_response(ctx, JSON.generate(doc), groups: [ctx.collection.url])
186
+ end
187
+
188
+ def collection_action(ctx, a)
189
+ coll = ctx.collection
190
+ ActiveRecord::Base.transaction(requires_new: true) do
191
+ precheck_collection(ctx).call
192
+ input = coll.validate_input(a, Body.object!(ctx.body))
193
+ status, doc = a.run.call(coll.model, input)
194
+ # §11.1 (draft 7): an unsafe action on a collection has no representation of its own, so
195
+ # it answers 201 with the Location of what it creates, or 204; never 200.
196
+ unless [201, 204].include?(status)
197
+ raise ArgumentError, "the unsafe action #{a.name} on a collection answers 201 or 204, not #{status} (11.1)"
198
+ end
199
+ headers = { "cache-control" => "no-store", "cache-group-invalidation" => sf_list([coll.url]) }
200
+ next [status, headers, nil] if doc.nil?
201
+ [status, headers.merge("content-type" => "application/json"), JSON.generate(doc)]
202
+ end
203
+ end
204
+
205
+ # ---- Support -----------------------------------------------------------------------------
206
+
207
+ # Strong ETag of the body for what is not the full representation of an item (discovery,
208
+ # pages, items with fields): different if anything changes.
209
+ def body_etag(body) = %("#{Digest::SHA256.hexdigest(body)[0, 32]}")
210
+
211
+ def read_response(ctx, body, groups:, etag: nil, cache_control: "no-cache")
212
+ etag ||= body_etag(body)
213
+ headers = { "etag" => etag, "cache-control" => cache_control, "content-type" => "application/json" }
214
+ headers["cache-groups"] = sf_list(groups) unless groups.empty?
215
+ if Conditional.evaluate(ctx.if_match, ctx.if_none_match, etag, safe: true) == :not_modified
216
+ return [304, headers.except("content-type"), nil]
217
+ end
218
+ [200, headers, body]
219
+ end
220
+
221
+ # §7.2: a POST to the collection evaluates the conditions against the ETag of the GET without parameters.
222
+ def precheck_collection(ctx)
223
+ coll = ctx.collection
224
+ lambda do
225
+ next unless ctx.if_match || ctx.if_none_match
226
+ # §7.2 (draft 7): * depends on whether the principal can read the collection, which every
227
+ # principal here can, whether or not its GET carries an ETag; a list compares with the ETag
228
+ # of a GET without parameters, and there is none where a filter is required (6.1).
229
+ etag = begin
230
+ q = Query.new(coll, :collection, "GET", [])
231
+ rows, token, = q.run
232
+ items = rows.map { |r| coll.with_etag(coll.represent(r)) }
233
+ body_etag(JSON.generate({ "items" => items, "next" => token ? q.next_link(coll.url, token) : nil }))
234
+ rescue Problem
235
+ nil
236
+ end
237
+ if ctx.if_none_match == :any
238
+ raise Problem.new(412, "precondition_failed", detail: "If-None-Match: * matches: the collection has a current representation.")
239
+ end
240
+ Conditional.evaluate(ctx.if_match == :any ? nil : ctx.if_match, ctx.if_none_match, etag, safe: false)
241
+ end
242
+ end
243
+
244
+ # A Resolver::Missing is an id that names no item (it may not even be a valid id, such as
245
+ # "07"): it gives 404 without querying, because find_by would turn it into another id ("7").
246
+ def lock!(coll, rec)
247
+ raise gone if rec.is_a?(Resolver::Missing)
248
+ coll.model.lock("FOR UPDATE").find_by(id: rec.id) or raise gone
249
+ end
250
+
251
+ # The item as it is now, without locking it: the same 404 as lock! if it no longer exists
252
+ # (another request deleted it, or the Resolver gave a Resolver::Missing).
253
+ def current!(coll, rec)
254
+ raise gone if rec.is_a?(Resolver::Missing)
255
+ coll.model.find_by(id: rec.id) or raise gone
256
+ end
257
+
258
+ def gone = Problem.new(404, "not_found", detail: "The item no longer exists.")
259
+
260
+ def save_or_conflict(coll, rec)
261
+ ActiveRecord::Base.transaction(requires_new: true) { rec.save! }
262
+ rescue ActiveRecord::RecordNotUnique
263
+ raise coll.conflict(:unique, rec)
264
+ end
265
+
266
+ # action: §7.2 and §11.1 (draft 7). A 200 to an action carries the item's representation with
267
+ # Content-Location (the item's path) and the new item ETag, so it is the client's new copy;
268
+ # the 204 of an action carries no ETag, unlike the minimal response of a POST or a PATCH (7.3).
269
+ def write_result(ctx, status, rec, rep, location: false, invalidate: true, action: false)
270
+ coll = ctx.collection
271
+ rep = coll.with_etag(rep)
272
+ headers = { "etag" => rep["_etag"], "cache-control" => "no-store" }
273
+ headers["location"] = coll.item_url(rec.id) if location
274
+ headers["cache-group-invalidation"] = sf_list([coll.url, coll.item_url(rec.id)]) if invalidate
275
+ if ctx.minimal?
276
+ headers["preference-applied"] = "return=minimal"
277
+ headers.delete("etag") if action
278
+ [status == 201 ? 201 : 204, headers, nil]
279
+ else
280
+ headers["content-location"] = coll.item_url(rec.id) if action
281
+ [status, headers.merge("content-type" => "application/json"), JSON.generate(rep)]
282
+ end
283
+ end
284
+
285
+ def sf_list(items) = items.first(32).map { |g| %("#{g}") }.join(", ")
286
+
287
+ def problem_response(e) = [e.status, e.response_headers, JSON.generate(e.body)]
288
+ end
289
+ end
@@ -0,0 +1,105 @@
1
+ module Restep
2
+ # A Restep error (§5.4) that the controller turns into application/problem+json.
3
+ class Problem < StandardError
4
+ # §5.4 (draft 7): the closed table of codes, in the order of public/1/schema/problem.json, with
5
+ # the status each one goes with and its title. A status the table does not list takes
6
+ # http_ and its three digits as code, never a name derived from the IANA registry.
7
+ CODES = {
8
+ "bad_request" => [400, "Bad request"],
9
+ "invalid_parameter" => [400, "Invalid parameter"],
10
+ "unsupported_parameter" => [400, "Unsupported parameter"],
11
+ "idempotency_key_required" => [400, "Idempotency key required"],
12
+ "unauthenticated" => [401, "Unauthenticated"],
13
+ "forbidden" => [403, "Forbidden"],
14
+ "not_found" => [404, "Not found"],
15
+ "method_not_allowed" => [405, "Method not allowed"],
16
+ "not_acceptable" => [406, "Not acceptable"],
17
+ "request_timeout" => [408, "Request timeout"],
18
+ "conflict" => [409, "Conflict"],
19
+ "request_in_progress" => [409, "Request in progress"],
20
+ "state_expired" => [410, "State expired"],
21
+ "retired" => [410, "Retired"],
22
+ "precondition_failed" => [412, "Precondition failed"],
23
+ "content_too_large" => [413, "Content too large"],
24
+ "uri_too_long" => [414, "URI too long"],
25
+ "unsupported_media_type" => [415, "Unsupported media type"],
26
+ "misdirected_request" => [421, "Misdirected request"],
27
+ "invalid" => [422, "Invalid data"],
28
+ "idempotency_mismatch" => [422, "Idempotency key reused with a different request"],
29
+ "not_executed" => [424, "Not executed"],
30
+ "too_early" => [425, "Too early"],
31
+ "precondition_required" => [428, "Precondition required"],
32
+ "rate_limited" => [429, "Too many requests"],
33
+ "internal" => [500, "Internal server error"],
34
+ "not_implemented" => [501, "Not implemented"],
35
+ "bad_gateway" => [502, "Bad gateway"],
36
+ "unavailable" => [503, "Service unavailable"],
37
+ "gateway_timeout" => [504, "Gateway timeout"]
38
+ }.freeze
39
+ TITLES = CODES.transform_values(&:last).freeze
40
+ # Statuses the table lists: any other takes http_NNN.
41
+ LISTED = CODES.values.map(&:first).uniq.freeze
42
+ # §5.1 and §5.4: fields aimed at shared caches (RFC 9213), which a problem never carries.
43
+ SHARED_CACHE_FIELD = /\A(cdn-cache-control|surrogate-control|[a-z0-9-]+-cdn-cache-control)\z/i
44
+
45
+ # §5.4: the code a status carries. With code nil, the only one the table gives that status,
46
+ # or http_NNN for a status it does not list. A code that does not go with its status is a
47
+ # programming error.
48
+ def self.code_for(status, code = nil)
49
+ raise ArgumentError, "#{status.inspect} is not an error status" unless status.is_a?(Integer) && status.between?(400, 599)
50
+ unless LISTED.include?(status)
51
+ raise ArgumentError, "status #{status} is not in the table of 5.4, so its code is http_#{status}, not #{code}" unless code.nil? || code == "http_#{status}"
52
+ return "http_#{status}"
53
+ end
54
+ listed = CODES.select { |_, (st, _)| st == status }.keys
55
+ return listed.first if code.nil? && listed.size == 1
56
+ raise ArgumentError, "code #{code.inspect} does not go with status #{status}; use one of #{listed.join(", ")} (5.4)" unless listed.include?(code)
57
+ code
58
+ end
59
+
60
+ # Title of a problem: the table's, or the reason phrase of a status the table does not list.
61
+ def self.title_for(status, code)
62
+ TITLES[code] || Rack::Utils::HTTP_STATUS_CODES.fetch(status, "Error")
63
+ end
64
+
65
+ attr_reader :status, :code, :detail, :extra, :headers
66
+
67
+ def initialize(status, code, detail: nil, headers: {}, **extra)
68
+ @status = status
69
+ @code = Problem.code_for(status, code)
70
+ @detail = detail
71
+ @headers = headers
72
+ @extra = extra.compact
73
+ super("#{status} #{code}: #{detail}")
74
+ end
75
+
76
+ def body
77
+ h = { "type" => "#{PROFILE_URI}errors##{code}", "title" => Problem.title_for(status, code),
78
+ "status" => status, "code" => code }
79
+ h["detail"] = detail if detail
80
+ extra.each { |k, v| h[k.to_s] = v }
81
+ h
82
+ end
83
+
84
+ def self.rack(status, code, detail: nil, headers: {}, **extra)
85
+ pr = new(status, code, detail: detail, headers: headers, **extra)
86
+ [status, pr.response_headers, [JSON.generate(pr.body)]]
87
+ end
88
+
89
+ # §5.4: every problem is no-store (428, 429, 431 and 511 must be), whatever its own headers
90
+ # say, and never carries a field aimed at shared caches such as CDN-Cache-Control.
91
+ def response_headers
92
+ own = headers.reject { |k, _| k.to_s.downcase == "cache-control" || SHARED_CACHE_FIELD.match?(k.to_s) }
93
+ { "content-type" => "application/problem+json", "cache-control" => "no-store" }.merge(own)
94
+ end
95
+
96
+ # Shortcuts
97
+ def self.param(code, name, detail)
98
+ new(400, code, detail: detail, parameter: name)
99
+ end
100
+
101
+ def self.invalid(errors, detail: "The request body is not valid.")
102
+ new(422, "invalid", detail: detail, errors: errors)
103
+ end
104
+ end
105
+ end