Skip to content

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

Go

fix(cli): classify attachment download body network errors (#10010)

沙雕的小鱼儿 boyfeiyu61e7e8f966f5
diff --git a/server/cmd/multica/cmd_attachment_test.go b/server/cmd/multica/cmd_attachment_test.go
index bd779e3998..2c949ff746 100644
--- a/server/cmd/multica/cmd_attachment_test.go
+++ b/server/cmd/multica/cmd_attachment_test.go
@@ -2,6 +2,8 @@ package main
import (
"encoding/json"
+ "errors"
+ "io"
"net/http"
"net/http/httptest"
"os"
@@ -9,9 +11,50 @@ import (
"strings"
"testing"
+ "github.com/multica-ai/multica/server/internal/cli"
"github.com/spf13/cobra"
)
+func TestRunAttachmentDownloadInterruptedBodyPreservesTarget(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/attachments/att-interrupted":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "filename": "report.txt", "download_url": "/download",
+ })
+ case "/download":
+ w.Header().Set("Content-Length", "71")
+ _, _ = io.WriteString(w, "payload")
+ default:
+ t.Errorf("unexpected request: %s", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+ outputDir := t.TempDir()
+ dest := filepath.Join(outputDir, "report.txt")
+ if err := os.WriteFile(dest, []byte("original"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cmd := newAttachmentDownloadTestCmd()
+ _ = cmd.Flags().Set("output-dir", outputDir)
+ out, err := captureStdout(t, func() error {
+ return runAttachmentDownload(cmd, []string{"att-interrupted"})
+ })
+ if !errors.Is(err, io.ErrUnexpectedEOF) || cli.ExitCodeFor(err) != cli.ExitNetwork {
+ t.Fatalf("expected network error preserving unexpected EOF, got %v (exit %d)", err, cli.ExitCodeFor(err))
+ }
+ if !strings.HasPrefix(err.Error(), "download file: ") || out != "" {
+ t.Errorf("error context or failure output changed: err=%v stdout=%q", err, out)
+ }
+ data, readErr := os.ReadFile(dest)
+ if readErr != nil || string(data) != "original" {
+ t.Fatalf("target changed after interrupted download: data=%q err=%v", data, readErr)
+ }
+}
+
func newAttachmentDownloadTestCmd() *cobra.Command {
cmd := &cobra.Command{Use: "download"}
cmd.Flags().StringP("output-dir", "o", ".", "")
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index 84fd220449..aa5030dc6b 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -814,7 +814,8 @@ func (c *APIClient) DownloadFile(ctx context.Context, downloadURL string) ([]byt
}
const maxDownloadSize = 100 << 20 // 100 MB
- return io.ReadAll(io.LimitReader(resp.Body, maxDownloadSize))
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadSize))
+ return data, wrapBodyRead(req, err)
}
// HealthCheck hits the /health endpoint and returns the response body.
diff --git a/server/internal/cli/errors_integration_test.go b/server/internal/cli/errors_integration_test.go
index 7f8968d8b6..eeaf58c1f2 100644
--- a/server/internal/cli/errors_integration_test.go
+++ b/server/internal/cli/errors_integration_test.go
@@ -11,9 +11,100 @@ import (
"strings"
"sync/atomic"
"testing"
+ "testing/iotest"
"time"
)
+func TestDownloadFileInterruptedBodyIsClassified(t *testing.T) {
+ withLang(t, "en_US.UTF-8")
+ var requests atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ w.Header().Set("Content-Length", "71")
+ _, _ = io.WriteString(w, "payload")
+ }))
+ defer srv.Close()
+
+ client := NewAPIClient(srv.URL, "ws-1", "test-token")
+ data, err := client.DownloadFile(context.Background(), "/download")
+ if string(data) != "payload" || !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("lost partial body or underlying error: data=%q err=%v", data, err)
+ }
+ var netErr *NetworkError
+ if !errors.As(err, &netErr) || netErr.Op != "GET /download" {
+ t.Fatalf("expected download NetworkError, got %T: %v", err, err)
+ }
+ if got := ExitCodeFor(err); got != ExitNetwork {
+ t.Errorf("ExitCodeFor = %d, want %d", got, ExitNetwork)
+ }
+ if msg := FormatError(err, false); !strings.Contains(msg, "network connection") {
+ t.Errorf("FormatError = %q, want network guidance", msg)
+ }
+ if requests.Load() != 1 {
+ t.Errorf("download sent %d requests, want one", requests.Load())
+ }
+}
+
+type downloadRoundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f downloadRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
+func TestDownloadFileBodyReadErrors(t *testing.T) {
+ readerErr := errors.New("synthetic reader failure")
+ for _, tc := range []struct {
+ name string
+ err error
+ wantExit int
+ }{
+ {"canceled", context.Canceled, ExitNetwork},
+ {"deadline exceeded", context.DeadlineExceeded, ExitNetwork},
+ {"non-network reader error", readerErr, ExitGeneric},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ client := NewAPIClient("https://example.test", "", "")
+ client.HTTPClient.Transport = downloadRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: io.NopCloser(iotest.ErrReader(tc.err)),
+ Request: req,
+ }, nil
+ })
+ _, err := client.DownloadFile(context.Background(), "/download")
+ if !errors.Is(err, tc.err) || ExitCodeFor(err) != tc.wantExit {
+ t.Fatalf("DownloadFile = %v (exit %d), want underlying %v (exit %d)", err, ExitCodeFor(err), tc.err, tc.wantExit)
+ }
+ var netErr *NetworkError
+ if got, want := errors.As(err, &netErr), tc.wantExit == ExitNetwork; got != want {
+ t.Errorf("NetworkError = %t, want %t", got, want)
+ }
+ if tc.err == readerErr && err != readerErr {
+ t.Errorf("non-network error changed: %v", err)
+ }
+ })
+ }
+}
+
+func TestDownloadFileBodyTimeoutIsClassified(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.WriteString(w, "payload")
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ }))
+ defer srv.Close()
+ client := NewAPIClient(srv.URL, "", "")
+ client.HTTPClient = &http.Client{Timeout: 200 * time.Millisecond}
+ data, err := client.DownloadFile(context.Background(), "/download")
+ if string(data) != "payload" || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("expected timeout after reading partial body: data=%q err=%v", data, err)
+ }
+ if got := ExitCodeFor(err); got != ExitNetwork {
+ t.Errorf("ExitCodeFor = %d, want %d; err=%v", got, ExitNetwork, err)
+ }
+}
+
func TestUploadResponseErrorsAreClassified(t *testing.T) {
withLang(t, "en_US.UTF-8")
helpers := []struct {