Repository navigation
Expand file tree
/
Copy patherrors.go
More file actions
302 lines (277 loc) · 10.5 KB
/
Copy patherrors.go
File metadata and controls
302 lines (277 loc) · 10.5 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
294
295
296
297
298
299
300
301
302
package zipbox
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// ErrorCode is the public error code carried by every Zipbox error. The code is
// the contract; the message is for humans and may change.
type ErrorCode string
// The public error codes. See https://zipbox.ai/docs/errors for causes and fixes.
const (
CodeInvalidRequest ErrorCode = "invalid_request"
CodeUnauthorized ErrorCode = "unauthorized"
CodeForbidden ErrorCode = "forbidden"
CodeNotFound ErrorCode = "not_found"
CodeInsufficientCredits ErrorCode = "insufficient_credits"
CodeConflict ErrorCode = "conflict"
CodeRateLimited ErrorCode = "rate_limited"
CodeBoxNotRunning ErrorCode = "box_not_running"
CodeUnavailable ErrorCode = "unavailable"
// CodeMachineLimitReached: the account holds 250 machine names (a deleted box
// keeps its name); reuse one instead of creating a new one. Never retried. See
// https://zipbox.ai/docs/machine-limit.
CodeMachineLimitReached ErrorCode = "machine_limit_reached"
// CodeBoxKeyChanged: the box's key changed between reading it and sending a
// sealed credential (a claim re-mints it). Tailscale.Connect re-seals once.
CodeBoxKeyChanged ErrorCode = "box_key_changed"
// CodeTailnetNotConnected: private mode needs the box on a tailnet first.
CodeTailnetNotConnected ErrorCode = "tailnet_not_connected"
// CodeTailscaleUnavailableEgressLockdown: company egress lockdown blocks Tailscale on this box.
CodeTailscaleUnavailableEgressLockdown ErrorCode = "tailscale_unavailable_egress_lockdown"
// CodeTailscaleRequiresUpdate: the box's ZipOS predates Tailscale; accept the ZipOS update first.
CodeTailscaleRequiresUpdate ErrorCode = "tailscale_requires_update"
// CodeBoxPrivateUnreachable: the box is private and this device is not on its tailnet.
CodeBoxPrivateUnreachable ErrorCode = "box_private_unreachable"
// Fork refusals, each answered before anything is reserved or the source is
// touched, and never retried.
// CodeNameTaken: the requested name is in use.
CodeNameTaken ErrorCode = "name_taken"
// CodeSourceUnsupported: the source is not a machine a fork supports (its class,
// or, as a fork's own error, its disk layout).
CodeSourceUnsupported ErrorCode = "source_unsupported"
// CodeSourceBusy: the source has another change in flight.
CodeSourceBusy ErrorCode = "source_busy"
// CodePauseRequired: the source is running and the fork did not allow pausing it
// (ForkPauseAndResume).
CodePauseRequired ErrorCode = "pause_required"
// CodeRequiresInteractive: copying the source's machine-scoped credentials needs
// the owner signed in to the dashboard, not an API key.
CodeRequiresInteractive ErrorCode = "requires_interactive"
// CodeIdempotencyMismatch: the Idempotency-Key was already used for a different request.
CodeIdempotencyMismatch ErrorCode = "idempotency_mismatch"
// Why a fork ended without a box (SandboxFork.Error), returned by a waiting
// Fork. Each is final; retrying the same fork fails the same way.
// CodeSourceGone: the source was deleted before it was captured.
CodeSourceGone ErrorCode = "source_gone"
// CodeIdentityReused: the new box came up with the source's key, so it was
// stopped before serving and its disk discarded.
CodeIdentityReused ErrorCode = "identity_reused"
// CodeCopyFailed: the isolated copy could not produce a verified filesystem.
CodeCopyFailed ErrorCode = "copy_failed"
// CodeStartFailed: the new box failed to boot.
CodeStartFailed ErrorCode = "start_failed"
)
const docsErrorsURL = "https://zipbox.ai/docs/errors"
// Error is the single error type every SDK call returns for a failure the
// control plane or a box reported (and for a box that is not ready). Use
// errors.As to inspect it:
//
// var zerr *zipbox.Error
// if errors.As(err, &zerr) && zerr.Code == zipbox.CodeNotFound { … }
//
// A command that exits non-zero is a result, never an Error.
type Error struct {
// Code is the public error code.
Code ErrorCode `json:"code"`
// Status is the HTTP status, or 0 when the error did not come from a response.
Status int `json:"status,omitempty"`
// Message is a human-readable description.
Message string `json:"message"`
// RequestID identifies the request in Zipbox's logs, when the server sent one.
RequestID string `json:"requestId,omitempty"`
// Retryable reports whether the same request may succeed if sent again later.
Retryable bool `json:"retryable"`
// RetryAfter is how long the server asked the caller to wait, when it said. JSON
// carries it as retryAfterMs, the envelope's name (see MarshalJSON).
RetryAfter time.Duration `json:"-"`
// DocsURL points at the docs entry for Code.
DocsURL string `json:"docsUrl"`
// hasRetryAfter distinguishes "retry now" (Retry-After: 0) from no hint.
hasRetryAfter bool
// unsent marks a request that provably never left: the connection or its TLS
// handshake failed. Any method may be retried then, since nothing was sent.
unsent bool
}
// Error implements the error interface.
func (e *Error) Error() string {
if e.Status > 0 {
return fmt.Sprintf("zipbox: %s (%d): %s", e.Code, e.Status, e.Message)
}
return fmt.Sprintf("zipbox: %s: %s", e.Code, e.Message)
}
// MarshalJSON writes the error's fields plus retryAfterMs, RetryAfter in
// milliseconds, when the server said how long to wait.
func (e *Error) MarshalJSON() ([]byte, error) {
type fields Error
out := struct {
*fields
RetryAfterMs *int64 `json:"retryAfterMs,omitempty"`
}{fields: (*fields)(e)}
if e.hasRetryAfter {
ms := e.RetryAfter.Milliseconds()
out.RetryAfterMs = &ms
}
return json.Marshal(out)
}
// IsCode reports whether err is a *Error with the given code.
func IsCode(err error, code ErrorCode) bool {
zerr, ok := asError(err)
return ok && zerr.Code == code
}
func asError(err error) (*Error, bool) {
for err != nil {
if zerr, ok := err.(*Error); ok {
return zerr, true
}
unwrapper, ok := err.(interface{ Unwrap() error })
if !ok {
return nil, false
}
err = unwrapper.Unwrap()
}
return nil, false
}
func docsURLFor(code ErrorCode) string {
return docsErrorsURL + "#" + string(code)
}
// knownCode reports a code this SDK documents. Another code from a later server
// maps by status, as in every SDK.
func knownCode(code ErrorCode) bool {
switch code {
case CodeInvalidRequest, CodeUnauthorized, CodeForbidden, CodeNotFound, CodeInsufficientCredits,
CodeConflict, CodeRateLimited, CodeBoxNotRunning, CodeUnavailable, CodeMachineLimitReached,
CodeBoxKeyChanged, CodeTailnetNotConnected, CodeTailscaleUnavailableEgressLockdown,
CodeTailscaleRequiresUpdate, CodeBoxPrivateUnreachable, CodeNameTaken, CodeSourceUnsupported,
CodeSourceBusy, CodePauseRequired, CodeRequiresInteractive, CodeIdempotencyMismatch,
CodeSourceGone, CodeIdentityReused, CodeCopyFailed, CodeStartFailed:
return true
}
return false
}
func retryableCode(code ErrorCode) bool {
switch code {
case CodeRateLimited, CodeUnavailable, CodeBoxNotRunning:
return true
}
return false
}
// codeForStatus is the status mapping every SDK shares, for responses that
// carry no error envelope (box routes, proxy error pages).
func codeForStatus(status int) ErrorCode {
switch status {
case 400, 413, 422:
return CodeInvalidRequest
case 401:
return CodeUnauthorized
case 402:
return CodeInsufficientCredits
case 403:
return CodeForbidden
case 404:
return CodeNotFound
case 409:
return CodeConflict
case 429:
return CodeRateLimited
case 502:
return CodeBoxNotRunning
}
if status >= 500 {
return CodeUnavailable
}
return CodeInvalidRequest
}
func newError(code ErrorCode, message string) *Error {
return &Error{Code: code, Message: message, Retryable: retryableCode(code), DocsURL: docsURLFor(code)}
}
type envelopeBody struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
RequestID string `json:"requestId"`
Retryable *bool `json:"retryable"`
RetryAfterMs *int64 `json:"retryAfterMs"`
DocsURL string `json:"docsUrl"`
}
// errorFromResponse classifies a non-2xx response. An `{error: {code, …}}` body
// is the public envelope; anything else (box routes answer `{error: "<msg>"}`)
// maps by status.
func errorFromResponse(resp *http.Response, body []byte) *Error {
retryAfter, hasRetryAfter := parseRetryAfter(resp.Header.Get("Retry-After"))
var raw struct {
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(body, &raw) == nil && len(raw.Error) > 0 {
var env envelopeBody
if raw.Error[0] == '{' && json.Unmarshal(raw.Error, &env) == nil && env.Code != "" {
if !knownCode(env.Code) {
env.Code = codeForStatus(resp.StatusCode)
env.DocsURL = ""
}
zerr := &Error{
Code: env.Code,
Status: resp.StatusCode,
Message: env.Message,
RequestID: env.RequestID,
Retryable: retryableCode(env.Code),
RetryAfter: retryAfter,
DocsURL: env.DocsURL,
hasRetryAfter: hasRetryAfter,
}
if env.Retryable != nil {
zerr.Retryable = *env.Retryable
}
if env.RetryAfterMs != nil && !hasRetryAfter {
zerr.RetryAfter = time.Duration(*env.RetryAfterMs) * time.Millisecond
zerr.hasRetryAfter = true
}
if zerr.DocsURL == "" {
zerr.DocsURL = docsURLFor(zerr.Code)
}
return zerr
}
var message string
if json.Unmarshal(raw.Error, &message) == nil {
return statusError(resp, message, retryAfter, hasRetryAfter)
}
}
message := strings.TrimSpace(string(body))
if len(message) > 300 || message == "" {
message = http.StatusText(resp.StatusCode)
}
return statusError(resp, message, retryAfter, hasRetryAfter)
}
func statusError(resp *http.Response, message string, retryAfter time.Duration, hasRetryAfter bool) *Error {
code := codeForStatus(resp.StatusCode)
return &Error{
Code: code,
Status: resp.StatusCode,
Message: message,
RequestID: resp.Header.Get("X-Request-Id"),
Retryable: retryableCode(code),
RetryAfter: retryAfter,
DocsURL: docsURLFor(code),
hasRetryAfter: hasRetryAfter,
}
}
// parseRetryAfter reads `Retry-After` as delta-seconds or an HTTP date.
// The bool is false when the header is absent or unreadable.
func parseRetryAfter(value string) (time.Duration, bool) {
value = strings.TrimSpace(value)
if value == "" {
return 0, false
}
if seconds, err := strconv.ParseFloat(value, 64); err == nil && seconds >= 0 {
return time.Duration(seconds * float64(time.Second)), true
}
if at, err := http.ParseTime(value); err == nil {
if wait := time.Until(at); wait > 0 {
return wait, true
}
return 0, true
}
return 0, false
}