-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem.go
480 lines (386 loc) · 14.5 KB
/
problem.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package akumu
import (
_ "embed"
"encoding/json"
"fmt"
"maps"
"net/http"
"strings"
"github.com/studiolambda/akumu/utils"
)
// Problem represents a problem details for HTTP APIs.
// See https://datatracker.ietf.org/doc/html/rfc9457 for more information.
type Problem struct {
// err stores the native error of the problem if
// it happens to have one. This struct member can be
// nil if the problem was created manually.
//
// Refer to [NewProblem] to automatically assign an error
// to the new Problem.
err error
// additional stores additional metadata that will be
// appended to the problem JSON representation. It is used
// to serialize and de-serialize properties.
additional map[string]any
// Type member is a JSON string containing a URI reference
// that identifies the problem type.
//
// Consumers MUST use the Type URI (after resolution,
// if necessary) as the problem type's primary identifier.
//
// When this member is not present, its value is assumed
// to be "about:blank".
Type string
// Title member is a string containing a short,
// human-readable summary of the problem type.
//
// It SHOULD NOT change from occurrence to occurrence of
// the problem, except for localization (e.g., using proactive
// content negotiation.
//
// The Title string is advisory and is included only for users
// who are unaware of and cannot discover the semantics of the
// type URI (e.g., during offline log analysis).
Title string
// Detail member is a JSON string containing a human-readable
// explanation specific to this occurrence of the problem.
//
// The Detail string, if present, ought to focus on helping
// the client correct the problem, rather than giving debugging information.
//
// Consumers SHOULD NOT parse the Detail member for information.
//
// Extensions are more suitable and less error-prone ways to obtain
// such information.
Detail string
// The Status member is a JSON number indicating the HTTP status
// code generated by the origin server for this occurrence of the problem.
//
// The "status" member, if present, is only advisory; it conveys the HTTP
// status code used for the convenience of the consumer.
//
// Generators MUST use the same status code in the actual HTTP response,
// to assure that generic HTTP software that does not understand this format
// still behaves correctly.
//
// Consumers can use the status member to determine what the original status
// code used by the generator was when it has been changed
// (e.g., by an intermediary or cache) and when a message's content is
// persisted without HTTP information. Generic HTTP software will still
// use the HTTP status code.
Status int
// The "instance" member is a JSON string containing a URI reference that
// identifies the specific occurrence of the problem.
//
// When the "instance" URI is dereferenceable, the problem details object
// can be fetched from it. It might also return information about the problem
// occurrence in other formats through use of proactive content negotiation.
//
// When the "instance" URI is not dereferenceable, it serves as a unique identifier
// for the problem occurrence that may be of significance to the server but is
// opaque to the client.
//
// When "instance" contains a relative URI, it is resolved relative to the document's
// base URI. However, using relative URIs can cause confusion, and they might not
// be handled correctly by all implementations.
//
// For example, if the two resources "https://api.example.org/foo/bar/123"
// and "https://api.example.org/widget/456" both respond with an "instance" equal
// to the relative URI reference "example-instance", when resolved they will
// identify different resources ("https://api.example.org/foo/bar/example-instance"
// and "https://api.example.org/widget/example-instance", respectively).
//
// As a result, it is RECOMMENDED that absolute URIs be used in "instance" when possible,
// and that when relative URIs are used, they include the full path (e.g., "/instances/123").
Instance string
}
// ProblemControlsResolver is a func that resolves to a response T given
// a [Problem] and a [http.Request].
type ProblemControlsResolver[R any] func(problem Problem, request *http.Request) R
// ProblemControls is the structure used to control how
// [Problem] instances are responded. Those helpers allow
// controlling certain aspects of the default handler.
type ProblemControls struct {
// Lowercase determines if the problem controls
// should lowercase the errors found.
Lowercase ProblemControlsResolver[bool]
// DefaultStatus determines the default status code of a [Problem]
// in case it does not have one defined.
DefaultStatus ProblemControlsResolver[int]
// DefaultType determines the default type of a [Problem]
// in case it does not have one defined.
DefaultType ProblemControlsResolver[string]
// DefaultTitle determines the default title of a [Problem]
// in case it does not have one defined.
DefaultTitle ProblemControlsResolver[string]
// DefaultInstance determines the default instance of a [Problem]
// in case it does not have one defined.
DefaultInstance ProblemControlsResolver[string]
// DefaultDetails determines the default details of a [Problem]
// in case it does not have one defined.
DefaultDetails ProblemControlsResolver[string]
// Errors determines if the problem should contain a stack-trace
// of errors from the error it comes from (if any).
Errors ProblemControlsResolver[bool]
// Response allows customizing the actual Builder response
// that a [Problem] should be resolved to.
Response ProblemControlsResolver[Builder]
}
// ProblemsKey is the context key where the
// problem controls are stored in the request.
type ProblemsKey struct{}
// defaultedProblemControls returns a [ProblemControls] that is defaulted
// with the default values for each field if they are nil on the controls param.
func defaultedProblemControls(controls ProblemControls) ProblemControls {
if controls.Lowercase == nil {
controls.Lowercase = defaultProblemControlsLowercase
}
if controls.DefaultStatus == nil {
controls.DefaultStatus = defaultProblemControlsStatus
}
if controls.DefaultType == nil {
controls.DefaultType = defaultProblemControlsType
}
if controls.DefaultTitle == nil {
controls.DefaultTitle = defaultProblemControlsTitle
}
if controls.DefaultInstance == nil {
controls.DefaultInstance = defaultProblemControlsInstance
}
if controls.DefaultDetails == nil {
controls.DefaultDetails = defaultProblemControlsDetails
}
if controls.Errors == nil {
controls.Errors = defaultProblemControlsErrors
}
if controls.Response == nil {
controls.Response = defaultProblemControlsResponse
}
return controls
}
// Problems return the [ProblemControls] used to determine
// how [Problem] respond to http requests.
func Problems(request *http.Request) (ProblemControls, bool) {
controls, ok := request.
Context().
Value(ProblemsKey{}).(ProblemControls)
return controls, ok
}
// defaultProblemControlsLowercase is the default value for the [ProblemControls] lowercase.
func defaultProblemControlsLowercase(problem Problem, request *http.Request) bool {
return true
}
// defaultProblemControlsStatus is the default value for the [ProblemControls] status.
func defaultProblemControlsStatus(problem Problem, request *http.Request) int {
return http.StatusInternalServerError
}
// defaultProblemControlsType is the default value for the [ProblemControls] type.
func defaultProblemControlsType(problem Problem, request *http.Request) string {
return "about:blank"
}
// defaultProblemControlsTitle is the default value for the [ProblemControls] title.
func defaultProblemControlsTitle(problem Problem, request *http.Request) string {
return http.StatusText(problem.Status)
}
// defaultProblemControlsInstance is the default value for the [ProblemControls] instance.
func defaultProblemControlsInstance(problem Problem, request *http.Request) string {
return request.URL.String()
}
// defaultProblemControlsDetails is the default value for the [ProblemControls] instance.
func defaultProblemControlsDetails(problem Problem, request *http.Request) string {
if traces := problem.Errors(); len(traces) > 0 {
return traces[0].Error()
}
return ""
}
// defaultProblemControlsInstance is the default value for the [ProblemControls] instance.
func defaultProblemControlsErrors(problem Problem, request *http.Request) bool {
return true
}
// ProblemControlsResponseFrom is a helper that generates a [ProblemControlsResolver] with
// the given response content types. It is very useful to map mimes to responses.
func ProblemControlsResponseFrom(responses map[string]Builder) ProblemControlsResolver[Builder] {
return func(problem Problem, request *http.Request) Builder {
accept := utils.ParseAccept(request)
for _, media := range accept.Order() {
if response, ok := responses[media]; ok {
return response
}
}
return Response(problem.Status).
Text(fmt.Sprintf("%d %s\n\n%s", problem.Status, problem.Title, problem.Detail))
}
}
// defaultProblemControlsResponse is the default response that will be
// used on the [ProblemControls]
func defaultProblemControlsResponse(problem Problem, request *http.Request) Builder {
responses := map[string]Builder{
"application/problem+json": Response(problem.Status).
JSON(problem).
Header("Content-Type", "application/problem+json"),
"application/json": Response(problem.Status).
JSON(problem).
Header("Content-Type", "application/problem+json"),
}
return ProblemControlsResponseFrom(responses)(problem, request)
}
// NewProblem creates a new [Problem] from
// the given error and status code.
func NewProblem(err error, status int) Problem {
return Problem{
err: err,
Status: status,
}
}
// Additional returns the additional value of the given key.
//
// Use [Problem.With] to add additional values.
// Use [Problem.Without] to remove additional values.
func (problem Problem) Additional(key string) (any, bool) {
additional, ok := problem.additional[key]
return additional, ok
}
// With adds a new additional value to the given key.
func (problem Problem) With(key string, value any) Problem {
if problem.additional == nil {
problem.additional = map[string]any{key: value}
return problem
}
problem.additional = maps.Clone(problem.additional)
problem.additional[key] = value
return problem
}
// WithError returns a new [Problem] with the given error
// set as the
func (problem Problem) WithError(err error) Problem {
problem.err = err
return problem
}
// WithoutError returns a new [Problem] with the error
// that's associated with it removed.
func (problem Problem) WithoutError() Problem {
problem.err = nil
return problem
}
// Without removes an additional value to the given key.
func (problem Problem) Without(key string) Problem {
if problem.additional == nil {
return problem
}
problem.additional = maps.Clone(problem.additional)
delete(problem.additional, key)
return problem
}
// Error is the error-like string representation of a [Problem].
func (problem Problem) Error() string {
if problem.err != nil {
return fmt.Sprintf("%d %s: %s", problem.Status, http.StatusText(problem.Status), problem.err)
}
return fmt.Sprintf("%d %s: %s", problem.Status, http.StatusText(problem.Status), problem.Title)
}
// Errors returns all the strack-trace of errors that
// are bound to this particular [Problem].
func (problem Problem) Errors() []error {
return stackTrace(problem.err)
}
// Unwrap is used to get the original error from
// the problem to use with the errors pkg.
func (problem Problem) Unwrap() error {
return problem.err
}
// MarshalJSON replaces the default JSON encoding behaviour.
func (problem Problem) MarshalJSON() ([]byte, error) {
mapped := make(map[string]any, len(problem.additional)+5)
mapped["detail"] = problem.Detail
mapped["instance"] = problem.Instance
mapped["status"] = problem.Status
mapped["title"] = problem.Title
mapped["type"] = problem.Type
for key, value := range problem.additional {
mapped[key] = value
}
return json.Marshal(mapped)
}
// UnmarshalJSON replaces the default JSON decoding behaviour.
func (problem *Problem) UnmarshalJSON(data []byte) error {
mapped := make(map[string]any)
if err := json.Unmarshal(data, &mapped); err != nil {
return err
}
if value, ok := mapped["detail"].(string); ok {
problem.Detail = value
}
if value, ok := mapped["instance"].(string); ok {
problem.Instance = value
}
if value, ok := mapped["status"].(float64); ok {
problem.Status = int(value)
}
if value, ok := mapped["title"].(string); ok {
problem.Title = value
}
if value, ok := mapped["type"].(string); ok {
problem.Type = value
}
delete(mapped, "detail")
delete(mapped, "instance")
delete(mapped, "status")
delete(mapped, "title")
delete(mapped, "type")
problem.additional = mapped
return nil
}
// controls returns the [ProblemControls] associated with the request. It is always
// defaulted as well. If not found in the request, a fresh defaulted instance
// is returned.
func (problem Problem) controls(request *http.Request) ProblemControls {
controls := ProblemControls{}
if c, ok := Problems(request); ok {
controls = c
}
return defaultedProblemControls(controls)
}
// Defaulted returns a [Problem] that is defaulted using the given
// request and the current instance.
func (problem Problem) Defaulted(request *http.Request) Problem {
controls := problem.controls(request)
if problem.Type == "" {
problem.Type = controls.DefaultType(problem, request)
}
if problem.Status == 0 {
problem.Status = controls.DefaultStatus(problem, request)
}
if problem.Title == "" {
problem.Title = controls.DefaultTitle(problem, request)
}
if problem.Instance == "" {
problem.Instance = controls.DefaultInstance(problem, request)
}
if problem.Detail == "" {
problem.Detail = controls.DefaultDetails(problem, request)
}
lower := controls.Lowercase(problem, request)
if controls.Errors(problem, request) {
traces := problem.Errors()
messages := make([]string, len(traces))
for i, trace := range traces {
if lower {
messages[i] = strings.ToLower(trace.Error())
continue
}
messages[i] = trace.Error()
}
problem = problem.With("errors", messages)
}
if lower {
problem.Title = strings.ToLower(problem.Title)
problem.Detail = strings.ToLower(problem.Detail)
}
return problem
}
// Respond implements [Responder] interface to implement
// how a problem responds to an http request.
func (problem Problem) Respond(request *http.Request) Builder {
controls := problem.controls(request)
return controls.Response(problem.Defaulted(request), request)
}