Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type HintedError interface {
type APIError struct {
StatusCode int
Message string
Code string
Hint string
RetryAfter time.Duration
}
Expand Down Expand Up @@ -68,23 +69,28 @@ func (e *APIError) Is(target error) bool {

func parseAPIError(statusCode int, body []byte) error {
var resp struct {
Success bool `json:"success"`
Message string `json:"message"`
Error string `json:"error"`
Success bool `json:"success"`
Message string `json:"message"`
Error string `json:"error"`
Code json.RawMessage `json:"error_code"`
}
code := ""
if err := json.Unmarshal(body, &resp); err == nil {
if len(resp.Code) > 0 {
_ = json.Unmarshal(resp.Code, &code)
}
message := resp.Message
if message == "" {
message = resp.Error
}
if message != "" {
msg, hint := rewriteError(statusCode, message)
return &APIError{StatusCode: statusCode, Message: msg, Hint: hint}
return &APIError{StatusCode: statusCode, Message: msg, Code: code, Hint: hint}
}
}

msg, hint := rewriteError(statusCode, "")
return &APIError{StatusCode: statusCode, Message: msg, Hint: hint}
return &APIError{StatusCode: statusCode, Message: msg, Code: code, Hint: hint}
}

func rewriteError(statusCode int, msg string) (message, hint string) {
Expand Down
97 changes: 97 additions & 0 deletions internal/api/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,100 @@ func TestAPIError_GetHint_Nil(t *testing.T) {
t.Errorf("expected empty hint from nil receiver")
}
}

func TestParseAPIError_StructuredErrorCode(t *testing.T) {
tests := []struct {
name string
status int
body string
wantMessage string
wantCode string
}{
{
name: "NoSuchUpload structured response",
status: 400,
body: `{"status":400,"error":"The specified upload does not exist.","error_code":"multipart_upload_not_found"}`,
wantMessage: "The specified upload does not exist.",
wantCode: "multipart_upload_not_found",
},
{
name: "legacy response without code",
status: 400,
body: `{"status":400,"error":"The specified upload does not exist."}`,
wantMessage: "The specified upload does not exist.",
wantCode: "",
},
{
name: "unrelated structured code",
status: 400,
body: `{"error":"invalid key","error_code":"unrelated_error"}`,
wantMessage: "invalid key",
wantCode: "unrelated_error",
},
{
name: "code without message",
status: 400,
body: `{"error_code":"multipart_upload_not_found"}`,
wantMessage: "API error (HTTP 400)",
wantCode: "multipart_upload_not_found",
},
{
name: "message takes precedence over error",
status: 400,
body: `{"message":"preferred","error":"fallback","error_code":"multipart_upload_not_found"}`,
wantMessage: "preferred",
wantCode: "multipart_upload_not_found",
},
{
name: "numeric code preserves legacy error",
status: 400,
body: `{"error":"invalid key","error_code":42}`,
wantMessage: "invalid key",
wantCode: "",
},
{
name: "object code preserves legacy error",
status: 400,
body: `{"error":"invalid key","error_code":{"unexpected":true}}`,
wantMessage: "invalid key",
wantCode: "",
},
{
name: "null code preserves legacy error",
status: 400,
body: `{"error":"invalid key","error_code":null}`,
wantMessage: "invalid key",
wantCode: "",
},
{
name: "malformed JSON cannot supply a code",
status: 400,
body: `{"error":"invalid key","error_code":"multipart_upload_not_found"`,
wantMessage: "API error (HTTP 400)",
wantCode: "",
},
{
name: "code parsing does not change HTTP status",
status: 500,
body: `{"error":"S3 unavailable","error_code":"multipart_upload_not_found"}`,
wantMessage: "S3 unavailable",
wantCode: "multipart_upload_not_found",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
apiErr := mustAPIError(t, parseAPIError(tt.status, []byte(tt.body)))

if apiErr.StatusCode != tt.status {
t.Errorf("StatusCode = %d, want %d", apiErr.StatusCode, tt.status)
}
if apiErr.Message != tt.wantMessage {
t.Errorf("Message = %q, want %q", apiErr.Message, tt.wantMessage)
}
if apiErr.Code != tt.wantCode {
t.Errorf("Code = %q, want %q", apiErr.Code, tt.wantCode)
}
})
}
}
19 changes: 15 additions & 4 deletions internal/cmd/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -367,6 +368,11 @@ func mergeCleanupRecovery(recovery *commandRecoveryInfo, cleanup *upload.Cleanup
return recovery
}

func missingMultipartUpload(state *upload.UnknownStateError) bool {
var apiErr *api.APIError
return errors.As(state.Cause, &apiErr) && apiErr.StatusCode == http.StatusBadRequest && apiErr.Code == "multipart_upload_not_found"
}

func uploadIncompleteDetail(err error, state *upload.UnknownStateError) commandErrorDetail {
recovery := &commandRecoveryInfo{
FileURL: state.FileURL,
Expand All @@ -382,10 +388,11 @@ func uploadIncompleteDetail(err error, state *upload.UnknownStateError) commandE
// The recovery's file_url is a non-authoritative hint from the presign
// response: the upload package documents the authoritative URL as the
// one returned by /files/complete, so a matching file_url is not
// proof of commit. Speak in terms of the actions the caller has: use
// `files complete` to replay finalize (safe — the same parts remain),
// or `files abort` to reclaim storage if they decide to give up.
// proof of commit.
hint := "Do not retry blindly — a retry may create a duplicate. Finalize with `gumroad files complete --recovery <manifest>` to commit without re-uploading, or reclaim storage with `gumroad files abort --upload-id <id> --key <key>`."
if missingMultipartUpload(state) {
hint = "The upload ID is no longer available. The earlier completion may have succeeded. Keep the recovery manifest and verify the original upload's outcome before taking further action."
}
return commandErrorDetail{
Type: "upload_error",
Code: "complete_state_unknown",
Expand Down Expand Up @@ -478,7 +485,11 @@ func printUploadRecovery(w io.Writer, style output.Styler, err error) {
}
parts := resolveRecoveryParts(state, rejected, hasState, hasRejected)
if n := len(parts); n > 0 {
fmt.Fprintln(w, style.Dim(fmt.Sprintf(" completed_parts: %d uploaded (re-finalize with `gumroad files complete --recovery <manifest>` to avoid re-uploading):", n)))
description := "uploaded (re-finalize with `gumroad files complete --recovery <manifest>` to avoid re-uploading)"
if hasState && missingMultipartUpload(state) {
description = "recorded"
}
fmt.Fprintln(w, style.Dim(fmt.Sprintf(" completed_parts: %d %s:", n, description)))
for _, p := range parts {
fmt.Fprintln(w, style.Dim(fmt.Sprintf(" part_number=%d etag=%s", p.PartNumber, p.ETag)))
}
Expand Down
8 changes: 5 additions & 3 deletions internal/cmd/files/complete.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,9 @@ func runComplete(opts cmdutil.Options, manifest completeManifest, body map[strin

// handleCompleteFailure wraps a /files/complete failure with the recovery
// manifest so the caller retains actionable state:
// - Ambiguous (5xx, 408, 409, 429, transport, parse): *upload.UnknownStateError
// — a retry with the same manifest can still succeed.
// - Ambiguous (5xx, 408, 409, 429, transport, parse, or HTTP 400 with
// error_code=multipart_upload_not_found): *upload.UnknownStateError.
// The manifest remains available for reconciliation.
// - Definitive (other 4xx, or HTTP-200-with-success-false): *CompleteRejectedError
// — preserves upload_id/key so the caller can run `gumroad files abort`
// after verifying that abort is actually the right next step. Unlike
Expand All @@ -256,7 +257,8 @@ func handleCompleteFailure(err error, manifest completeManifest) error {
parts[i] = upload.CompletedPart{PartNumber: p.PartNumber, ETag: p.ETag}
}
var apiErr *api.APIError
if errors.As(err, &apiErr) && isDefinitiveCompleteRejection(apiErr.StatusCode) {
if errors.As(err, &apiErr) && isDefinitiveCompleteRejection(apiErr.StatusCode) &&
(apiErr.StatusCode != http.StatusBadRequest || apiErr.Code != "multipart_upload_not_found") {
return &CompleteRejectedError{
FileURL: manifest.FileURL,
UploadID: manifest.UploadID,
Expand Down
170 changes: 170 additions & 0 deletions internal/cmd/files/complete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strings"
"testing"

"github.com/antiwork/gumroad-cli/internal/api"
"github.com/antiwork/gumroad-cli/internal/testutil"
"github.com/antiwork/gumroad-cli/internal/upload"
)
Expand Down Expand Up @@ -295,6 +296,175 @@ func TestComplete_AmbiguousReplayFailure_PreservesManifest(t *testing.T) {
}
}

func TestComplete_StructuredNoSuchUploadClassification(t *testing.T) {
tests := []struct {
name string
status int
body string
wantUnknown bool
wantCode string
}{
{
name: "exact structured HTTP 400",
status: http.StatusBadRequest,
body: `{"status":400,"error":"The specified upload does not exist.","error_code":"multipart_upload_not_found"}`,
wantUnknown: true,
wantCode: "multipart_upload_not_found",
},
{
name: "legacy HTTP 400 without code",
status: http.StatusBadRequest,
body: `{"status":400,"error":"The specified upload does not exist."}`,
},
{
name: "different code on HTTP 400",
status: http.StatusBadRequest,
body: `{"error":"invalid key","error_code":"invalid_key"}`,
wantCode: "invalid_key",
},
{
name: "case-sensitive error code",
status: http.StatusBadRequest,
body: `{"error":"invalid key","error_code":"Multipart_Upload_Not_Found"}`,
wantCode: "Multipart_Upload_Not_Found",
},
{
name: "non-string code on HTTP 400",
status: http.StatusBadRequest,
body: `{"error":"invalid key","error_code":42}`,
},
{
name: "matching code on HTTP 403 is definitive",
status: http.StatusForbidden,
body: `{"error":"forbidden","error_code":"multipart_upload_not_found"}`,
wantCode: "multipart_upload_not_found",
},
{
name: "HTTP 500 remains ambiguous",
status: http.StatusInternalServerError,
body: `{"error":"server error","error_code":"multipart_upload_not_found"}`,
wantUnknown: true,
wantCode: "multipart_upload_not_found",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
completeCalls := 0
abortCalls := 0

testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/files/complete":
completeCalls++
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tt.status)
if _, err := fmt.Fprint(w, tt.body); err != nil {
t.Errorf("write response: %v", err)
}
case "/files/abort":
abortCalls++
t.Error("recovery command must never automatically abort")
default:
t.Errorf("unexpected request path: %s", r.URL.Path)
}
})

manifest := map[string]any{
"file_url": "https://example.com/maybe-committed",
"upload_id": "up-structured",
"key": "attachments/u/k/original/p.bin",
"completed_parts": []map[string]any{
{"part_number": 1, "etag": "etag-one"},
{"part_number": 2, "etag": "etag-two"},
},
}

path := writeRecovery(t, manifest)
cmd := testutil.Command(newCompleteCmd(), testutil.Yes(true))
cmd.SetArgs([]string{"--recovery", path})

err := cmd.Execute()
if err == nil {
t.Fatal("expected completion error")
}
if completeCalls != 1 {
t.Fatalf("complete calls = %d, want 1", completeCalls)
}
if abortCalls != 0 {
t.Fatalf("abort calls = %d, want 0", abortCalls)
}

var apiErr *api.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("underlying APIError not preserved: %T: %v", err, err)
}
if apiErr.StatusCode != tt.status || apiErr.Code != tt.wantCode {
t.Errorf("APIError = %+v, want status=%d code=%q",
apiErr, tt.status, tt.wantCode)
}

if tt.wantUnknown {
var unknown *upload.UnknownStateError
if !errors.As(err, &unknown) {
t.Fatalf("expected UnknownStateError, got %T: %v", err, err)
}
if !errors.Is(err, upload.ErrCompleteStateUnknown) {
t.Fatal("missing ErrCompleteStateUnknown sentinel")
}
var rejected *CompleteRejectedError
if errors.As(err, &rejected) {
t.Fatal("ambiguous result incorrectly classified as rejected")
}
if unknown.FileURL != "https://example.com/maybe-committed" ||
unknown.UploadID != "up-structured" ||
unknown.Key != "attachments/u/k/original/p.bin" {
t.Errorf("unknown-state handles not preserved: %+v", unknown)
}
if len(unknown.CompletedParts) != 2 {
t.Fatalf("unknown-state parts = %+v", unknown.CompletedParts)
}
if unknown.CompletedParts[0].PartNumber != 1 ||
unknown.CompletedParts[0].ETag != "etag-one" ||
unknown.CompletedParts[1].PartNumber != 2 ||
unknown.CompletedParts[1].ETag != "etag-two" {
t.Errorf("unknown-state parts not preserved: %+v", unknown.CompletedParts)
}
if unknown.Cause == nil {
t.Fatal("unknown-state cause missing")
}
} else {
var rejected *CompleteRejectedError
if !errors.As(err, &rejected) {
t.Fatalf("expected CompleteRejectedError, got %T: %v", err, err)
}
var unknown *upload.UnknownStateError
if errors.As(err, &unknown) ||
errors.Is(err, upload.ErrCompleteStateUnknown) {
t.Fatal("definitive response classified as unknown")
}
if rejected.FileURL != "https://example.com/maybe-committed" ||
rejected.UploadID != "up-structured" ||
rejected.Key != "attachments/u/k/original/p.bin" {
t.Errorf("rejected-state handles not preserved: %+v", rejected)
}
if len(rejected.CompletedParts) != 2 {
t.Fatalf("rejected-state parts = %+v", rejected.CompletedParts)
}
if rejected.CompletedParts[0].PartNumber != 1 ||
rejected.CompletedParts[0].ETag != "etag-one" ||
rejected.CompletedParts[1].PartNumber != 2 ||
rejected.CompletedParts[1].ETag != "etag-two" {
t.Errorf("rejected-state parts not preserved: %+v", rejected.CompletedParts)
}
if rejected.Cause == nil {
t.Fatal("rejected-state cause missing")
}
}
})
}
}

func TestComplete_DefinitiveFailure_PreservesFullManifestForRetry(t *testing.T) {
// Real failure mode: stdin-piped recovery hits 4xx, user loses the
// only copy of the manifest unless CompleteRejectedError carries
Expand Down
Loading
Loading