Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(weixin): stop cutting off outbound file uploads at the API timeout (MUL-9866) (#11203)
Multica Eve1bf341d7512a
diff --git a/server/internal/integrations/weixin/media_test.go b/server/internal/integrations/weixin/media_test.goindex 9f03b0be6f..089329588a 100644--- a/server/internal/integrations/weixin/media_test.go+++ b/server/internal/integrations/weixin/media_test.go@@ -6,14 +6,18 @@ import ("encoding/base64""encoding/hex""encoding/json"+ "errors""io""net/http""net/http/httptest""strings"+ "sync/atomic""testing"+ "time""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ db "github.com/multica-ai/multica/server/pkg/db/generated")func TestInboundMediaWithoutStorageIsExplicitlyUnavailable(t *testing.T) {@@ -136,3 +140,100 @@ func TestMediaRejectsUntrustedURLsAndOversize(t *testing.T) {t.Fatal("untrusted media URL reached transport")}}++// Regression: the CDN upload rode on the API client, whose per-request timeout+// cut off every file slower than that to upload.+func TestMediaUploadOutlivesAPIRequestTimeout(t *testing.T) {+ const apiTimeout = 100 * time.Millisecond+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/ilink/bot/getuploadurl":+ _, _ = w.Write([]byte(`{"ret":0,"upload_full_url":"https://novac2c.cdn.weixin.qq.com/c2c/upload"}`))+ case "/c2c/upload":+ _, _ = io.Copy(io.Discard, r.Body)+ time.Sleep(3 * apiTimeout) // a slow cross-border transfer+ w.Header().Set("x-encrypted-param", "download")+ default:+ t.Errorf("unexpected path %s", r.URL.Path)+ }+ }))+ defer server.Close()+ client := providerClient(server)+ client.Timeout = apiTimeout+ item, err := newAPI(DefaultBaseURL, "token", client).Upload(context.Background(), "owner", []byte("png"), "image.png", "image/png")+ if err != nil || item.Image == nil || item.Image.Media.Query != "download" {+ t.Fatalf("slow CDN upload was cut off: %v", err)+ }+}++func TestMediaUploadUsesHTTP1ToTheCDN(t *testing.T) {+ if newAPI(DefaultBaseURL, "token", nil).cdnClient().Transport != cdnTransport {+ t.Fatal("default CDN uploads must use the HTTP/1.1 transport")+ }+ var proto atomic.Int32+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ proto.Store(int32(r.ProtoMajor))+ }))+ server.EnableHTTP2 = true+ server.StartTLS()+ defer server.Close()+ base := server.Client().Transport.(*http.Transport)+ base.ForceAttemptHTTP2 = true+ resp, err := (&http.Client{Transport: http1Transport(base)}).Post(server.URL, "application/octet-stream", strings.NewReader("x"))+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if proto.Load() != 1 {+ t.Fatalf("CDN upload negotiated HTTP/%d", proto.Load())+ }+ // Control: the same server does speak HTTP/2 to the unmodified transport.+ resp, err = (&http.Client{Transport: base}).Post(server.URL, "application/octet-stream", strings.NewReader("x"))+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if proto.Load() != 2 {+ t.Fatal("test server did not offer HTTP/2")+ }+}++func TestMediaTransferTimeoutScalesWithSize(t *testing.T) {+ if got := mediaTransferTimeout(0); got != mediaTransferBase {+ t.Fatalf("empty file budget %s", got)+ }+ // The failing replies carried ~2.3 MB images at ~20 KB/s.+ if got := mediaTransferTimeout(2363885); got < 2363885/(20<<10)*time.Second {+ t.Fatalf("2.3 MB budget %s is below the measured transfer time", got)+ }+ if got := mediaTransferTimeout(maxMediaBytes); got != mediaTransferMax {+ t.Fatalf("budget is not capped: %s", got)+ }+}++type deadlineStore struct {+ objectStore+ deadline time.Duration+}++func (s *deadlineStore) KeyFromURL(string) string { return "key" }++func (s *deadlineStore) GetReader(ctx context.Context, _ string) (io.ReadCloser, error) {+ if deadline, ok := ctx.Deadline(); ok {+ s.deadline = time.Until(deadline)+ }+ return nil, errors.New("unavailable")+}++// The CDN upload's size-scaled budget must not stretch a stalled storage read,+// which would hold the conversation's later replies behind it.+func TestAttachmentStorageReadKeepsFixedDeadline(t *testing.T) {+ store := &deadlineStore{}+ o := &Outbound{objects: store}+ if _, err := o.attachment(context.Background(), nil, "owner", db.Attachment{Url: "u", SizeBytes: 10 << 20}); err == nil {+ t.Fatal("expected storage read failure")+ }+ if store.deadline <= 0 || store.deadline > attachmentReadTimeout {+ t.Fatalf("storage read deadline %s, want at most %s", store.deadline, attachmentReadTimeout)+ }+}diff --git a/server/internal/integrations/weixin/media_upload.go b/server/internal/integrations/weixin/media_upload.goindex 3886749c30..5a95d9eb96 100644--- a/server/internal/integrations/weixin/media_upload.go+++ b/server/internal/integrations/weixin/media_upload.go@@ -9,6 +9,7 @@ import ("encoding/base64""encoding/hex""errors"+ "fmt""io""net/http""net/url"@@ -20,6 +21,48 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+// Uploads from our servers to the WeChat CDN were measured at ~20 KB/s, so a+// fixed deadline sized for API calls cut off every file above ~0.8 MB. The+// budget scales with the file, floored below that measured rate, and is capped+// so one file cannot hold a conversation's reply queue indefinitely.+const (+ mediaTransferBase = 45 * time.Second+ mediaTransferMinRate = 16 << 10 // bytes per second+ mediaTransferMax = 10 * time.Minute++ attachmentReadTimeout = 45 * time.Second+)++func mediaTransferTimeout(size int64) time.Duration {+ return min(mediaTransferBase+time.Duration(size)*time.Second/mediaTransferMinRate, mediaTransferMax)+}++// cdnTransport carries CDN uploads over HTTP/1.1, as the provider's reference+// client does. Over HTTP/2 the CDN grants a 64 KiB stream window, and uploads+// ran far below what the same network path achieves to the iLink API.+var cdnTransport http.RoundTripper = http1Transport(http.DefaultTransport.(*http.Transport))++func http1Transport(base *http.Transport) *http.Transport {+ tr := base.Clone()+ if tr.TLSClientConfig != nil {+ tr.TLSClientConfig.NextProtos = nil // else ALPN can still select h2+ }+ tr.Protocols = new(http.Protocols)+ tr.Protocols.SetHTTP1(true)+ return tr+}++// cdnClient is bounded by the caller's size-scaled deadline, not by the API+// client's per-request timeout.+func (c *apiClient) cdnClient() *http.Client {+ client := *c.http+ client.Timeout = 0+ if client.Transport == nil {+ client.Transport = cdnTransport+ }+ return &client+}+func encryptMedia(data, key []byte) ([]byte, error) {block, err := aes.NewCipher(key)if err != nil || len(key) != aes.BlockSize {@@ -41,7 +84,7 @@ func (c *apiClient) Upload(ctx context.Context, userID string, data []byte, fileif len(data) > maxMediaBytes {return messageItem{}, errors.New("weixin: file exceeds the 20 MiB transfer limit")}- ctx, cancel := context.WithTimeout(ctx, 45*time.Second)+ ctx, cancel := context.WithTimeout(ctx, mediaTransferTimeout(int64(len(data))))defer cancel()key := make([]byte, aes.BlockSize)fileKey := make([]byte, 16)@@ -90,8 +133,12 @@ func (c *apiClient) Upload(ctx context.Context, userID string, data []byte, filereturn messageItem{}, ErrProtocol}req.Header.Set("Content-Type", "application/octet-stream")- resp, err := c.http.Do(req) // no Authorization on the CDN request+ resp, err := c.cdnClient().Do(req) // no Authorization on the CDN requestif err != nil {+ if ctx.Err() != nil {+ return messageItem{}, fmt.Errorf("weixin: media upload of %d bytes: %w", len(encrypted), ctx.Err())+ }+ // The URL carries the provider's upload ticket; keep it out of logs.return messageItem{}, errors.New("weixin: media upload failed")}defer resp.Body.Close()@@ -139,20 +186,31 @@ func (o *Outbound) attachment(ctx context.Context, api *apiClient, userID stringif row.SizeBytes > maxMediaBytes {return messageItem{}, errors.New("weixin: file exceeds the 20 MiB transfer limit")}- ctx, cancel := context.WithTimeout(ctx, 45*time.Second)- defer cancel()key := o.objects.KeyFromURL(row.Url)if key == "" {return messageItem{}, errors.New("weixin: attachment is not in Multica object storage")}+ data, err := o.readAttachment(ctx, key)+ if err != nil {+ return messageItem{}, err+ }+ // Upload applies its own size-scaled deadline for the slow CDN leg.+ return api.Upload(ctx, userID, data, row.Filename, row.ContentType)+}++// readAttachment keeps the fixed object-storage deadline: a stalled read must+// not hold the conversation's reply queue for the CDN upload's longer budget.+func (o *Outbound) readAttachment(ctx context.Context, key string) ([]byte, error) {+ ctx, cancel := context.WithTimeout(ctx, attachmentReadTimeout)+ defer cancel()reader, err := o.objects.GetReader(ctx, key)if err != nil {- return messageItem{}, errors.New("weixin: cannot read attachment")+ return nil, errors.New("weixin: cannot read attachment")}defer reader.Close()data, err := io.ReadAll(io.LimitReader(reader, maxMediaBytes+1))if err != nil || len(data) > maxMediaBytes {- return messageItem{}, errors.New("weixin: attachment transfer failed or exceeds limit")+ return nil, errors.New("weixin: attachment transfer failed or exceeds limit")}- return api.Upload(ctx, userID, data, row.Filename, row.ContentType)+ return data, nil}diff --git a/server/internal/integrations/weixin/outbound.go b/server/internal/integrations/weixin/outbound.goindex 1442291eaf..6c98da4c06 100644--- a/server/internal/integrations/weixin/outbound.go+++ b/server/internal/integrations/weixin/outbound.go@@ -165,7 +165,9 @@ func (o *Outbound) sendSession(ctx context.Context, key string, session *outbounsession.queue[0] = outboundReply{}session.queue = session.queue[1:]o.mu.Unlock()- call, cancel := context.WithTimeout(ctx, 5*time.Minute)+ // Each provider call carries its own deadline; this outer bound must+ // leave room for several attachments at their size-scaled budgets.+ call, cancel := context.WithTimeout(ctx, 30*time.Minute)if err := o.deliverReply(call, reply); err != nil {o.logger.WarnContext(ctx, "weixin: reply delivery failed", "task_id", reply.event.TaskID, "error", err)}@@ -293,10 +295,12 @@ func (o *Outbound) deliverReply(ctx context.Context, reply outboundReply) errorif i < len(chunks) {msg = textMessage(creds.UserID, token, msg.ClientID, chunks[i])} else {- item, prepErr := o.attachment(ctx, api, creds.UserID, attachments[i-len(chunks)])+ row := attachments[i-len(chunks)]+ started := time.Now()+ item, prepErr := o.attachment(ctx, api, creds.UserID, row)if prepErr != nil {msg = textMessage(creds.UserID, token, msg.ClientID, "This file could not be sent to WeChat. It is still attached to the reply in Multica.")- o.logger.WarnContext(ctx, "weixin: attachment unavailable", "error", prepErr)+ o.logger.WarnContext(ctx, "weixin: attachment unavailable", "error", prepErr, "task_id", util.UUIDToString(taskID), "attachment_id", util.UUIDToString(row.ID), "content_type", row.ContentType, "size_bytes", row.SizeBytes, "elapsed", time.Since(started))} else {msg.Items = []messageItem{item}}