Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9051 fix(uploads): classify cancelled upload requests as 499 (#10376)

Frezc0a105c9be858
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index e5eac8ccf3..ab753a4833 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -19,6 +19,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/imagemetadata"
+ "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/storage"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -579,6 +580,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
}
link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)
if err != nil {
+ if writeUploadCancellation(w, r, err) {
+ return
+ }
slog.Error("file upload failed", "error", err)
writeError(w, http.StatusInternalServerError, "upload failed")
return
@@ -606,6 +610,11 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
})
}
if err != nil {
+ if writeUploadCancellation(w, r, err) {
+ // The record write may have committed. Deleting uploaded bytes
+ // could leave a committed attachment pointing at a missing object.
+ return
+ }
slog.Error("failed to create attachment record", "error", err)
// S3 upload succeeded but DB record failed — still return the link
// so the file is usable. Log the error for investigation.
@@ -644,6 +653,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
// No workspace context (e.g. avatar upload) — upload directly.
link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)
if err != nil {
+ if writeUploadCancellation(w, r, err) {
+ return
+ }
slog.Error("file upload failed", "error", err)
writeError(w, http.StatusInternalServerError, "upload failed")
return
@@ -1616,3 +1628,11 @@ func (h *Handler) deleteS3Objects(ctx context.Context, urls []string) {
}
h.Storage.DeleteKeys(ctx, keys)
}
+
+func writeUploadCancellation(w http.ResponseWriter, r *http.Request, err error) bool {
+ if !errors.Is(r.Context().Err(), context.Canceled) || !errors.Is(err, context.Canceled) {
+ return false
+ }
+ w.WriteHeader(middleware.StatusClientClosedRequest)
+ return true
+}
diff --git a/server/internal/handler/file_upload_cancellation_test.go b/server/internal/handler/file_upload_cancellation_test.go
new file mode 100644
index 0000000000..893f2a7daa
--- /dev/null
+++ b/server/internal/handler/file_upload_cancellation_test.go
@@ -0,0 +1,154 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+type cancellationUploadStorage struct {
+ mockStorage
+ fail func() error
+}
+
+func (s *cancellationUploadStorage) Upload(context.Context, string, []byte, string, string) (string, error) {
+ return "", s.fail()
+}
+
+func uploadCancellationRequest(t *testing.T, ctx context.Context, filename string) *http.Request {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := part.Write([]byte("upload body")); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/upload-file", &body)
+ r.Header.Set("Content-Type", writer.FormDataContentType())
+ r.Header.Set("X-User-ID", testUserID)
+ r.Header.Set("X-Workspace-ID", testWorkspaceID)
+ return r
+}
+
+func TestUploadFileStorageCancellation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ direct bool
+ cancel bool
+ err error
+ status int
+ }{
+ {"workspace cancellation", false, true, context.Canceled, 499},
+ {"direct cancellation", true, true, context.Canceled, 499},
+ {"operation cancellation with live request", false, false, context.Canceled, http.StatusInternalServerError},
+ {"storage timeout", false, false, context.DeadlineExceeded, http.StatusInternalServerError},
+ {"unrelated failure after cancellation", false, true, errors.New("storage unavailable"), http.StatusInternalServerError},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ h := *testHandler
+ h.Storage = &cancellationUploadStorage{fail: func() error {
+ if tc.cancel {
+ cancel()
+ }
+ return fmt.Errorf("upload: %w", tc.err)
+ }}
+ filename := uuid.NewString() + ".txt"
+ r := uploadCancellationRequest(t, ctx, filename)
+ if tc.direct {
+ r.Header.Del("X-Workspace-ID")
+ }
+ response := testutil.Call(t, h.UploadFile, r).Want(tc.status)
+ if tc.status == 499 && response.Body.Len() != 0 {
+ t.Fatal("cancelled upload returned a response body")
+ }
+ if dbfx.Count(t, "SELECT count(*) FROM attachment WHERE workspace_id=$1 AND filename=$2", testWorkspaceID, filename) != 0 {
+ t.Fatal("failed upload created an attachment")
+ }
+ })
+ }
+}
+
+type uploadRecordErrorStarter struct {
+ txStarter
+ fail func() error
+}
+
+type uploadRecordErrorTx struct {
+ pgx.Tx
+ fail func() error
+}
+
+type uploadRecordErrorRow struct{ err error }
+
+func (s uploadRecordErrorStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.txStarter.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return uploadRecordErrorTx{tx, s.fail}, nil
+}
+
+func (tx uploadRecordErrorTx) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {
+ if strings.Contains(query, "-- name: CreateAttachment ") {
+ return uploadRecordErrorRow{tx.fail()}
+ }
+ return tx.Tx.QueryRow(ctx, query, args...)
+}
+
+func (r uploadRecordErrorRow) Scan(...any) error { return r.err }
+
+func TestUploadFileRecordCancellation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cancel bool
+ err error
+ status int
+ }{
+ {"request cancelled during record write", true, context.Canceled, 499},
+ {"operation cancellation with live request", false, context.Canceled, http.StatusOK},
+ {"unrelated failure after cancellation", true, errors.New("record unavailable"), http.StatusOK},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ h := *testHandler
+ store := &mockStorage{}
+ h.Storage = store
+ h.TxStarter = uploadRecordErrorStarter{h.TxStarter, func() error {
+ if tc.cancel {
+ cancel()
+ }
+ return tc.err
+ }}
+ filename := uuid.NewString() + ".txt"
+ response := testutil.Call(t, h.UploadFile, uploadCancellationRequest(t, ctx, filename)).Want(tc.status)
+ if tc.status == 499 && response.Body.Len() != 0 {
+ t.Fatal("cancelled record write returned a response body")
+ }
+ if len(store.files) != 1 {
+ t.Fatal("uncertain record write deleted uploaded bytes")
+ }
+ if dbfx.Count(t, "SELECT count(*) FROM attachment WHERE workspace_id=$1 AND filename=$2", testWorkspaceID, filename) != 0 {
+ t.Fatal("injected record failure committed an attachment")
+ }
+ })
+ }
+}