-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror_contract.go
More file actions
293 lines (267 loc) · 6.89 KB
/
Copy patherror_contract.go
File metadata and controls
293 lines (267 loc) · 6.89 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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/url"
"strings"
"github.com/rest-sh/restish/cli"
)
const (
exitSuccess = 0
exitGenericFailure = 1
exitUsage = 2
exitAuthentication = 10
exitAuthorization = 11
exitNotFound = 20
exitConflict = 21
exitValidation = 30
exitServer = 40
exitNetwork = 41
exitRateLimited = 50
)
var (
responseExitCode int
agentErrorWritten bool
)
func resetErrorContractState() {
responseExitCode = 0
agentErrorWritten = false
}
type structuredErrorEnvelope struct {
Error structuredError `json:"error"`
}
type structuredError struct {
Code string `json:"code"`
Message string `json:"message"`
Hint string `json:"hint,omitempty"`
Retryable bool `json:"retryable"`
HTTPStatus int `json:"http_status,omitempty"`
RequestID string `json:"request_id,omitempty"`
RetryAfter string `json:"retry_after,omitempty"`
}
type agentErrorDescriptor interface {
AgentErrorCode() string
AgentErrorHint() string
AgentErrorRetryable() bool
}
func exitCodeForHTTPStatus(status int) int {
switch status {
case 0:
return exitSuccess
case 400, 422:
return exitValidation
case 401:
return exitAuthentication
case 403:
return exitAuthorization
case 404:
return exitNotFound
case 409:
return exitConflict
case 429:
return exitRateLimited
}
if status >= 500 {
return exitServer
}
if status >= 400 {
return exitGenericFailure
}
return exitSuccess
}
func exitCodeForExecutionError(err error, status int) int {
var codedError interface{ ExitCode() int }
if errors.As(err, &codedError) {
return codedError.ExitCode()
}
if code := exitCodeForHTTPStatus(status); code != exitSuccess {
return code
}
var networkError net.Error
var urlError *url.Error
if errors.As(err, &networkError) || errors.As(err, &urlError) {
return exitNetwork
}
if isUsageError(err) {
return exitUsage
}
return exitGenericFailure
}
func isSilentExecutionError(err error) bool {
var silentError interface{ Silent() bool }
return errors.As(err, &silentError) && silentError.Silent()
}
func isUsageError(err error) bool {
if err == nil {
return false
}
message := strings.ToLower(err.Error())
for _, fragment := range []string{
"unknown command",
"unknown flag",
"unknown shorthand flag",
"invalid argument",
"invalid --output",
"required flag",
"requires at least",
"requires exactly",
"accepts ",
} {
if strings.Contains(message, fragment) {
return true
}
}
return false
}
func structuredErrorForExecution(err error, status int) structuredError {
var errorProvider interface{ StructuredError() structuredError }
if errors.As(err, &errorProvider) {
return errorProvider.StructuredError()
}
var descriptor agentErrorDescriptor
if errors.As(err, &descriptor) {
return structuredError{
Code: descriptor.AgentErrorCode(),
Message: err.Error(),
Hint: descriptor.AgentErrorHint(),
Retryable: descriptor.AgentErrorRetryable(),
}
}
if status >= 400 {
return structuredErrorForStatus(status, err.Error(), nil)
}
if exitCodeForExecutionError(err, status) == exitNetwork {
return structuredError{
Code: "NETWORK_ERROR",
Message: err.Error(),
Hint: "Check network connectivity and retry",
Retryable: true,
}
}
if isUsageError(err) {
return structuredError{
Code: "USAGE_ERROR",
Message: err.Error(),
Hint: "Run the command with --help to inspect its arguments and flags",
Retryable: false,
}
}
return structuredError{
Code: "CLI_ERROR",
Message: err.Error(),
Retryable: false,
}
}
func structuredErrorForResponse(resp cli.Response) structuredError {
message := responseErrorMessage(resp.Body)
if message == "" {
message = fmt.Sprintf("DoiT API request failed with HTTP status %d", resp.Status)
}
return structuredErrorForStatus(resp.Status, message, resp.Headers)
}
func structuredErrorForStatus(status int, message string, headers map[string]string) structuredError {
result := structuredError{
Code: "API_ERROR",
Message: message,
HTTPStatus: status,
RequestID: requestID(headers),
}
switch status {
case 400, 422:
result.Code = "VALIDATION_ERROR"
result.Hint = "Review the request arguments and payload"
case 401:
result.Code = "AUTHENTICATION_FAILED"
result.Hint = "Run: dci login"
case 403:
result.Code = "PERMISSION_DENIED"
result.Hint = "Check the active customer context and your DoiT permissions"
case 404:
result.Code = "RESOURCE_NOT_FOUND"
case 409:
result.Code = "RESOURCE_CONFLICT"
case 429:
result.Code = "RATE_LIMITED"
result.Hint = "Retry after the server-provided delay"
result.Retryable = true
result.RetryAfter = firstHeaderValue(headers, "Retry-After", "X-Retry-In")
default:
if status >= 500 {
result.Code = "API_SERVER_ERROR"
result.Hint = "Retry the request; contact DoiT support if the error persists"
result.Retryable = true
}
}
return result
}
func responseErrorMessage(body interface{}) string {
switch value := body.(type) {
case string:
return strings.TrimSpace(value)
case []byte:
return strings.TrimSpace(string(value))
case map[string]interface{}:
for _, key := range []string{"message", "detail", "error_description"} {
if message, ok := value[key].(string); ok && strings.TrimSpace(message) != "" {
return strings.TrimSpace(message)
}
}
switch nested := value["error"].(type) {
case string:
return strings.TrimSpace(nested)
case map[string]interface{}:
for _, key := range []string{"message", "detail", "code"} {
if message, ok := nested[key].(string); ok && strings.TrimSpace(message) != "" {
return strings.TrimSpace(message)
}
}
}
}
return ""
}
func requestID(headers map[string]string) string {
for _, name := range []string{"X-Request-Id", "X-Doit-Trace", "Cf-Ray", "X-Cloud-Trace-Context", "Traceparent"} {
if value := strings.TrimSpace(headerValue(headers, name)); value != "" {
return value
}
}
return ""
}
func firstHeaderValue(headers map[string]string, names ...string) string {
for _, name := range names {
if value := strings.TrimSpace(headerValue(headers, name)); value != "" {
return value
}
}
return ""
}
func writeStructuredError(writer io.Writer, detail structuredError) {
agentErrorWritten = true
_ = json.NewEncoder(writer).Encode(structuredErrorEnvelope{Error: detail})
}
func agentErrorContractEnabled() bool {
return agentMode && agentUAMode != uaModeNonInteractive
}
func executeCLI() error {
return executeCLIWith(cli.Run)
}
func executeCLIWith(run func() error) error {
if !agentErrorContractEnabled() {
return run()
}
cli.Root.SilenceErrors = true
cli.Root.SilenceUsage = true
originalStderr := cli.Stderr
var capturedStderr bytes.Buffer
cli.Stderr = &capturedStderr
err := run()
cli.Stderr = originalStderr
if err == nil || agentErrorWritten {
_, _ = io.Copy(originalStderr, &capturedStderr)
}
return err
}