Repository navigation
Expand file tree
/
Copy pathproblem.go
More file actions
182 lines (168 loc) · 6.15 KB
/
Copy pathproblem.go
File metadata and controls
182 lines (168 loc) · 6.15 KB
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
package sdk
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/kasmtech/go-sdk/internal/generated"
)
// Error is the single error type for API failures. It carries the RFC 9457
// problem+json fields when the server sent them and falls back to the HTTP
// status otherwise. Check the kind with errors.Is against the status
// sentinels (ErrNotFound, ErrConflict, ...) and read the fields with
// errors.As.
type Error struct {
Op string // operation, e.g. "zones.list"
Status int
Title string
Detail string
Type string
Instance string
// Validation holds field-level messages from a 422 response.
Validation []string
// Header is the response's headers, for Retry-After and the like.
Header http.Header
// Problem is the typed body when it has fields beyond the RFC 9457 ones:
// from a typed method, the schema the operation declares for the status
// (*ImportProblemDetail for a config import, for example); otherwise,
// and from Do, by problem type: *CaptchaRequiredProblem,
// *NoResourcesProblem, *LaunchConfigRequiredProblem,
// *EgressSelectionRequiredProblem, *RdpClientRequiredProblem or
// *PersistentProfileModeProblem. Nil for every other response.
Problem any
}
func (e *Error) Error() string {
var b strings.Builder
fmt.Fprintf(&b, "%s: %d", e.Op, e.Status)
if e.Title != "" {
b.WriteString(" ")
b.WriteString(e.Title)
}
if e.Detail != "" {
b.WriteString(": ")
b.WriteString(e.Detail)
}
for _, v := range e.Validation {
b.WriteString("\n - ")
b.WriteString(v)
}
return b.String()
}
// Status sentinels, matched by errors.Is against an *Error's status.
// ErrForbidden covers both a missing permission and a feature the licence
// lacks; the spec gives the two no separate problem types.
var (
ErrBadRequest = errors.New("bad request") // 400
ErrUnauthenticated = errors.New("unauthenticated") // 401
ErrForbidden = errors.New("forbidden") // 403
ErrNotFound = errors.New("not found") // 404
ErrConflict = errors.New("conflict") // 409
ErrPayloadTooLarge = errors.New("payload too large") // 413
ErrValidation = errors.New("validation failed") // 422
ErrRateLimited = errors.New("rate limited") // 429
ErrServer = errors.New("server error") // 5xx
)
var statusSentinels = map[int]error{
http.StatusBadRequest: ErrBadRequest,
http.StatusUnauthorized: ErrUnauthenticated,
http.StatusForbidden: ErrForbidden,
http.StatusNotFound: ErrNotFound,
http.StatusConflict: ErrConflict,
http.StatusRequestEntityTooLarge: ErrPayloadTooLarge,
http.StatusUnprocessableEntity: ErrValidation,
http.StatusTooManyRequests: ErrRateLimited,
}
// Is reports whether target is the sentinel for e's status.
func (e *Error) Is(target error) bool {
if target == ErrServer {
return e.Status >= 500
}
s, ok := statusSentinels[e.Status]
return ok && s == target
}
// ConnectionError is a failure before any HTTP response: DNS, TLS, a refused
// connection, a timeout or a cancelled context. It is never an *Error.
// errors.As reaches the cause (*net.DNSError, x509.UnknownAuthorityError, ...)
// through Unwrap.
type ConnectionError struct {
Op string
Err error
}
func (e *ConnectionError) Error() string { return e.Op + ": " + e.Err.Error() }
func (e *ConnectionError) Unwrap() error { return e.Err }
// sendError wraps an error from sending a request: a *ConnectionError when
// the HTTP client failed, the error as is otherwise.
func sendError(op string, err error) error {
var ue *url.Error
if errors.As(err, &ue) {
return &ConnectionError{Op: op, Err: ue.Err}
}
return fmt.Errorf("%s: %w", op, err)
}
// problemSchemas builds the typed body for each problem type whose schema
// adds fields.
var problemSchemas = map[string]func() any{
"captcha-required": func() any { return &generated.CaptchaRequiredProblem{} },
"no-resources": func() any { return &generated.NoResourcesProblem{} },
"launch-config-required": func() any { return &generated.LaunchConfigRequiredProblem{} },
"egress-selection-required": func() any { return &generated.EgressSelectionRequiredProblem{} },
"rdp-client-required": func() any { return &generated.RdpClientRequiredProblem{} },
"persistent-profile-mode-unavailable": func() any { return &generated.PersistentProfileModeProblem{} },
}
// errorFrom builds an *Error from a non-success response. It understands
// problem+json bodies, FastAPI-style 422 validation bodies, and falls back to
// the HTTP status text.
func errorFrom(op string, resp *http.Response, body []byte) *Error {
e := &Error{Op: op, Status: resp.StatusCode, Title: http.StatusText(resp.StatusCode), Header: resp.Header}
ct := resp.Header.Get("Content-Type")
switch {
case strings.HasPrefix(ct, "application/problem+json"):
var p generated.ProblemDetail
if json.Unmarshal(body, &p) == nil {
if p.Title != "" {
e.Title = p.Title
}
e.Detail = p.Detail
// type is a union of the ProblemType catalog and about:blank;
// both are strings.
if p.Type != nil {
if raw, err := p.Type.MarshalJSON(); err == nil {
_ = json.Unmarshal(raw, &e.Type)
}
}
if v, err := p.Instance.Get(); err == nil {
e.Instance = v
}
}
if mk := problemSchemas[e.Type]; mk != nil {
if v := mk(); json.Unmarshal(body, v) == nil {
e.Problem = v
}
}
case resp.StatusCode == http.StatusUnprocessableEntity:
var v generated.HTTPValidationError
if json.Unmarshal(body, &v) == nil && v.Detail != nil {
for _, d := range *v.Detail {
e.Validation = append(e.Validation, fmt.Sprintf("%s: %s", joinLoc(d.Loc), d.Msg))
}
}
default:
if len(body) > 0 && len(body) < 512 {
e.Detail = strings.TrimSpace(string(body))
}
}
return e
}
func joinLoc(loc []generated.ValidationError_Loc_Item) string {
parts := make([]string, 0, len(loc))
for _, l := range loc {
if s, err := l.AsValidationErrorLoc0(); err == nil {
parts = append(parts, s)
} else if n, err := l.AsValidationErrorLoc1(); err == nil {
parts = append(parts, fmt.Sprint(n))
}
}
return strings.Join(parts, ".")
}