-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherrors.go
More file actions
579 lines (522 loc) · 18.9 KB
/
Copy patherrors.go
File metadata and controls
579 lines (522 loc) · 18.9 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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
package ipfs
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/avast/retry-go/v4"
client "go.lumeweb.com/ipfs-sdk/internal/client"
backend "go.lumeweb.com/ipfs-sdk/internal/download"
httputil "go.lumeweb.com/ipfs-sdk/internal/http"
)
// Operation identifiers for error message mapping.
// Defined as iota constants for automatic incrementing IDs.
const (
// DNS operations
OpListZones = iota
OpCreateZone
OpGetZone
OpDeleteZone
OpListRecords
OpGetRecord
OpCreateRecord
OpUpdateRecord
OpDeleteRecord
OpBulkCreateRecords
OpBulkDeleteRecords
OpGetZoneStatus
OpValidateZone
OpPushCert
OpUpdateTLSA
OpGetCert
// IPNS operations
OpListIPNSKeys
OpGetIPNSKey
OpCreateIPNSKey
OpDeleteIPNSKey
OpPublishIPNS
OpRepublishIPNS
OpResolveIPNS
// Websites operations
OpListWebsites
OpGetWebsite
OpCreateWebsite
OpUpdateWebsite
OpDeleteWebsite
OpValidateWebsite
OpGetSSLStatus
OpUpdateSSLStatusInternal
OpGetGatewayWebsite
OpGetGatewayWebsiteStatus
OpGetWebsiteConfig
OpReconcileWebsiteChanges
// Website domain binding operations
OpListWebsiteDomains
OpBindWebsiteDomain
OpUpdateWebsiteDomain
OpUnbindWebsiteDomain
OpVerifyWebsiteDomain
OpDNSRequirementsWebsiteDomain
OpRepublishDomainDANE
OpConvertDomainToOnChain
OpListPlatformDomains
OpCheckPlatformDomainAvailability
// Pinning operations
OpListPins
OpAddPin
OpGetPin
OpRemovePin
// Ping operations
OpPing
// DAG operations
OpResolveDAG
)
// operationString maps operation IDs to human-readable names.
var operationString = map[int]string{
// DNS operations
OpListZones: "list DNS zones",
OpCreateZone: "create DNS zone",
OpGetZone: "get DNS zone",
OpDeleteZone: "delete DNS zone",
OpListRecords: "list DNS records",
OpGetRecord: "get DNS record",
OpCreateRecord: "create DNS record",
OpUpdateRecord: "update DNS record",
OpDeleteRecord: "delete DNS record",
OpBulkCreateRecords: "bulk create DNS records",
OpBulkDeleteRecords: "bulk delete DNS records",
OpGetZoneStatus: "get DNS zone status",
OpValidateZone: "validate DNS zone",
OpPushCert: "push DNS certificate",
OpUpdateTLSA: "update DNS TLSA record",
OpGetCert: "get DNS certificate",
// IPNS operations
OpListIPNSKeys: "list IPNS keys",
OpGetIPNSKey: "get IPNS key",
OpCreateIPNSKey: "create IPNS key",
OpDeleteIPNSKey: "delete IPNS key",
OpPublishIPNS: "publish to IPNS",
OpRepublishIPNS: "republish to IPNS",
OpResolveIPNS: "resolve IPNS name",
// Websites operations
OpListWebsites: "list websites",
OpGetWebsite: "get website",
OpCreateWebsite: "create website",
OpUpdateWebsite: "update website",
OpDeleteWebsite: "delete website",
OpValidateWebsite: "validate website",
OpGetSSLStatus: "get SSL status",
OpUpdateSSLStatusInternal: "update SSL status internal",
OpGetGatewayWebsite: "get gateway website",
OpGetGatewayWebsiteStatus: "get gateway website status",
OpGetWebsiteConfig: "get website config",
OpReconcileWebsiteChanges: "reconcile website changes",
// Website domain binding operations
OpListWebsiteDomains: "list website domains",
OpBindWebsiteDomain: "bind website domain",
OpUpdateWebsiteDomain: "update website domain",
OpUnbindWebsiteDomain: "unbind website domain",
OpVerifyWebsiteDomain: "verify website domain",
OpDNSRequirementsWebsiteDomain: "get domain DNS requirements",
OpRepublishDomainDANE: "republish domain DANE records",
OpConvertDomainToOnChain: "convert domain to on-chain managed",
OpListPlatformDomains: "list platform domains",
OpCheckPlatformDomainAvailability: "check platform domain availability",
// Pinning operations
OpListPins: "list pins",
OpAddPin: "add pin",
OpGetPin: "get pin",
OpRemovePin: "remove pin",
// Ping operations
OpPing: "ping",
// DAG operations
OpResolveDAG: "resolve DAG",
}
// Named error types for error comparison.
var (
// ErrUnauthorized is returned when authentication fails.
ErrUnauthorized = errors.New("unauthorized")
// ErrNotFound is returned when a requested resource is not found.
ErrNotFound = errors.New("not found")
// ErrForbidden is returned when the caller is authenticated but not
// authorized for the requested resource (e.g. another domain's private key).
ErrForbidden = errors.New("forbidden")
// ErrGone is returned when a resource exists but is in a deleted or broken state.
ErrGone = errors.New("gone")
// ErrRateLimitExceeded is returned when a download rate limit is exceeded.
// This error is returned by download operations when the configured rate limiter
// denies a request due to too many concurrent operations or excessive bandwidth usage.
// Re-exported from internal/download package for error matching with errors.Is().
ErrRateLimitExceeded = backend.ErrRateLimitExceeded
)
// errorFactory is a helper for creating errors with optional wrapping.
type errorFactory struct {
wrapErr bool
sentinel error
message string
}
// Error creates the actual error.
func (ef errorFactory) Error() error {
if ef.wrapErr && ef.sentinel != nil {
return fmt.Errorf("%w: %s", ef.sentinel, ef.message)
}
return fmt.Errorf("%s", ef.message)
}
// authErr creates an error factory that wraps with ErrUnauthorized.
func authErr(msg string) errorFactory {
return errorFactory{wrapErr: true, sentinel: ErrUnauthorized, message: msg}
}
// notFoundErr creates an error factory that wraps with ErrNotFound.
func notFoundErr(msg string) errorFactory {
return errorFactory{wrapErr: true, sentinel: ErrNotFound, message: msg}
}
// forbiddenErr creates an error factory that wraps with ErrForbidden.
func forbiddenErr(msg string) errorFactory {
return errorFactory{wrapErr: true, sentinel: ErrForbidden, message: msg}
}
// goneErr creates an error factory that wraps with ErrGone.
func goneErr(msg string) errorFactory {
return errorFactory{wrapErr: true, sentinel: ErrGone, message: msg}
}
// plainErr creates an error factory without wrapping.
func plainErr(msg string) errorFactory {
return errorFactory{wrapErr: false, message: msg}
}
const defaultOperationName = "operation"
// opsString returns the operation name for the given operation ID.
func opsString(op int) string {
if opName, ok := operationString[op]; ok {
return opName
}
return defaultOperationName
}
// ErrBadRequest creates a bad request error with the given message.
func ErrBadRequest(msg string) error {
return fmt.Errorf("%s", msg)
}
// Backend error reason codes returned by the API in ErrorDetail.Reason.
// These distinguish otherwise-identical HTTP error responses so callers can
// handle each failure mode explicitly.
const (
// ErrorCodeCIDNotPinned is returned when a request targets a CID that is
// not pinned on the gateway.
ErrorCodeCIDNotPinned = "CID_NOT_PINNED"
// ErrorCodeIPNSKeyNotFound is returned when a request targets an IPNS key
// that does not exist.
ErrorCodeIPNSKeyNotFound = "IPNS_KEY_NOT_FOUND"
// ErrorCodeDNSValidationFailed is returned when domain DNS validation fails
// (e.g. verification TXT record not published or domain does not resolve).
ErrorCodeDNSValidationFailed = "DNS_VALIDATION_FAILED"
)
// APIError carries the machine-readable reason code and human-readable details
// returned by the backend alongside the underlying error. It preserves the
// underlying error chain so errors.Is/errors.As still match sentinels like
// ErrNotFound.
type APIError struct {
// Reason is the backend machine-readable error code (e.g. CID_NOT_PINNED).
Reason string
// Details is the optional human-readable detail message from the backend.
Details string
// Err is the wrapped underlying error.
Err error
}
// Error implements the error interface.
func (e *APIError) Error() string {
if e.Err == nil {
return fmt.Sprintf("api error (reason: %s)", e.Reason)
}
if e.Reason != "" {
return fmt.Sprintf("%s (reason: %s)", e.Err, e.Reason)
}
return e.Err.Error()
}
// Unwrap returns the wrapped underlying error for errors.Is/As support.
func (e *APIError) Unwrap() error {
return e.Err
}
// ErrorReasonOf extracts the backend reason code from err, or returns "" if the
// error does not carry one.
func ErrorReasonOf(err error) string {
var apiErr *APIError
if errors.As(err, &apiErr) {
return apiErr.Reason
}
return ""
}
// withReason wraps err with the backend ErrorResponse parsed from body, if the
// body contains a non-empty machine-readable reason code. If err is nil or no
// code is present, err is returned unchanged.
func withReason(err error, body []byte) error {
if err == nil || len(body) == 0 {
return err
}
var resp client.ErrorResponse
if e := json.Unmarshal(body, &resp); e != nil || resp.Error.Reason == "" {
return err
}
apiErr := &APIError{
Reason: resp.Error.Reason,
Err: err,
}
if resp.Error.Details != nil {
apiErr.Details = *resp.Error.Details
}
return apiErr
}
// httpErrorMessages maps operation IDs to their custom status code error messages.
// This provides a centralized, DRY way to handle HTTP error responses.
var httpErrorMessages = map[int]map[int]errorFactory{
// DNS operations - all use similar patterns
OpListZones: {
http.StatusUnauthorized: authErr("authentication required"),
},
OpCreateZone: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid zone data"),
http.StatusConflict: plainErr("zone already exists"),
},
OpGetZone: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpDeleteZone: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpListRecords: {
http.StatusUnauthorized: authErr("authentication required"),
},
OpGetRecord: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("record not found"),
},
OpCreateRecord: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid record data"),
},
OpUpdateRecord: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid record data"),
http.StatusNotFound: notFoundErr("record not found"),
},
OpDeleteRecord: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("record not found"),
},
OpBulkCreateRecords: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid records data"),
},
OpBulkDeleteRecords: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid record identifiers"),
},
OpGetZoneStatus: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpValidateZone: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpPushCert: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid certificate data"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpUpdateTLSA: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid TLSA data"),
http.StatusNotFound: notFoundErr("zone not found"),
},
OpGetCert: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusForbidden: forbiddenErr("not authorized for this domain"),
http.StatusNotFound: notFoundErr("certificate not found"),
},
// IPNS operations
OpListIPNSKeys: {
http.StatusUnauthorized: authErr("authentication required"),
},
OpGetIPNSKey: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("IPNS key not found"),
},
OpCreateIPNSKey: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid key data"),
},
OpDeleteIPNSKey: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("IPNS key not found"),
},
OpPublishIPNS: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid publish data"),
},
OpRepublishIPNS: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("no keys to republish"),
},
OpResolveIPNS: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("IPNS name not found"),
},
// Websites operations
OpListWebsites: {
http.StatusUnauthorized: authErr("authentication required"),
},
OpGetWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
http.StatusGone: goneErr("website is broken"),
},
OpCreateWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid website data"),
http.StatusConflict: plainErr("website already exists"),
},
OpUpdateWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid website data"),
http.StatusNotFound: notFoundErr("website not found"),
},
OpDeleteWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
},
OpValidateWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
http.StatusBadRequest: plainErr("validation failed"),
},
OpGetSSLStatus: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
},
OpUpdateSSLStatusInternal: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid SSL status data"),
http.StatusNotFound: notFoundErr("website not found"),
},
OpGetWebsiteConfig: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website config not found"),
},
OpReconcileWebsiteChanges: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusForbidden: plainErr("gateway authentication failed"),
http.StatusBadRequest: plainErr("invalid after cursor"),
http.StatusNotFound: notFoundErr("website changes not found"),
},
// Website domain binding operations
OpListWebsiteDomains: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
},
OpBindWebsiteDomain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid domain data"),
http.StatusNotFound: notFoundErr("website not found"),
http.StatusConflict: plainErr("domain already bound"),
},
OpUpdateWebsiteDomain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid request"),
http.StatusNotFound: notFoundErr("domain or website not found"),
http.StatusUnprocessableEntity: plainErr("validation failed"),
},
OpUnbindWebsiteDomain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("domain or website not found"),
},
OpVerifyWebsiteDomain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("domain or website not found"),
http.StatusBadRequest: plainErr("verification failed"),
},
OpDNSRequirementsWebsiteDomain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("domain or website not found"),
},
OpRepublishDomainDANE: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("domain or website not found"),
http.StatusBadRequest: plainErr("invalid request"),
http.StatusConflict: plainErr("no DANE records to republish (no stored certificate or managed zone)"),
},
OpConvertDomainToOnChain: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("domain or website not found"),
http.StatusUnprocessableEntity: plainErr("domain is not eligible for on-chain conversion (already on-chain, not yet on-chain, or shared zone)"),
},
OpCheckPlatformDomainAvailability: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusBadRequest: plainErr("invalid label"),
},
OpListPlatformDomains: {
http.StatusUnauthorized: authErr("authentication required"),
},
OpGetGatewayWebsite: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
http.StatusGone: goneErr("website is broken or deleted"),
},
OpGetGatewayWebsiteStatus: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("website not found"),
http.StatusGone: goneErr("website is broken or deleted"),
},
// Ping operations
OpPing: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusForbidden: plainErr("gateway secret required"),
},
// DAG operations
OpResolveDAG: {
http.StatusUnauthorized: authErr("authentication required"),
http.StatusNotFound: notFoundErr("CID not found"),
},
}
// handleResponse processes an HTTP response using the global error message map.
//
// op: the operation ID (used to lookup custom error messages)
// statusCode: the HTTP status code from the response
// body: the response body
// successCodes: status codes that indicate success (e.g., []int{http.StatusOK})
//
// Returns nil for success codes, unrecoverable error for client errors (to stop retries),
// or retryable error for server errors.
func handleResponse(statusCode int, body []byte, op int, successCodes []int) error {
// Check if the status code indicates success
for _, code := range successCodes {
if statusCode == code {
return nil
}
}
// Check for custom error message in global map
var err error
if errorMessages, ok := httpErrorMessages[op]; ok {
if factory, ok := errorMessages[statusCode]; ok {
err = factory.Error()
}
}
if err == nil {
// Get operation name for generic error
opName := operationString[op]
if opName == "" {
opName = defaultOperationName
}
// Generic error with body
err = fmt.Errorf("%s failed with status %d: %s", opName, statusCode, string(body))
}
// Attach the backend machine-readable reason code (if present) so callers
// can distinguish otherwise-identical HTTP error responses (e.g.
// CID_NOT_PINNED vs IPNS_KEY_NOT_FOUND vs DNS_VALIDATION_FAILED).
err = withReason(err, body)
// Mark client errors as unrecoverable to prevent retries
if httputil.IsUnrecoverable(statusCode) {
return retry.Unrecoverable(err)
}
return err
}