Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(wecom): tell the sender when the media budget gives up on an attachment, and count every failure (#9695)
Xichang(Seacen) Zhao908456c60192
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 8b9bd7896d..50fc02f4cd 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1069,6 +1069,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busstore,engine.NewDBMediaIntentLedger(queries),wecomSenders,+ queries,slog.Default(),)}diff --git a/server/cmd/server/wecom_media_wiring_test.go b/server/cmd/server/wecom_media_wiring_test.gonew file mode 100644index 0000000000..15d5795235--- /dev/null+++ b/server/cmd/server/wecom_media_wiring_test.go@@ -0,0 +1,69 @@+package main++import (+ "bytes"+ "crypto/rand"+ "encoding/base64"+ "log/slog"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The media resolver's queries are a constructor argument that may be nil, and+// a nil one has no symptom of its own: every attachment-failure notice simply+// comes out in the deployment's language, and is written even to an+// installation revoked since the message came in. Every unit test in the+// wecom package passes them by hand, so the package stays green with the+// production wiring absent.+//+// So this asserts it off the REAL boot path, NewRouter, by the warning+// NewMediaResolver logs when the queries are nil. The resolver is only built when+// a storage backend exists, so the test gives it one: local storage in a+// temporary directory, with S3 unset.+//+// Two routers, one without the WeCom key and one with it, as in+// wecom_replier_wiring_test.go: only the difference between them says the WeCom+// block ran.+func TestWecomMediaResolverGetsItsQueriesOnTheRealBootPath(t *testing.T) {+ key := make([]byte, secretbox.KeySize)+ if _, err := rand.Read(key); err != nil {+ t.Fatalf("generate a wecom secretbox key: %v", err)+ }+ t.Setenv("S3_BUCKET", "")+ t.Setenv("LOCAL_UPLOAD_DIR", t.TempDir())++ var logged bytes.Buffer+ restore := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug})))+ t.Cleanup(func() { slog.SetDefault(restore) })++ t.Setenv("MULTICA_WECOM_SECRET_KEY", "")+ withoutWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withoutWecom, analytics.NoopClient{}, nil)++ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))+ withWecom := events.New()+ NewRouter(nil, realtime.NewHub(), withWecom, analytics.NoopClient{}, nil)++ if got, base := withWecom.SubscriberCount(protocol.EventChatDone),+ withoutWecom.SubscriberCount(protocol.EventChatDone); got <= base {+ t.Fatalf("the WeCom boot block did not run: chat:done listeners %d with the key set vs %d without, "++ "so this test proves nothing. Re-point this guard at wherever WeCom is wired now", got, base)+ }+ if !strings.Contains(logged.String(), "local storage initialized") {+ t.Fatalf("no storage backend came up, so the media resolver was never built and this test proves nothing.\nlog:\n%s", logged.String())+ }++ if got := logged.String(); strings.Contains(got, "wecom media: no queries wired") {+ t.Errorf("the production media resolver was built without its queries, so every "++ "attachment-failure notice uses the deployment language whatever the reader's profile says, "++ "and is written even after the installation is revoked. "++ "Pass them to wecom.NewMediaResolver in router.go.\nlog:\n%s", got)+ }+}diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 44579aa4e8..cf4e349bb2 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -319,6 +319,56 @@ type MediaResolver interface {ResolveMedia(ctx context.Context, inst ResolvedInstallation, sender ResolvedIdentity, sessionID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage}+// MediaAbandonNotifier is an optional extra a MediaResolver may implement, for+// the one failure it cannot see for itself.+//+// ResolveMedia owns telling the sender about the attachments it tried and+// could not fetch. But the Router wraps the whole call in a media budget of+// its own, and when THAT expires the resolver either never ran or was cut off+// mid-way, and the Router then discards even the refs it did return. The+// resolver cannot see that last step, so neither the notice nor any count it+// keeps covers it. The user is left with the bot answering the line they typed+// beside the picture as if there were no picture, and nothing telling them to+// send it again.+//+// The Router calls this on that path, on a goroutine of its own and a context+// of its own with a deadline (mediaAbandonNoticeTimeout): database+// finalization does not wait for it, and the context that expired cannot carry+// a message out. Implementing it is optional, and a resolver that does not is+// left exactly as it was: the type assertion simply misses, which is what+// keeps the budget path unchanged for every channel that has not opted in.+type MediaAbandonNotifier interface {+ NotifyMediaAbandoned(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, a MediaAbandonment)+}++// MediaNoticeDrainer is an optional extra for a MediaResolver whose+// ResolveMedia sends its failure notice on a goroutine of its own, so that the+// Router's bind does not wait on a chat write. The Router's Drain calls it+// after every media job has finished, which is after every ResolveMedia has+// returned and so after every such notice has been started; it blocks until+// those notices are done. Each notice carries its own deadline, which is what+// bounds the wait.+type MediaNoticeDrainer interface {+ DrainMediaNotices()+}++// MediaAbandonment is what the Router knows about the attachments it gave up+// on, and the resolver does not.+type MediaAbandonment struct {+ // Cause is the media budget's own error: context.DeadlineExceeded when the+ // budget ran out, context.Canceled when the Router is draining for+ // shutdown.+ Cause error+ // Started is false when the budget was gone before ResolveMedia was+ // called, so the resolver saw none of this message's attachments. When it+ // is true, ResolveMedia ran and returned, and every attachment it failed on+ // is already its own to account for.+ Started bool+ // Dropped are the refs ResolveMedia returned that the Router is discarding+ // instead of binding: stored, but too late to reach the agent.+ Dropped []channel.MediaRef+}+// MediaIntentLedger persists upload intent BEFORE the object is written. The// row is the only artifact any failure path leaves behind: upload error,// resolve deadline, bind failure, ambiguous commit, or a crash all simplydiff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 71f2bcaab3..8e8fde98aa 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -155,21 +155,36 @@ func (r *Router) EnableRunBatching(window time.Duration) {}// Drain cancels detached media processing, flushes debounced run triggers, and-// joins media/reply goroutines until ctx ends. It returns whether everything-// completed. Call on shutdown AFTER the Supervisor has stopped delivering-// events; timed-out media retains its durable placeholder fallback.+// joins media/reply goroutines, and the failure notices media resolvers sent+// off on their own (MediaNoticeDrainer), until ctx ends. It returns whether+// everything completed. Call on shutdown AFTER the Supervisor has stopped+// delivering events; timed-out media retains its durable placeholder fallback.func (r *Router) Drain(ctx context.Context) bool {r.mediaQueueMu.Lock()r.stopping = truer.mediaCancel()r.mediaQueueMu.Unlock()+ r.mu.RLock()+ var noticeDrainers []MediaNoticeDrainer+ for _, set := range r.sets {+ if d, ok := set.Media.(MediaNoticeDrainer); ok {+ noticeDrainers = append(noticeDrainers, d)+ }+ }+ r.mu.RUnlock()+done := make(chan struct{})go func() {if r.batcher != nil {r.batcher.FlushAll()}r.mediaWg.Wait()+ // Only after mediaWg: every ResolveMedia has returned by then, so+ // every notice it sent off has been started and none can start later.+ for _, d := range noticeDrainers {+ d.DrainMediaNotices()+ }r.replyWg.Wait()close(done)}()@@ -817,11 +832,19 @@ func (r *Router) enqueueMediaJob(set ResolverSet, inst ResolvedInstallation, ideconst mediaFinalizeTimeout = 5 * time.Second+// mediaAbandonNoticeTimeout bounds a resolver's NotifyMediaAbandoned. It runs+// beside database finalization rather than inside mediaFinalizeTimeout, so it+// is sized for a chat write rather than for a query: a profile lookup, a wait+// for the chat's turn behind an answer already streaming, and one server+// acknowledgement.+const mediaAbandonNoticeTimeout = 15 * time.Second+func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, resolveRemote bool, deadline time.Time) {ctx, cancel := context.WithDeadline(r.mediaCtx, deadline)defer cancel()resolved := msg+ started := falseif !resolveRemote {resolved.MediaRefs = nil} else if ctx.Err() == nil {@@ -829,6 +852,7 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,// shutdown): resolving on a dead context would only churn through// intent writes that immediately fail.resolved = set.Media.ResolveMedia(ctx, inst, identity, sessionID, chatMessageID, msg)+ started = true}finalizeCtx, finalizeCancel := context.WithTimeout(context.Background(), mediaFinalizeTimeout)defer finalizeCancel()@@ -837,12 +861,23 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,// will not gain an attachment row. Nothing is deleted here — their// intent-ledger rows were written before the uploads, and the// reconciler reclaims unreferenced objects after the settle delay.+ dropped := resolved.MediaRefsresolved.MediaRefs = nilr.logger.Warn("channel router: media resolution incomplete; using placeholder","channel_type", string(msg.Source.ChannelType),"event_id", msg.EventID,"message_id", msg.MessageID,"error", err)+ // The log above is the only record of this, and the person who sent+ // the attachment cannot read it. The resolver was cut off or never+ // started, and cannot see the refs dropped just above, so the notice+ // it owns does not cover them either.+ //+ // A resolver that does not implement the interface is left untouched:+ // the assertion misses and nothing else on this path changes.+ if notifier, ok := set.Media.(MediaAbandonNotifier); ok {+ r.notifyMediaAbandoned(notifier, inst, msg, MediaAbandonment{Cause: err, Started: started, Dropped: dropped})+ }}bindRes, bindErr := set.Session.BindMedia(finalizeCtx, BindMediaParams{MessageID: chatMessageID,@@ -896,6 +931,32 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,}}+// notifyMediaAbandoned hands the abandonment to the resolver without making+// finalization wait for it. The notice is a chat write: it can wait on a+// profile lookup, on the chat's turn behind an answer already streaming, and+// on the server's acknowledgement, and none of that may spend the budget that+// binds the message, clears its pending-media marker and promotes its task.+//+// It starts before finalization rather than after, because nothing in the+// notice depends on how finalization goes. The refs are already dropped, so+// the message is bound with the placeholder either way and the agent reads+// "[Image]" with no file behind it: "the attachment did not arrive" is true+// whatever the bind returns. Starting first gives the notice its best chance+// of reaching the chat ahead of the agent's answer, which cannot begin until+// the promotion below.+//+// It is counted in mediaWg, so Drain waits for it like any other media work;+// its own deadline is what keeps that wait bounded.+func (r *Router) notifyMediaAbandoned(n MediaAbandonNotifier, inst ResolvedInstallation, msg channel.InboundMessage, a MediaAbandonment) {+ r.mediaWg.Add(1)+ go func() {+ defer r.mediaWg.Done()+ ctx, cancel := context.WithTimeout(context.Background(), mediaAbandonNoticeTimeout)+ defer cancel()+ n.NotifyMediaAbandoned(ctx, inst, msg, a)+ }()+}+func (r *Router) finishMediaQueue(key string, done chan struct{}) {r.mediaQueueMu.Lock()defer r.mediaQueueMu.Unlock()diff --git a/server/internal/integrations/channel/engine/router_media_abandon_test.go b/server/internal/integrations/channel/engine/router_media_abandon_test.gonew file mode 100644index 0000000000..484616f9e7--- /dev/null+++ b/server/internal/integrations/channel/engine/router_media_abandon_test.go@@ -0,0 +1,340 @@+package engine++// router_media_abandon_test.go — what a person is owed when the photo they+// sent runs out of budget before it is bound.+//+// The Router already handles the budget expiring: it drops the refs, logs a+// warning and lets the run proceed on the "[Image]" placeholder. From the+// resolver's side nothing failed — it was cut off, or it never started — so+// the notice a resolver owns for its own failures cannot fire. The photo is+// gone, the agent answers the line typed beside it as if there were no photo,+// and the only record is a server log the sender cannot read.+//+// The tests here drive the real Router through the real detached media path.+// One is the guard for the channels that have not opted in: the interface is+// optional, and a resolver that does not implement it must come out of this+// path with exactly the behaviour it had before.++import (+ "context"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// abandonAwareMedia is a MediaResolver that also implements+// MediaAbandonNotifier — the shape an adapter takes when it can push an+// unsolicited message into the chat the attachment came from.+type abandonAwareMedia struct {+ *fakeMedia+ // block, when set, holds every call until it is closed, whatever the+ // context says: the worst a resolver can do with a chat that is busy or a+ // server that does not answer.+ block <-chan struct{}++ noteMu sync.Mutex+ notes int+ liveCtx bool+ hasDeadline bool+ deadline time.Time+ noteMsg channel.InboundMessage+ noteInst ResolvedInstallation+ noteWhat MediaAbandonment+}++func (m *abandonAwareMedia) NotifyMediaAbandoned(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, a MediaAbandonment) {+ m.noteMu.Lock()+ m.notes+++ // Recorded, not asserted here: a notice handed the context that just+ // expired cannot be written to the chat, which would make the whole call+ // ceremonial.+ m.liveCtx = ctx.Err() == nil+ m.deadline, m.hasDeadline = ctx.Deadline()+ m.noteInst = inst+ m.noteMsg = msg+ m.noteWhat = a+ block := m.block+ m.noteMu.Unlock()+ if block != nil {+ <-block+ }+}++func (m *abandonAwareMedia) abandonment() MediaAbandonment {+ m.noteMu.Lock()+ defer m.noteMu.Unlock()+ return m.noteWhat+}++func (m *abandonAwareMedia) observed() (int, bool, ResolvedInstallation, channel.InboundMessage) {+ m.noteMu.Lock()+ defer m.noteMu.Unlock()+ return m.notes, m.liveCtx, m.noteInst, m.noteMsg+}++// registerMediaSet re-registers the harness's resolver set with a different+// media resolver, leaving every other seam as newHarness built it.+func registerMediaSet(h *harness, media MediaResolver) {+ h.router.Register(channel.TypeFeishu, ResolverSet{+ Installation: h.inst,+ Identity: h.ident,+ Dedup: h.dedup,+ Session: h.binder,+ Audit: h.audit,+ Replier: h.replier,+ Typing: h.typing,+ Media: media,+ OriginType: "lark_chat",+ })+}++// TestRouter_MediaBudgetExpiredTellsAResolverThatCanSaySo is the defect. The+// budget runs out while ResolveMedia is still working, so the resolver returns+// having observed no failure of its own; without this call nothing anywhere+// tells the person who sent the attachment that it did not arrive.+func TestRouter_MediaBudgetExpiredTellsAResolverThatCanSaySo(t *testing.T) {+ h := newHarness(t)+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 10 * time.Millisecond, Logger: discardLogger()})+ h.media.waitForCancel = true+ media := &abandonAwareMedia{fakeMedia: h.media}+ registerMediaSet(h, media)++ msg := p2pMessage(t)+ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(2*time.Second, func() bool { n, _, _, _ := media.observed(); return n > 0 }) {+ t.Fatal("the media budget expired, the refs were dropped, and the resolver was never told: " ++ "nothing on this path can tell the sender their attachment did not arrive, " ++ "so the bot answers the line they typed beside the picture as if there were no picture")+ }+ notes, liveCtx, inst, gotMsg := media.observed()+ if notes != 1 {+ t.Fatalf("the resolver was told %d times about one abandoned message; the sender reads one apology per notice", notes)+ }+ if !liveCtx {+ t.Fatal("the notice was handed the context that had just expired — nothing can be written to the chat on it, " ++ "so the sender is told nothing after all")+ }+ if !inst.ID.Valid {+ t.Fatal("the notice carries no installation, so the resolver cannot work out which socket to write to")+ }+ if gotMsg.MessageID != msg.MessageID {+ t.Fatalf("the notice carries message %q, want %q — the resolver needs the original message to find the chat and the attachments",+ gotMsg.MessageID, msg.MessageID)+ }+ // The refs are still dropped and the run still proceeds on the+ // placeholder. Telling the sender is an addition to that outcome, not a+ // replacement for it.+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 0 {+ t.Fatalf("timed-out media refs must still not attach: %+v", refs)+ }+}++// TestRouter_MediaBudgetExpiredLeavesAResolverThatCannotNotifyAlone is the+// blast-radius guard. MediaAbandonNotifier is shared engine code, and lark and+// dingtalk hand the Router resolvers that do not implement it. For them the+// type assertion must simply miss and the expiry path must end exactly where+// it ended before: refs dropped, message still ingested, placeholder task+// still promoted, no panic, no extra call to anything.+func TestRouter_MediaBudgetExpiredLeavesAResolverThatCannotNotifyAlone(t *testing.T) {+ h := newHarness(t)+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 10 * time.Millisecond, Logger: discardLogger()})+ h.media.waitForCancel = true+ // fakeMedia is the sibling shape: HasMedia + ResolveMedia and nothing else.+ if _, ok := MediaResolver(h.media).(MediaAbandonNotifier); ok {+ t.Fatal("this test is only a guard while the plain resolver does NOT implement the notifier")+ }+ registerMediaSet(h, h.media)++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(2*time.Second, func() bool { return h.media.calls() == 1 }) {+ t.Fatalf("media resolver calls = %d, want 1", h.media.calls())+ }+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 0 {+ t.Fatalf("timed-out media refs must not attach: %+v", refs)+ }+ if !waitFor(2*time.Second, h.tasks.wasCalled) {+ t.Fatal("a channel that cannot send a notice lost its chat run: the message must still be ingested")+ }+ if !waitFor(2*time.Second, func() bool { return h.tasks.promotionCalls() >= 1 }) {+ t.Fatal("a channel that cannot send a notice lost its placeholder promotion")+ }+ if h.dedup.releases() != 0 {+ t.Fatalf("media timeout must not release a durably appended message, got %d", h.dedup.releases())+ }+}++// TestRouter_AnAbandonNoticeThatNeverReturnsDoesNotHoldUpFinalization is the+// latency guard. The notice is a chat write and can wait on a profile lookup,+// the chat's turn and the server's acknowledgement; the bind, the clearing of+// the pending-media marker and the task promotion must not wait behind it,+// nor run on a budget it has spent. The notifier here never returns until the+// test lets it, whatever its context says.+//+// REVERSE VERIFICATION: call NotifyMediaAbandoned inline on finalizeCtx, as+// before, and the bind and promotion never happen while the notice is stuck.+func TestRouter_AnAbandonNoticeThatNeverReturnsDoesNotHoldUpFinalization(t *testing.T) {+ h := newHarness(t)+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 10 * time.Millisecond, Logger: discardLogger()})+ h.media.waitForCancel = true+ stuck := make(chan struct{})+ var unstick sync.Once+ t.Cleanup(func() { unstick.Do(func() { close(stuck) }) })+ media := &abandonAwareMedia{fakeMedia: h.media, block: stuck}+ registerMediaSet(h, media)++ asked := time.Now()+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(2*time.Second, func() bool { n, _, _, _ := media.observed(); return n > 0 }) {+ t.Fatal("the resolver was never told the budget ran out")+ }+ if !waitFor(2*time.Second, func() bool { return h.binder.boundMedia().MessageID.Valid }) {+ t.Fatal("the message was never bound while the notice was stuck: its pending-media marker stays set " ++ "and every later message in the session waits on it")+ }+ if !waitFor(2*time.Second, func() bool { return h.tasks.promotionCalls() >= 1 }) {+ t.Fatal("the task was never promoted while the notice was stuck: the agent does not run until recovery finds it")+ }++ media.noteMu.Lock()+ hasDeadline, deadline := media.hasDeadline, media.deadline+ media.noteMu.Unlock()+ if !hasDeadline {+ t.Fatal("the notice was handed a context with no deadline: a chat that never answers holds its goroutine forever")+ }+ if limit := asked.Add(mediaAbandonNoticeTimeout + time.Second); deadline.After(limit) {+ t.Fatalf("the notice's deadline %s is past the %s bound", deadline.Sub(asked), mediaAbandonNoticeTimeout)+ }++ // Drain counts the notice as media work in flight: it reports the stuck+ // one, and finishes once it returns.+ shortCtx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)+ defer cancel()+ if h.router.Drain(shortCtx) {+ t.Fatal("Drain reported everything finished while the abandon notice was still running")+ }+ unstick.Do(func() { close(stuck) })+ if !h.router.Drain(context.Background()) {+ t.Fatal("Drain did not finish after the notice returned")+ }+}++// TestRouter_TellsTheResolverWhatItDroppedAndWhetherItRan carries the two+// facts only the Router has. When the budget runs out mid-way, the refs+// ResolveMedia did return are discarded after it has returned, so it cannot+// count them; when the budget is gone before the job comes up, ResolveMedia is+// never called, so it saw none of the attachments. Without these the resolver+// either misses attachments or counts the ones it already counted.+//+// REVERSE VERIFICATION: pass a MediaAbandonment with only Cause set and the+// cut-off case fails. (The never-started case is the zero value on both+// fields, so it pins the Router not to report a run that did not happen.)+func TestRouter_TellsTheResolverWhatItDroppedAndWhetherItRan(t *testing.T) {+ t.Run("cut off after one ref landed", func(t *testing.T) {+ h := newHarness(t)+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 20 * time.Millisecond, Logger: discardLogger()})+ h.media.resolve = func(ctx context.Context, msg channel.InboundMessage) channel.InboundMessage {+ msg.MediaRefs = append(msg.MediaRefs, channel.MediaRef{Type: channel.MsgTypeImage, StorageKey: "landed-in-time"})+ <-ctx.Done()+ return msg+ }+ media := &abandonAwareMedia{fakeMedia: h.media}+ registerMediaSet(h, media)++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(2*time.Second, func() bool { n, _, _, _ := media.observed(); return n > 0 }) {+ t.Fatal("the resolver was never told the budget ran out")+ }+ a := media.abandonment()+ if !a.Started {+ t.Error("Started = false, but ResolveMedia ran: the resolver would count again what it already counted")+ }+ if len(a.Dropped) != 1 || a.Dropped[0].StorageKey != "landed-in-time" {+ t.Errorf("Dropped = %+v, want the one ref ResolveMedia returned", a.Dropped)+ }+ if !errors.Is(a.Cause, context.DeadlineExceeded) {+ t.Errorf("Cause = %v, want context.DeadlineExceeded", a.Cause)+ }+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 0 {+ t.Fatalf("the dropped ref was bound anyway: %+v", refs)+ }+ })++ t.Run("never started", func(t *testing.T) {+ h := newHarness(t)+ media := &abandonAwareMedia{fakeMedia: h.media}+ h.router.resolveAndBindMedia(+ ResolverSet{Session: h.binder, Media: media},+ h.inst.inst, h.ident.id,+ uuidFromString(t, "77777777-7777-4777-8777-777777777777"),+ p2pMessage(t), h.binder.ensureID,+ db.Issue{}, pgtype.Text{}, "", pgtype.UUID{},+ true, time.Now().Add(-time.Second),+ )+ if !waitFor(2*time.Second, func() bool { n, _, _, _ := media.observed(); return n > 0 }) {+ t.Fatal("the resolver was never told the budget ran out before it started")+ }+ if h.media.calls() != 0 {+ t.Fatalf("ResolveMedia ran %d time(s) on a budget already spent", h.media.calls())+ }+ a := media.abandonment()+ if a.Started {+ t.Error("Started = true, but ResolveMedia never ran: the resolver would count none of the attachments")+ }+ if len(a.Dropped) != 0 {+ t.Errorf("Dropped = %+v, want none", a.Dropped)+ }+ if !errors.Is(a.Cause, context.DeadlineExceeded) {+ t.Errorf("Cause = %v, want context.DeadlineExceeded", a.Cause)+ }+ })+}++// noticeDrainingMedia is a MediaResolver that sends its own failure notices on+// goroutines and exposes them to Drain, as the WeCom resolver does. Its one+// notice is held until the test lets go.+type noticeDrainingMedia struct {+ *fakeMedia+ held <-chan struct{}+}++func (m *noticeDrainingMedia) DrainMediaNotices() { <-m.held }++// TestRouter_DrainWaitsForAResolversOwnNotices: a resolver that moved its+// notice off the bind path still has it waited for at shutdown, as it was+// when the notice was sent inline inside the media goroutine. The WeCom+// package drives the same thing through the real resolver and a real+// database (TestDrainWaitsForTheResolversOwnNotice).+//+// REVERSE VERIFICATION: drop the DrainMediaNotices loop from Drain and the+// first Drain reports done.+func TestRouter_DrainWaitsForAResolversOwnNotices(t *testing.T) {+ h := newHarness(t)+ held := make(chan struct{})+ var letGo sync.Once+ t.Cleanup(func() { letGo.Do(func() { close(held) }) })+ registerMediaSet(h, ¬iceDrainingMedia{fakeMedia: h.media, held: held})++ short, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)+ defer cancel()+ if h.router.Drain(short) {+ t.Fatal("Drain reported everything finished while a resolver's notice was still in flight")+ }+ letGo.Do(func() { close(held) })+ if !h.router.Drain(context.Background()) {+ t.Fatal("Drain did not finish after the resolver's notices did")+ }+}diff --git a/server/internal/integrations/wecom/language_lint_test.go b/server/internal/integrations/wecom/language_lint_test.goindex f64f76c91f..cfd2346c7a 100644--- a/server/internal/integrations/wecom/language_lint_test.go+++ b/server/internal/integrations/wecom/language_lint_test.go@@ -71,14 +71,12 @@ func TestOnlyStringsGoHoldsUserVisibleCopy(t *testing.T) {}var offenders []offence- // The files below still hold their copy as literals. They are listed with- // an exact count rather than left out of the walk, so the lint still fails- // on a literal added anywhere else — including a new one in a listed file —+ // A file that still holds its copy as literals is listed here with an+ // exact count rather than left out of the walk, so the lint still fails on+ // a literal added anywhere else — including a new one in a listed file —// and fails again if a listed file loses a literal without this list being- // updated.- pending := map[string]int{- "media_ingest.go": 2,- }+ // updated. None is left.+ pending := map[string]int{}for _, name := range packageGoFiles(t, "strings.go") {f, err := parser.ParseFile(fset, filepath.Clean(name), nil, 0)diff --git a/server/internal/integrations/wecom/media_failure_metric_test.go b/server/internal/integrations/wecom/media_failure_metric_test.gonew file mode 100644index 0000000000..aa1eaf9a4d--- /dev/null+++ b/server/internal/integrations/wecom/media_failure_metric_test.go@@ -0,0 +1,221 @@+package wecom++// media_failure_metric_test.go — every attachment that never reached the agent+// is counted once, under the reason an operator acts on.++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++// Per attachment, not per message: the sender hears one sentence for two+// expired links, and an operator asking how much media is being lost wants+// the two. And a guard refusal is its own reason, though the sender reads it+// as the same "did not arrive": what separates them is what the operator must+// change.+//+// REVERSE VERIFICATION: drop the recordFailure call from ResolveMedia and every+// case fails with a zero count.+func TestEveryAttachmentThatFailsIsCountedByReason(t *testing.T) {+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()+ oversize := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Length", "209715200")+ w.WriteHeader(http.StatusOK)+ }))+ defer oversize.Close()++ image := func(url string) map[string]any {+ return map[string]any{"msgtype": "image", "image": map[string]any{"url": url, "aeskey": testAESKey}}+ }++ cases := []struct {+ name string+ // production keeps the real guard, which refuses the loopback test+ // servers; the others use the client that permits them.+ production bool+ items []any+ want map[string]int+ }{+ {+ name: "two expired links are two unreadable attachments",+ items: []any{image(expired.URL), image(expired.URL)},+ want: map[string]int{mediaDropUnreadable: 2},+ },+ {+ name: "one too large and one expired are counted apart",+ items: []any{image(oversize.URL), image(expired.URL)},+ want: map[string]int{mediaDropTooLarge: 1, mediaDropUnreadable: 1},+ },+ {+ name: "an address the guard refuses is its own reason",+ production: true,+ items: []any{image(expired.URL)},+ want: map[string]int{mediaDropBlockedAddress: 1},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if tc.production {+ withAllowed(t)+ }+ storage := &fakeMediaStorage{}+ senders, _ := notifierWithLiveSocket(uuidOf(1))+ mx := newCountingMetrics()+ senders.WithMetrics(mx)+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, nil, testLogger()).(*wecomMediaResolver)+ if !tc.production {+ r.http = testMediaClient()+ }++ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": tc.items}})+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()++ for _, reason := range []string{mediaDropUnreadable, mediaDropTooLarge, mediaDropBlockedAddress} {+ if got := mx.get("media_failure:" + reason); got != tc.want[reason] {+ t.Errorf("media_failure:%s = %d, want %d", reason, got, tc.want[reason])+ }+ }+ })+ }+}++// The notice needs a live socket; the count does not. A failure with nobody to+// tell is exactly the moment it most wants recording.+func TestAFailedAttachmentIsCountedWithNoSocketToTellTheSender(t *testing.T) {+ t.Parallel()+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()++ mx := newCountingMetrics()+ senders := newSendersRegistry().WithMetrics(mx) // no connection registered+ storage := &fakeMediaStorage{}+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)++ msg := mediaMessage(t, "image", map[string]any{+ "image": map[string]any{"url": expired.URL, "aeskey": testAESKey},+ })+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()++ if got := mx.get("media_failure:" + mediaDropUnreadable); got != 1 {+ t.Fatalf("media_failure:unreadable = %d, want 1", got)+ }+}++// allMediaDropReasons is the label set, read off the constants rather than+// spelled again, so a count under any of them shows up in the sums below.+var allMediaDropReasons = []string{+ mediaDropUnreadable, mediaDropTooLarge, mediaDropBlockedAddress,+ mediaDropBudgetExpired, mediaDropShutdown,+}++// The attachments the Router's budget takes are counted too, once each, under+// the budget's own reason, with no socket to tell anyone on. Two paths reach+// that: the budget is gone before ResolveMedia is called, so the resolver+// never sees the attachments at all; or it runs out mid-way, and the Router+// then drops even the refs that did land. On the second path the attachments+// split three ways — landed and dropped, cut off, failed on their own before+// the deadline — and each is counted at exactly one place, so the total is+// the number of attachments sent.+//+// REVERSE VERIFICATION: drop the recordFailure call from NotifyMediaAbandoned+// and "never started" counts nothing and "cut off" misses the landed one;+// count every in-loop failure as its own kind again and "cut off" reports+// the cut-off ones as unreadable; count len(wm.Media) on both paths and "cut+// off" counts every attachment ResolveMedia already failed on a second time.+func TestEveryAttachmentTheBudgetTookIsCountedOnce(t *testing.T) {+ landed := cosServer(t, []byte("\x89PNG\r\n\x1a\nlanded in time"), `attachment; filename="a.png"`)+ defer landed.Close()+ oversize := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Length", "209715200")+ w.WriteHeader(http.StatusOK)+ }))+ defer oversize.Close()+ slow := stallingCOS(t, 800*time.Millisecond, []byte("\x89PNG\r\n\x1a\nslower than the budget"))+ defer slow.Close()+ image := func(url string) map[string]any {+ return map[string]any{"msgtype": "image", "image": map[string]any{"url": url, "aeskey": testAESKey}}+ }++ cases := []struct {+ name string+ items []any+ deadline func() time.Time+ want map[string]int+ }{+ {+ name: "never started",+ items: []any{image(landed.URL), image(landed.URL), image(landed.URL)},+ deadline: func() time.Time { return time.Now().Add(-time.Millisecond) },+ want: map[string]int{mediaDropBudgetExpired: 3},+ },+ {+ // landed and then dropped by the Router, too large on its own+ // merits, cut off mid-download, and never reached before the+ // deadline.+ name: "cut off",+ items: []any{image(landed.URL), image(oversize.URL), image(slow.URL), image(landed.URL)},+ deadline: func() time.Time { return time.Now().Add(300 * time.Millisecond) },+ want: map[string]int{mediaDropBudgetExpired: 3, mediaDropTooLarge: 1},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ mx := newCountingMetrics()+ senders := newSendersRegistry().WithMetrics(mx) // no connection registered+ storage := &fakeMediaStorage{}+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": tc.items}})++ asTheRouterDoes(t, r, tc.deadline(), mediaInstallation(), msg)++ total := 0+ for _, reason := range allMediaDropReasons {+ got := mx.get("media_failure:" + reason)+ total += got+ if got != tc.want[reason] {+ t.Errorf("media_failure:%s = %d, want %d", reason, got, tc.want[reason])+ }+ }+ if total != len(tc.items) {+ t.Errorf("%d attachments sent, %d counted: every one that never reached the agent is counted exactly once", len(tc.items), total)+ }+ })+ }+}++// A budget ended by shutdown is counted under its own reason: a deploy is+// expected to cut downloads off, and folding it into budget_expired would make+// every deploy look like a slow media host.+//+// REVERSE VERIFICATION: return mediaDropBudgetExpired for every cause in+// abandonReason and this counts three budget_expired.+func TestAttachmentsAbandonedAtShutdownAreCountedApart(t *testing.T) {+ t.Parallel()+ mx := newCountingMetrics()+ senders := newSendersRegistry().WithMetrics(mx)+ storage := &fakeMediaStorage{}+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)+ image := map[string]any{"msgtype": "image", "image": map[string]any{"url": "https://cos.example/x", "aeskey": testAESKey}}+ msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{image, image, image}}})++ r.NotifyMediaAbandoned(context.Background(), mediaInstallation(), msg, engine.MediaAbandonment{Cause: context.Canceled})++ if got := mx.get("media_failure:" + mediaDropShutdown); got != 3 {+ t.Errorf("media_failure:shutdown = %d, want 3", got)+ }+ if got := mx.get("media_failure:" + mediaDropBudgetExpired); got != 0 {+ t.Errorf("media_failure:budget_expired = %d, want 0", got)+ }+}diff --git a/server/internal/integrations/wecom/media_guard_allow_test.go b/server/internal/integrations/wecom/media_guard_allow_test.goindex 2ec1aa10ce..250a69bf9c 100644--- a/server/internal/integrations/wecom/media_guard_allow_test.go+++ b/server/internal/integrations/wecom/media_guard_allow_test.go@@ -294,13 +294,14 @@ func TestAGuardRefusalNeverPutsAnAddressOrUrlInTheChat(t *testing.T) {// NOT newTestResolver: that one swaps in a client which permits loopback,// which is the very thing under test here. This keeps the production// guard.- r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, testLogger()).(*wecomMediaResolver)+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, nil, testLogger()).(*wecomMediaResolver)msg := mediaMessage(t, "mixed", map[string]any{"mixed": map[string]any{"msg_item": []any{map[string]any{"msgtype": "image", "image": map[string]any{"url": srv.URL, "aeskey": testAESKey}},map[string]any{"msgtype": "image", "image": map[string]any{"url": "ftp://cos.example.com/object", "aeskey": testAESKey}},}}})out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(out.MediaRefs) != 0 {t.Fatalf("MediaRefs = %d, want 0 — the guard was supposed to refuse this fetch", len(out.MediaRefs))@@ -314,7 +315,7 @@ func TestAGuardRefusalNeverPutsAnAddressOrUrlInTheChat(t *testing.T) {body := conn.sendBody(t, 0)md, _ := body["markdown"].(map[string]any)content, _ := md["content"].(string)- if content != mediaUnreadableNotice {+ if content != copyFor(DefaultLocale).MediaUnreadable {t.Errorf("notice = %q, want the plain did-not-arrive wording exactly once", content)}for _, secret := range []string{"127.0.0.1", "::1", srv.URL, testAESKey} {diff --git a/server/internal/integrations/wecom/media_ingest.go b/server/internal/integrations/wecom/media_ingest.goindex e0c814ca2d..a8b8d32f8b 100644--- a/server/internal/integrations/wecom/media_ingest.go+++ b/server/internal/integrations/wecom/media_ingest.go@@ -30,6 +30,8 @@ import ("path""slices""strings"+ "sync"+ "time""github.com/jackc/pgx/v5/pgtype"@@ -38,13 +40,28 @@ import ("github.com/multica-ai/multica/server/internal/util")-// mediaFailureNotice lines. WeCom deployments are China-only, so these follow-// the Chinese product voice the rest of this adapter already writes in-// (wecom_channel.go's receipt, router.go's session titles).-const (- mediaUnreadableNotice = "抱歉,有附件没能收到,麻烦重新发一次。"- mediaTooLargeNotice = "抱歉,附件太大了,我这边收不下。"-)+// The two failure lines are copyPack.MediaUnreadable / MediaTooLarge+// (strings.go), read in the language of the chat they land in.++// mediaNoticeLocaleTimeout bounds the profile lookup behind the failure+// notice. Deliberately small: the notice is worth sending in the wrong+// language, and not worth delaying.+const mediaNoticeLocaleTimeout = 2 * time.Second++// mediaNoticeTimeout bounds the notice ResolveMedia sends about its own+// failures: the lookup above, a wait for the chat's turn behind an answer+// already streaming, and one server acknowledgement. Same size, and same+// reasoning, as the Router's bound on the notice it asks for when its budget+// runs out (engine.mediaAbandonNoticeTimeout).+const mediaNoticeTimeout = 15 * time.Second++// mediaNoticeQueries is what the failure notice reads before it writes: the+// reader's language, and whether the installation may still write at all+// (replyWriteGuard). *db.Queries is both.+type mediaNoticeQueries interface {+ languageLookup+ installationReader+}// mediaStorage is the slice of storage.Storage this resolver drives.// ObjectURL is a pure function of configuration, which is what lets the@@ -69,26 +86,65 @@ type wecomMediaResolver struct {// sender an attachment did not make it. nil disables the notice and// leaves only the log.notify *sendersRegistry- logger *slog.Logger+ // queries picks the failure notice's language from where it lands+ // (language.go: a 1:1 reads the sender's profile, a room the+ // deployment's) and asks, as the notice is written, whether the+ // installation was revoked since the message came in. nil puts every+ // notice on the deployment default and writes it unchecked.+ queries mediaNoticeQueries+ // notices counts the failure notices ResolveMedia has sent off on their+ // own goroutines, so that the Router's Drain can wait for them+ // (DrainMediaNotices) the way it waited when they were sent inline.+ notices sync.WaitGroup+ logger *slog.Logger}// NewMediaResolver builds the wecom MediaResolver. storage and ledger are// required — without either there is nothing durable to point an attachment// at, and the resolver degrades to leaving the placeholder in place. senders-// is optional: without it a failed attachment is only logged.-func NewMediaResolver(storage mediaStorage, ledger engine.MediaIntentLedger, senders *sendersRegistry, logger *slog.Logger) engine.MediaResolver {+// is optional: without it a failed attachment is only logged and the failure+// counter — which reports through the same registry — goes nowhere; so is+// queries, without which the notice is written in the deployment's language+// and is not checked against a revoked installation.+func NewMediaResolver(storage mediaStorage, ledger engine.MediaIntentLedger, senders *sendersRegistry, queries mediaNoticeQueries, logger *slog.Logger) engine.MediaResolver {if logger == nil {logger = slog.Default()}+ if queries == nil {+ logger.Warn("wecom media: no queries wired; attachment-failure notices go out in the deployment language whatever the reader's profile says, and are written even after the installation is revoked")+ }return &wecomMediaResolver{storage: storage,ledger: ledger,// Never a bare http.Client: the URL being fetched came off the wire,// and this client refuses to connect to anything that is not public// internet (media_guard.go).- http: newMediaHTTPClient(mediaGuard{}),- notify: senders,- logger: logger,+ http: newMediaHTTPClient(mediaGuard{}),+ notify: senders,+ queries: queries,+ logger: logger,+ }+}++// recordFailure reports n attachments that never reached the agent, under+// the reason an operator would act on (the mediaDrop* constants).+//+// It goes through the senders registry the resolver already holds rather than+// a sink of its own: this type is built at boot from router.go with five+// arguments already, and the registry is the one thing here that both knows+// about metrics and is guaranteed to be the same instance the read loop+// reports through.+//+// Each attachment is counted at exactly one of two places. ResolveMedia counts+// every attachment it failed on, whatever the reason. NotifyMediaAbandoned+// counts the ones ResolveMedia never saw fail: all of them when it never ran,+// and the refs it returned that the Router then dropped when it did.+func (r *wecomMediaResolver) recordFailure(reason string, n int) {+ if r.notify == nil {+ return+ }+ for range n {+ r.notify.RecordMediaFailure(reason)}}@@ -128,7 +184,26 @@ func (r *wecomMediaResolver) ResolveMedia(ctx context.Context, inst engine.Resolref, err := r.ingestOne(ctx, inst, chatMessageID, wm, i, m)if err != nil {failure := classifyMediaFailure(err)- failures = appendFailure(failures, failure)+ // Counted per attachment, not per message: appendFailure+ // deliberately collapses four expired links into one sentence for+ // the sender, and an operator asking how much media is being lost+ // wants the four. Counted here rather than beside the notice for+ // the same reason the log line is here — tellTheSender is skipped+ // entirely when there is no live socket to write to, which is+ // exactly the moment a failure most wants recording.+ if failure == mediaFailureUnreadable && ctx.Err() != nil {+ // The Router's budget cut this one off: it ran out mid-download,+ // or before this attachment's turn came and every step on the+ // dead context failed at once. Counted as that, not as+ // unreadable, or a budget too small for the files people send+ // would read as WeCom serving broken links. Left out of the+ // sender's notice: the Router is about to ask for that one+ // (NotifyMediaAbandoned).+ r.recordFailure(abandonReason(ctx.Err()), 1)+ } else {+ r.recordFailure(failure.metricReason(), 1)+ failures = appendFailure(failures, failure)+ }// A refused address gets its own line because the operator's next// move is different from every other failure here: the attachment// is fine and the deployment declined to dial where its host@@ -153,7 +228,34 @@ func (r *wecomMediaResolver) ResolveMedia(ctx context.Context, inst engine.Resolmsg.MediaRefs = append(msg.MediaRefs, ref)}- r.tellTheSender(inst, wm, failures)+ // When the Router's media budget ran out under us, the Router follows with+ // NotifyMediaAbandoned — and that says the same sentence, because from+ // where the sender is sitting it is the same event. Saying it here as well+ // gives them the identical apology twice in a row, which reads as the bot+ // glitching rather than as one attachment that did not make it.+ //+ // Only the line the Router is about to repeat is dropped. A "too big"+ // verdict was reached on its own merits before the clock ran out, and it+ // is the one the sender can actually act on, so it still goes.+ if ctx.Err() != nil {+ failures = withoutNotice(failures, mediaFailureUnreadable)+ }++ // On its own goroutine and its own deadline: the Router binds this+ // message, clears its pending-media marker and promotes its task only once+ // this returns, and a notice waiting on the chat's turn or on the server's+ // acknowledgement must not hold that up, nor spend the budget that decides+ // whether the refs above are kept. Counted in notices, so the Router's+ // Drain still waits for it (DrainMediaNotices).+ if len(failures) > 0 {+ r.notices.Add(1)+ go func() {+ defer r.notices.Done()+ noticeCtx, cancel := context.WithTimeout(context.Background(), mediaNoticeTimeout)+ defer cancel()+ r.tellTheSender(noticeCtx, inst, wm, failures)+ }()+ }return msg}@@ -352,6 +454,32 @@ func classifyMediaFailure(err error) mediaFailure {return mediaFailureUnreadable}+// abandonReason is the label for an attachment the Router's budget took, by+// what ended the budget: running out, or the server shutting down. The two+// want different answers (a bigger budget or a faster media host, versus+// nothing), and a deploy would otherwise read as a slow-download incident.+func abandonReason(cause error) string {+ if errors.Is(cause, context.Canceled) {+ return mediaDropShutdown+ }+ return mediaDropBudgetExpired+}++// metricReason is the label this failure is counted under. The sender's+// wording folds "blocked" into "unreadable" — there is nothing they can do+// differently either way — but the operator's does not, which is the whole+// reason this kind exists.+func (f mediaFailure) metricReason() string {+ switch f {+ case mediaFailureTooLarge:+ return mediaDropTooLarge+ case mediaFailureBlocked:+ return mediaDropBlockedAddress+ default:+ return mediaDropUnreadable+ }+}+// appendFailure keeps one entry per kind. A message with four attachments// that all expired is one thing that went wrong, and saying it four times// helps nobody.@@ -364,6 +492,85 @@ func appendFailure(list []mediaFailure, f mediaFailure) []mediaFailure {return append(list, f)}+// noticeKind collapses the failure kinds that read as the same sentence down+// to the one that names it. Two kinds do: mediaFailureBlocked lands on the+// unreadable wording deliberately, because from the sender's side a refused+// address and a download that fell over are the same event — the attachment+// did not arrive — and the thing that separates them is what the operator must+// change, which belongs in the log. Neither the resolved address nor the+// signed url goes into a chat message.+//+// Anything reasoning about "would these two read the same" asks here. It+// cannot compare the rendered sentences: since the copy pack those are the+// reader's, and two readers in one group get different strings for the one+// event.+func noticeKind(f mediaFailure) mediaFailure {+ if f == mediaFailureTooLarge {+ return mediaFailureTooLarge+ }+ return mediaFailureUnreadable+}++// noticeFor is the one place a failure kind becomes a sentence, in the+// language c is written in.+func noticeFor(c copyPack, f mediaFailure) string {+ if noticeKind(f) == mediaFailureTooLarge {+ return c.MediaTooLarge+ }+ return c.MediaUnreadable+}++// withoutNotice drops every kind that would read the same as drop, leaving the+// rest in order. It goes through noticeKind rather than comparing kinds+// directly because the sender reads sentences: dropping mediaFailureUnreadable+// while leaving mediaFailureBlocked in the list would still print the same+// line twice.+func withoutNotice(list []mediaFailure, drop mediaFailure) []mediaFailure {+ out := list[:0]+ for _, f := range list {+ if noticeKind(f) != noticeKind(drop) {+ out = append(out, f)+ }+ }+ return out+}++// DrainMediaNotices answers engine.MediaNoticeDrainer: it returns once every+// failure notice ResolveMedia has sent off has finished. Each runs under+// mediaNoticeTimeout, so the wait is bounded by that.+func (r *wecomMediaResolver) DrainMediaNotices() {+ r.notices.Wait()+}++// NotifyMediaAbandoned answers engine.MediaAbandonNotifier: the Router's own+// media budget expired, so this resolver either never ran or was cut off, and+// the Router has dropped whatever refs it did return.+//+// It counts what ResolveMedia could not: every attachment when ResolveMedia+// never ran, and otherwise only the refs it returned that the Router dropped.+// The ones ResolveMedia failed on it has already counted, so counting them+// here would count them twice.+//+// The sender gets the same line as an attachment that could not be read,+// because from where they are sitting it is the same event and the same+// remedy: the picture did not get through, send it again. Which side of the+// seam ran out of time is ours to know and theirs not to care about.+//+// ctx is the Router's, with its own deadline; the lookup and the write below+// both run under it.+func (r *wecomMediaResolver) NotifyMediaAbandoned(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, a engine.MediaAbandonment) {+ wm, err := wecomMsgFromRaw(msg)+ if err != nil || len(wm.Media) == 0 {+ return+ }+ lost := len(a.Dropped)+ if !a.Started {+ lost = len(wm.Media)+ }+ r.recordFailure(abandonReason(a.Cause), lost)+ r.tellTheSender(ctx, inst, wm, []mediaFailure{mediaFailureUnreadable})+}+// tellTheSender writes one short notice into the chat the attachments came// from, over the same live aibot socket every other wecom message uses.//@@ -372,7 +579,7 @@ func appendFailure(list []mediaFailure, f mediaFailure) []mediaFailure {// never received. The agent run itself is deliberately left to proceed — the// person can see for themselves that the picture did not get through, and the// answer to whatever they typed beside it is still worth having.-func (r *wecomMediaResolver) tellTheSender(inst engine.ResolvedInstallation, wm InboundMessage, failures []mediaFailure) {+func (r *wecomMediaResolver) tellTheSender(ctx context.Context, inst engine.ResolvedInstallation, wm InboundMessage, failures []mediaFailure) {if len(failures) == 0 || r.notify == nil || !inst.ID.Valid {return}@@ -395,27 +602,29 @@ func (r *wecomMediaResolver) tellTheSender(inst engine.ResolvedInstallation, wmif strings.EqualFold(wm.ChatType, "group") {chatType = chatTypeGroupInt}+ // ctx is the notice's own, never the media budget's: the commonest reason+ // to be here is a download that ran out of time, and on that path the+ // budget is already spent. The lookup gets a shorter slice of it, so a+ // stalled profile read costs the notice its language and not the notice.+ lookupCtx, cancel := context.WithTimeout(ctx, mediaNoticeLocaleTimeout)+ c := copyFor(localeFor(lookupCtx, r.queries, inst.ID, chatType, wm.SenderUserID))+ cancel()+lines := make([]string, 0, len(failures))for _, f := range failures {- notice := mediaUnreadableNotice- if f == mediaFailureTooLarge {- notice = mediaTooLargeNotice- }- // mediaFailureBlocked lands on the unreadable wording deliberately.- // From the sender's side a refused address and a download that fell- // over are the same event — the attachment did not arrive — and the- // thing that separates them is what the operator must change, which- // belongs in the log. Neither the resolved address nor the signed url- // goes into a chat message.- //- // Two kinds sharing one wording is why the dedupe moved here from- // appendFailure: a message with one blocked and one unreadable- // attachment is still one piece of news.- if !slices.Contains(lines, notice) {+ // Deduped by sentence, not by kind: two kinds share the unreadable+ // wording (see noticeFor), so a message with one blocked and one+ // unreadable attachment is still one piece of news. That is why the+ // dedupe is here rather than in appendFailure, which the operator log+ // needs kept per-kind.+ if notice := noticeFor(c, f); !slices.Contains(lines, notice) {lines = append(lines, notice)}}- if err := sender.sendText(chatID, chatType, strings.Join(lines, "\n")); err != nil {+ // guardReply: the installation was read when the message came in, which+ // can be a whole media budget ago. A revocation since then stops the+ // notice at the socket, as it stops every reply frame.+ if err := sender.sendTextCtx(guardReply(ctx, r.queries, inst.ID), chatID, chatType, strings.Join(lines, "\n")); err != nil {r.logger.Warn("wecom media failure notice not delivered","installation_id", util.UUIDToString(inst.ID), "msg_id", wm.MsgID, "err", err)}diff --git a/server/internal/integrations/wecom/media_ingest_test.go b/server/internal/integrations/wecom/media_ingest_test.goindex 153f2844ef..effeb5baf5 100644--- a/server/internal/integrations/wecom/media_ingest_test.go+++ b/server/internal/integrations/wecom/media_ingest_test.go@@ -184,7 +184,7 @@ func mediaInstallation() engine.ResolvedInstallation {func TestHasMediaLooksOnlyAtWhatIsAlreadyInHand(t *testing.T) {t.Parallel()- r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())+ r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, nil, testLogger())cases := []struct {name stringmsgType string@@ -215,7 +215,7 @@ func TestHasMediaLooksOnlyAtWhatIsAlreadyInHand(t *testing.T) {func TestHasMediaSaysNoWhenThereIsNoUrlToFetch(t *testing.T) {t.Parallel()- r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())+ r := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, nil, testLogger())// A body with an aeskey and no url is not something we can download; it// must not buy the message a media deadline and a deferred agent run.mc := aibotMsgCallback{MsgType: "image"}@@ -233,7 +233,7 @@ func TestHasMediaSaysNoWhenThereIsNoUrlToFetch(t *testing.T) {// runs is reachable while the guard's own decision stays under test in// media_guard_test.go.func newTestResolver(storage mediaStorage, ledger engine.MediaIntentLedger, senders *sendersRegistry) *wecomMediaResolver {- r := NewMediaResolver(storage, ledger, senders, testLogger()).(*wecomMediaResolver)+ r := NewMediaResolver(storage, ledger, senders, nil, testLogger()).(*wecomMediaResolver)r.http = testMediaClient()return r}@@ -267,6 +267,7 @@ func TestResolveMediaStoresTheDecryptedFile(t *testing.T) {"image": map[string]any{"url": srv.URL, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 1 {t.Fatalf("MediaRefs = %d, want 1", len(got.MediaRefs))@@ -318,6 +319,7 @@ func TestResolveMediaRecordsIntentBeforeUploading(t *testing.T) {"file": map[string]any{"url": srv.URL, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(ledger.records) != 1 {t.Fatalf("intent rows = %d, want 1", len(ledger.records))@@ -353,6 +355,7 @@ func TestResolveMediaSkipsAKeyTheReconcilerOwns(t *testing.T) {"image": map[string]any{"url": srv.URL, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(storage.stored()) != 0 {t.Fatal("uploaded into a key the reconciler owns")}@@ -382,6 +385,7 @@ func TestResolveMediaKeepsGoingWhenOneAttachmentFails(t *testing.T) {map[string]any{"msgtype": "image", "image": map[string]any{"url": good.URL, "aeskey": testAESKey}},}}})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 1 {t.Fatalf("MediaRefs = %d, want the one that downloaded", len(got.MediaRefs))@@ -438,7 +442,8 @@ func TestResolveMediaTellsTheSenderWhatWentWrong(t *testing.T) {"file": map[string]any{"url": oversize.URL, "aeskey": testAESKey},})r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)- if got := noticeText(t, conn); got != mediaTooLargeNotice {+ r.notices.Wait()+ if got := noticeText(t, conn); got != copyFor(DefaultLocale).MediaTooLarge {t.Fatalf("notice = %q, want the too-large wording", got)}})@@ -452,7 +457,8 @@ func TestResolveMediaTellsTheSenderWhatWentWrong(t *testing.T) {map[string]any{"msgtype": "image", "image": map[string]any{"url": expired.URL, "aeskey": testAESKey}},}}})r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)- if got := noticeText(t, conn); got != mediaUnreadableNotice {+ r.notices.Wait()+ if got := noticeText(t, conn); got != copyFor(DefaultLocale).MediaUnreadable {t.Fatalf("notice = %q, want the unreadable wording once", got)}})@@ -467,6 +473,7 @@ func TestResolveMediaTellsTheSenderWhatWentWrong(t *testing.T) {"image": map[string]any{"url": srv.URL, "aeskey": testAESKey},})r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(conn.frames) != 0 {t.Fatalf("sent %d notices for a message that worked", len(conn.frames))}@@ -482,6 +489,7 @@ func TestResolveMediaTellsTheSenderWhatWentWrong(t *testing.T) {"image": map[string]any{"url": expired.URL, "aeskey": testAESKey},})r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(conn.frames) != 1 {t.Fatalf("notices = %d, want 1", len(conn.frames))}@@ -514,6 +522,7 @@ func TestResolveMediaRefusesAnUndecryptablePayload(t *testing.T) {msg := channelMessageFromCallback("wb-1", "", mc, "[Image]", "req-1")got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(storage.stored()) != 0 {t.Fatal("stored bytes it could not decrypt")}@@ -540,6 +549,7 @@ func TestResolveMediaNamesAnUnnamedFile(t *testing.T) {map[string]any{"msgtype": "image", "image": map[string]any{"url": srv.URL, "aeskey": testAESKey}},}}})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 2 {t.Fatalf("MediaRefs = %d, want 2", len(got.MediaRefs))@@ -576,6 +586,7 @@ func TestResolveMediaKeepsTheKeyPerChatMessage(t *testing.T) {"image": map[string]any{"url": srv.URL, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), chatMessageID, msg)+ r.notices.Wait()if len(got.MediaRefs) != 1 {t.Fatalf("MediaRefs = %d", len(got.MediaRefs))}@@ -598,6 +609,7 @@ func TestResolveMediaWithoutStorageLeavesThePlaceholder(t *testing.T) {"image": map[string]any{"url": "https://cos.invalid/a", "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 0 {t.Fatal("produced refs with no storage configured")}@@ -622,6 +634,7 @@ func TestResolveMediaSurvivesAConnectionThatWentAway(t *testing.T) {"image": map[string]any{"url": expired.URL, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 0 {t.Fatal("produced a ref for an attachment that never downloaded")}@@ -697,13 +710,14 @@ func resolveOneAttachment(t *testing.T, storage mediaStorage, url string) stringif s, ok := storage.(*fakeStreamStorage); ok {inspect = &s.fakeMediaStorage}- r := NewMediaResolver(storage, newFakeMediaLedger(inspect), nil, logger).(*wecomMediaResolver)+ r := NewMediaResolver(storage, newFakeMediaLedger(inspect), nil, nil, logger).(*wecomMediaResolver)r.http = testMediaClient()msg := mediaMessage(t, "image", map[string]any{"image": map[string]any{"url": url, "aeskey": testAESKey},})got := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(got.MediaRefs) != 1 {t.Fatalf("MediaRefs = %d, want the attachment to have landed", len(got.MediaRefs))}diff --git a/server/internal/integrations/wecom/media_notice_locale_test.go b/server/internal/integrations/wecom/media_notice_locale_test.gonew file mode 100644index 0000000000..969fda5ad1--- /dev/null+++ b/server/internal/integrations/wecom/media_notice_locale_test.go@@ -0,0 +1,359 @@+package wecom++// media_notice_locale_test.go — the attachment-failure notice is written in+// the language of the person it lands in front of, a profile lookup that+// never answers delays it by its own small budget and no more, and nothing+// the notice waits on holds up the caller or outlives the context it is given.++import (+ "context"+ "fmt"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "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"+)++// TestMediaFailureNoticeReadsTheSendersLanguage drives the whole ingest, not+// tellTheSender directly: the notice runs after the download has already+// failed, on a context the caller may well have let expire, and resolving the+// language is the part of that path most likely to be skipped by accident.+func TestMediaFailureNoticeReadsTheSendersLanguage(t *testing.T) {+ t.Parallel()+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()++ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ storage := &fakeMediaStorage{}+ senders, conn := notifierWithLiveSocket(uuidOf(1))+ // mediaMessage sends as T-alex in a 1:1, so the notice is+ // addressed to one person and reads their profile.+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders,+ activeInstallation(fakeLanguages{senderID: "T-alex", userID: localeTestUserID, language: tc.language}),+ testLogger()).(*wecomMediaResolver)+ r.http = testMediaClient()++ msg := mediaMessage(t, "image", map[string]any{+ "image": map[string]any{"url": expired.URL, "aeskey": testAESKey},+ })+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()++ if got, want := sentMarkdown(t, conn, 0), copyPacks[tc.locale].MediaUnreadable; got != want {+ t.Fatalf("failure notice = %q, want the %s copy %q", got, tc.locale, want)+ }+ })+ }+}++// noticeQueries is the notice's two reads: a language lookup, and the+// installation row replyWriteGuard reads as the notice is written. The row is+// answered by id, as production answers it: the one installation it holds,+// pgx.ErrNoRows for any other.+type noticeQueries struct {+ languageLookup+ instID pgtype.UUID+ revoked bool+}++func (q noticeQueries) GetChannelInstallation(_ context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ if arg.ID != q.instID || arg.ChannelType != channelTypeWecom {+ return db.ChannelInstallation{}, pgx.ErrNoRows+ }+ status := InstallationActive+ if q.revoked {+ status = InstallationRevoked+ }+ return db.ChannelInstallation{ID: q.instID, Status: string(status)}, nil+}++// activeInstallation pairs a language lookup with mediaInstallation's row,+// still active.+func activeInstallation(languages languageLookup) noticeQueries {+ return noticeQueries{languageLookup: languages, instID: mediaInstallation().ID}+}++// stalledLanguages is a languageLookup that never answers. It stands for the+// case the notice's own budget exists for: the profile row is behind a lock,+// or the pool is drained by whatever also broke the download.+type stalledLanguages struct{}++func (stalledLanguages) GetChannelUserBindingByUserID(ctx context.Context, _ db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error) {+ <-ctx.Done()+ return db.ChannelUserBinding{}, ctx.Err()+}++func (stalledLanguages) GetUser(ctx context.Context, _ pgtype.UUID) (db.User, error) {+ <-ctx.Done()+ return db.User{}, ctx.Err()+}++// A lookup that never answers must not cost the notice: it goes out once the+// lookup's budget is spent, in the deployment's language, rather than being+// dropped along with the attachment that already failed.+//+// The lower bound on the wait is what keeps this honest — a notice that went+// out sooner did not wait on the lookup at all, and then nothing here was+// tested.+func TestMediaFailureNoticeSurvivesAStalledLookup(t *testing.T) {+ restoreLocale(t, LocaleEn)++ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()++ storage := &fakeMediaStorage{}+ senders, conn := notifierWithLiveSocket(uuidOf(1))+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, activeInstallation(stalledLanguages{}), testLogger()).(*wecomMediaResolver)+ r.http = testMediaClient()++ msg := mediaMessage(t, "image", map[string]any{+ "image": map[string]any{"url": expired.URL, "aeskey": testAESKey},+ })++ started := time.Now()+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()+ waited := time.Since(started)++ if got, want := sentMarkdown(t, conn, 0), copyPacks[LocaleEn].MediaUnreadable; got != want {+ t.Fatalf("notice = %q, want the deployment's %q — a lookup that never answers must not change what is said, only who it is said to", got, want)+ }+ if waited < mediaNoticeLocaleTimeout {+ t.Errorf("the notice went out in %s, before the %s budget was spent — the lookup was not actually waited on, so this proves nothing", waited, mediaNoticeLocaleTimeout)+ }+ if waited > 4*mediaNoticeLocaleTimeout {+ t.Errorf("the notice took %s against a %s budget; something other than the lookup is holding it", waited, mediaNoticeLocaleTimeout)+ }+}++// The notice ResolveMedia sends about its own failures must not hold up its+// return. The Router binds the message, clears its pending-media marker and+// promotes its task only once ResolveMedia returns, and a notice waiting for+// the chat's turn — here, behind an answer that holds the chat — would spend+// that time and, past the deadline, the refs that did arrive.+//+// REVERSE VERIFICATION: call tellTheSender inline instead of on its goroutine+// and ResolveMedia does not return until the chat is released.+func TestResolveMediaDoesNotWaitForItsNotice(t *testing.T) {+ t.Parallel()+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()++ storage := &fakeMediaStorage{}+ senders, conn := notifierWithLiveSocket(uuidOf(1))+ r := newTestResolver(storage, newFakeMediaLedger(storage), senders)+ release, err := conn.sender.chats.acquire(context.Background(), "T-alex")+ if err != nil {+ t.Fatalf("hold the chat: %v", err)+ }++ returned := make(chan struct{})+ go func() {+ defer close(returned)+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5),+ mediaMessage(t, "image", map[string]any{"image": map[string]any{"url": expired.URL, "aeskey": testAESKey}}))+ }()+ select {+ case <-returned:+ case <-time.After(2 * time.Second):+ release()+ <-returned+ t.Fatal("ResolveMedia waited for its failure notice to get the chat's turn; the Router cannot bind the " ++ "message or promote its task until it returns")+ }++ release()+ r.notices.Wait()+ if got, want := sentMarkdown(t, conn, 0), copyFor(DefaultLocale).MediaUnreadable; got != want {+ t.Fatalf("the notice, once the chat was free, read %q, want %q", got, want)+ }+}++// ResolveMedia's notice is off the bind path, and the Router's Drain still+// waits for it, as it did when the notice was sent inline: a deploy must not+// cut it off mid-send. Real Router, real wecom ResolverSet, real database; the+// notice is held behind the chat's turn, and the media job has finished (the+// promotion ran) before Drain is asked.+//+// REVERSE VERIFICATION: drop the DrainMediaNotices loop from Router.Drain and+// Drain reports everything finished while the notice is still waiting.+func TestDrainWaitsForTheResolversOwnNotice(t *testing.T) {+ pool := mediaBindTestDB(t)+ fixture := seedMediaBindFixture(t, pool)+ ctx := context.Background()+ queries := db.New(pool)++ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()++ senders, conn := liveSocketThatAcks(fixture.installationID)+ release, err := conn.sender.chats.acquire(ctx, fixture.senderID)+ if err != nil {+ t.Fatalf("hold the chat: %v", err)+ }+ var once sync.Once+ letGo := func() { once.Do(release) }+ t.Cleanup(letGo)++ storage := &fakeMediaStorage{}+ resolver := newTestResolver(storage, engine.NewDBMediaIntentLedger(queries), senders)+ session := engine.NewChatSession(queries, pool, TypeWecom, engine.SessionTitles{+ Group: "群聊", Direct: "单聊", Fallback: "会话",+ })+ tasks := &bindTestTasks{}+ router := engine.NewRouter(bindTestIssues{}, tasks, queries, engine.RouterConfig{+ MediaTimeout: 20 * time.Second,+ Logger: testLogger(),+ })+ router.Register(TypeWecom, NewResolverSet(NewStore(queries), session, nil, resolver))++ msgID := fmt.Sprintf("MSGID-DRAIN-%d", time.Now().UnixNano())+ if err := router.Handle(ctx, wecomImageCallback(t, fixture.botID, fixture.senderID, msgID, expired.URL)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ deadline := time.Now().Add(15 * time.Second)+ for tasks.promotions() == 0 {+ if time.Now().After(deadline) {+ t.Fatal("the media job never finished: the notice held up the bind and the promotion")+ }+ time.Sleep(20 * time.Millisecond)+ }++ short, cancel := context.WithTimeout(ctx, 200*time.Millisecond)+ defer cancel()+ if router.Drain(short) {+ t.Fatal("Drain reported everything finished while the resolver's failure notice was still waiting " ++ "for the chat: a deploy at this moment cuts the notice off mid-send")+ }++ letGo()+ full, cancelFull := context.WithTimeout(ctx, 10*time.Second)+ defer cancelFull()+ if !router.Drain(full) {+ t.Fatal("Drain did not finish after the notice got the chat")+ }+ if said := noticesOn(t, conn); len(said) != 1 || said[0] != copyFor(DefaultLocale).MediaUnreadable {+ t.Fatalf("notices on the socket = %q, want the one did-not-arrive line", said)+ }+}++// NotifyMediaAbandoned runs on the context the Router gives it, and nothing+// inside may outlive that: not the profile lookup, not the wait for the+// server's acknowledgement. Each is tried alone against a context far shorter+// than its own fallback — two seconds for the lookup, five for the ack — so+// one that ignored the context would run to that fallback.+//+// REVERSE VERIFICATION: derive the lookup's context from context.Background()+// and "a lookup that never answers" takes two seconds; write with sendText+// (context.Background()) and "an ack that never comes" takes five.+func TestTheAbandonNoticeStaysInsideTheContextItIsGiven(t *testing.T) {+ t.Parallel()+ const budget = 300 * time.Millisecond+ msg := mediaMessage(t, "image", map[string]any{"image": map[string]any{"url": "https://cos.example/x", "aeskey": testAESKey}})++ for _, tc := range []struct {+ name string+ languages languageLookup+ ack bool+ // frames is what the socket sees. A stalled lookup spends the whole+ // context, so nothing is left to write with; a missing ack comes after+ // the frame is already out.+ frames int+ }{+ {"a lookup that never answers", stalledLanguages{}, true, 0},+ {"an ack that never comes", fakeLanguages{}, false, 1},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ conn := &recordingConn{}+ sender := newWSSender(conn, testLogger())+ if tc.ack {+ sender = conn.autoAck(sender)+ }+ senders := newSendersRegistry()+ senders.set(uuidOf(1), sender)+ storage := &fakeMediaStorage{}+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders,+ activeInstallation(tc.languages), testLogger()).(*wecomMediaResolver)++ ctx, cancel := context.WithTimeout(context.Background(), budget)+ defer cancel()+ started := time.Now()+ r.NotifyMediaAbandoned(ctx, mediaInstallation(), msg, engine.MediaAbandonment{Cause: context.DeadlineExceeded})+ took := time.Since(started)++ if took >= mediaNoticeLocaleTimeout {+ t.Fatalf("the notice took %s on a %s context: it waited past the context it was given", took, budget)+ }+ conn.mu.Lock()+ frames := len(conn.frames)+ conn.mu.Unlock()+ if frames != tc.frames {+ t.Fatalf("frames written = %d, want %d", frames, tc.frames)+ }+ })+ }+}++// A revoked installation gets no notice. The installation was read when the+// message came in, up to a whole media budget before the notice is written,+// and a person who removed the bot in between is owed nothing more from it.+// Both notices go through the same check: the one ResolveMedia sends about+// its own failures, and the one the Router asks for when its budget runs out.+//+// REVERSE VERIFICATION: drop guardReply from tellTheSender and both cases+// write a frame.+func TestNoMediaNoticeIsWrittenToARevokedInstallation(t *testing.T) {+ t.Parallel()+ expired := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer expired.Close()+ msg := mediaMessage(t, "image", map[string]any{"image": map[string]any{"url": expired.URL, "aeskey": testAESKey}})++ for _, tc := range []struct {+ name string+ notify func(r *wecomMediaResolver)+ }{+ {"its own failure", func(r *wecomMediaResolver) {+ r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()+ }},+ {"the budget's", func(r *wecomMediaResolver) {+ r.NotifyMediaAbandoned(context.Background(), mediaInstallation(), msg, engine.MediaAbandonment{Cause: context.DeadlineExceeded})+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ storage := &fakeMediaStorage{}+ senders, conn := notifierWithLiveSocket(uuidOf(1))+ q := activeInstallation(fakeLanguages{})+ q.revoked = true+ r := NewMediaResolver(storage, newFakeMediaLedger(storage), senders, q, testLogger()).(*wecomMediaResolver)+ r.http = testMediaClient()++ tc.notify(r)++ conn.mu.Lock()+ defer conn.mu.Unlock()+ if len(conn.frames) != 0 {+ t.Fatalf("%d frame(s) written to an installation revoked since the message came in", len(conn.frames))+ }+ })+ }+}diff --git a/server/internal/integrations/wecom/media_stream_test.go b/server/internal/integrations/wecom/media_stream_test.goindex 047fb54977..f53fa282a0 100644--- a/server/internal/integrations/wecom/media_stream_test.go+++ b/server/internal/integrations/wecom/media_stream_test.go@@ -312,6 +312,7 @@ func TestIngestPrefersTheStreamingPathAndUploadsTheRightBytes(t *testing.T) {"file": map[string]any{"url": srv.URL + "/object", "aeskey": keyB64},})out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if storage.streamed != 1 {t.Fatalf("UploadStream was called %d times, want the streaming path taken", storage.streamed)@@ -362,6 +363,7 @@ func TestIngestFallsBackWhenTheBackendCannotStream(t *testing.T) {"file": map[string]any{"url": srv.URL + "/object", "aeskey": keyB64},})out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(out.MediaRefs) != 1 {t.Fatalf("MediaRefs = %d, want the buffered path to have carried it", len(out.MediaRefs))}diff --git a/server/internal/integrations/wecom/media_temp_test.go b/server/internal/integrations/wecom/media_temp_test.goindex 717cc54e61..1e9f3f39fe 100644--- a/server/internal/integrations/wecom/media_temp_test.go+++ b/server/internal/integrations/wecom/media_temp_test.go@@ -174,6 +174,7 @@ func TestIngestFallsBackWhenTempFileUnavailable(t *testing.T) {r := newTestResolver(storage, newFakeMediaLedger(nil), nil)msg := mediaMessage(t, "file", map[string]any{"file": map[string]any{"url": srv.URL, "aeskey": keyB64}})out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ r.notices.Wait()if len(out.MediaRefs) != 1 || requests.Load() != 2 || len(storage.stored()) != 1 || storage.gotFile != nil {t.Fatalf("temp-file failure did not use buffered fallback: refs=%d requests=%d buffered=%d file=%v", len(out.MediaRefs), requests.Load(), len(storage.stored()), storage.gotFile)}diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.goindex b001f83faf..62987aa391 100644--- a/server/internal/integrations/wecom/metrics.go+++ b/server/internal/integrations/wecom/metrics.go@@ -91,6 +91,10 @@ type Metrics interface {// gauge of a backlog read over time, not a balance.RecordStreamOpened()+ // RecordMediaFailure — an attachment that never reached the agent.+ // reason is one of the mediaDrop* constants below.+ RecordMediaFailure(reason string)+// RecordOutboundDelivered — one reply reached the user. It is the// denominator: without it a flat drop counter cannot be told apart from a// quiet day, and "the bot went silent" is exactly the report that cannot@@ -158,6 +162,32 @@ type Metrics interface {RecordRelayShed(kind string)}+// Reasons an attachment did not make it. Fixed set: these are label values and+// the label space has to stay bounded.+const (+ // mediaDropBlockedAddress — the media host resolved somewhere the guard+ // refuses. Either WeCom changed its CDN or somebody is pointing us at an+ // internal address; both want looking at, and they are the two an+ // operator can act on.+ mediaDropBlockedAddress = "blocked_address"+ // mediaDropTooLarge — past the size ceiling. The sender is told, so a+ // sustained rate is a conversation about the ceiling rather than a fault.+ mediaDropTooLarge = "too_large"+ // mediaDropUnreadable — everything else the resolver ran into on its own:+ // an expired url, a decrypt that failed, an upload the object store+ // refused.+ mediaDropUnreadable = "unreadable"+ // mediaDropBudgetExpired — the Router's media budget ran out first: the+ // download never started, was cut off, or finished too late to be bound.+ // A sustained rate says the budget is short for what people send, or the+ // media host is slow; the sender is told either way.+ mediaDropBudgetExpired = "budget_expired"+ // mediaDropShutdown — the server was draining while the attachment was+ // queued or in flight. Expected around a deploy, and kept apart so a+ // deploy does not read as a slow-download incident.+ mediaDropShutdown = "shutdown"+)+// nopMetrics is what the constructor falls back to. A nil sink must never be a// nil-pointer dereference on the read loop.type nopMetrics struct{}@@ -169,6 +199,7 @@ func (nopMetrics) RecordCallbackQueueBlocked() {}func (nopMetrics) RecordStreamOpened() {}func (nopMetrics) RecordStreamFinished() {}func (nopMetrics) RecordStreamFellBack() {}+func (nopMetrics) RecordMediaFailure(string) {}func (nopMetrics) RecordOutboundDelivered() {}func (nopMetrics) RecordOutboundDropped(string) {}func (nopMetrics) RecordOutboundSkipped(string) {}diff --git a/server/internal/integrations/wecom/metrics_test.go b/server/internal/integrations/wecom/metrics_test.goindex 1e0a02d8c0..849bed3b80 100644--- a/server/internal/integrations/wecom/metrics_test.go+++ b/server/internal/integrations/wecom/metrics_test.go@@ -44,14 +44,15 @@ func (m *countingMetrics) get(k string) int {return m.counts[k]}-func (m *countingMetrics) RecordConnectFailure() { m.bump("connect_failure") }-func (m *countingMetrics) RecordAuthFailure() { m.bump("auth_failure") }-func (m *countingMetrics) RecordCallbackQueued() { m.bump("callback_queued") }-func (m *countingMetrics) RecordCallbackQueueBlocked() { m.bump("callback_blocked") }-func (m *countingMetrics) RecordStreamOpened() { m.bump("stream_opened") }-func (m *countingMetrics) RecordStreamFinished() { m.bump("stream_finished") }-func (m *countingMetrics) RecordStreamFellBack() { m.bump("stream_fell_back") }-func (m *countingMetrics) RecordOutboundDelivered() { m.bump("outbound_delivered") }+func (m *countingMetrics) RecordConnectFailure() { m.bump("connect_failure") }+func (m *countingMetrics) RecordAuthFailure() { m.bump("auth_failure") }+func (m *countingMetrics) RecordCallbackQueued() { m.bump("callback_queued") }+func (m *countingMetrics) RecordCallbackQueueBlocked() { m.bump("callback_blocked") }+func (m *countingMetrics) RecordStreamOpened() { m.bump("stream_opened") }+func (m *countingMetrics) RecordStreamFinished() { m.bump("stream_finished") }+func (m *countingMetrics) RecordStreamFellBack() { m.bump("stream_fell_back") }+func (m *countingMetrics) RecordMediaFailure(reason string) { m.bump("media_failure:" + reason) }+func (m *countingMetrics) RecordOutboundDelivered() { m.bump("outbound_delivered") }func (m *countingMetrics) RecordOutboundDropped(reason string) {m.bump("outbound_dropped")m.bump("outbound_dropped:" + reason)diff --git a/server/internal/integrations/wecom/regression_media_budget_silence_test.go b/server/internal/integrations/wecom/regression_media_budget_silence_test.gonew file mode 100644index 0000000000..4820368a19--- /dev/null+++ b/server/internal/integrations/wecom/regression_media_budget_silence_test.go@@ -0,0 +1,217 @@+package wecom++// regression_media_budget_silence_test.go — what a person is owed when the+// photo they sent does not make it.+//+// The adapter already apologises for an attachment the resolver itself failed+// on: a dead COS link, a file over the size cap. But the resolver is not the+// only thing that can give up on an attachment. The engine Router wraps the+// whole ResolveMedia call in a media budget of its own, and when that budget+// runs out the Router drops the attachment references and lets the agent run+// on the "[Image]" placeholder. From the resolver's side nothing failed — it+// was cut off, or it never started — so the notice it owns is never written.+// The photo is gone and the chat says nothing about it: the person watches+// the bot answer the sentence they typed beside the picture as if the picture+// had never existed, and the only place it is recorded is a server log they+// cannot see.+//+// The tests here drive the two calls engine.Router.resolveAndBindMedia makes,+// in its order and with its contexts, against the real resolver over a real+// aibot socket. What they read is what the person reads: the frames on the+// socket.++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++// liveSocketThatAcks is notifierWithLiveSocket with the server's ack wired+// back, so a notice completes at once instead of waiting out the ack timeout.+func liveSocketThatAcks(id pgtype.UUID) (*sendersRegistry, *recordingConn) {+ conn := &recordingConn{}+ reg := newSendersRegistry()+ reg.set(id, conn.autoAck(newWSSender(conn, testLogger())))+ return reg, conn+}++// noticesOn returns the markdown text of every message pushed to the chat.+func noticesOn(t *testing.T, conn *recordingConn) []string {+ t.Helper()+ conn.mu.Lock()+ n := len(conn.frames)+ conn.mu.Unlock()+ out := make([]string, 0, n)+ for i := 0; i < n; i++ {+ body := conn.sendBody(t, i)+ md, ok := body["markdown"].(map[string]any)+ if !ok {+ t.Fatalf("frame %d has no markdown body: %#v", i, body)+ }+ text, _ := md["content"].(string)+ out = append(out, text)+ }+ return out+}++// asTheRouterDoes runs the two calls engine.Router.resolveAndBindMedia makes,+// with what it hands them: resolve under the media budget, and, when that+// budget is gone, tell the resolver it was abandoned, with the refs it is+// dropping, on a FRESH bounded context, because the one that just expired+// cannot carry a message out. It returns once both notices have finished.+//+// deadline in the past is the "never started" case: the Router skips+// ResolveMedia entirely rather than churn through intent writes on a dead+// context, which is exactly why the resolver observes no failure.+func asTheRouterDoes(t *testing.T, r *wecomMediaResolver, deadline time.Time, inst engine.ResolvedInstallation, msg channel.InboundMessage) {+ t.Helper()+ ctx, cancel := context.WithDeadline(context.Background(), deadline)+ resolved, started := msg, false+ if ctx.Err() == nil {+ resolved = r.ResolveMedia(ctx, inst, engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)+ started = true+ }+ budgetErr := ctx.Err()+ cancel()+ if budgetErr == nil {+ t.Fatal("the media budget did not expire; this test says nothing unless it does")+ }+ notifier, ok := engine.MediaResolver(r).(engine.MediaAbandonNotifier)+ if !ok {+ t.Fatal("the wecom resolver does not implement engine.MediaAbandonNotifier, so when the Router's " ++ "media budget expires nothing tells the sender their attachment did not arrive: the bot answers " ++ "the line they typed beside the picture as if there were no picture")+ }+ noticeCtx, noticeCancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer noticeCancel()+ notifier.NotifyMediaAbandoned(noticeCtx, inst, msg, engine.MediaAbandonment{+ Cause: budgetErr, Started: started, Dropped: resolved.MediaRefs,+ })+ r.notices.Wait()+}++// stallingCOS serves a real encrypted payload, but only after hold. It is the+// ordinary shape of a file slower than the budget, not an exotic one.+func stallingCOS(t *testing.T, hold time.Duration, plaintext []byte) *httptest.Server {+ t.Helper()+ ciphertext := encryptLikeWecom(t, testAESKey, plaintext)+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ time.Sleep(hold)+ w.Header().Set("Content-Type", "application/octet-stream")+ _, _ = w.Write(ciphertext)+ }))+}++// TestAPhotoTheMediaBudgetGaveUpOnBeforeItStartedIsNotSilentlyDropped: the+// budget is already spent by the time the job comes up, so the download never+// even starts. The resolver observes no failure because it is never asked to+// do anything — which is exactly why the notice it owns cannot fire, and why+// this has to be told to it from outside.+func TestAPhotoTheMediaBudgetGaveUpOnBeforeItStartedIsNotSilentlyDropped(t *testing.T) {+ t.Parallel()+ cos := cosServer(t, []byte("\x89PNG\r\n\x1a\nthe photo they wanted looked at"), `attachment; filename="chart.png"`)+ defer cos.Close()++ senders, conn := liveSocketThatAcks(uuidOf(1))+ r := newTestResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), senders)+ msg := mediaMessage(t, "image", map[string]any{+ "image": map[string]any{"url": cos.URL, "aeskey": testAESKey},+ })++ // A budget already gone is what a real 45s budget looks like behind a+ // burst of earlier attachments queued on the same session.+ asTheRouterDoes(t, r, time.Now().Add(-time.Millisecond), mediaInstallation(), msg)++ said := noticesOn(t, conn)+ if len(said) == 0 {+ t.Fatal("the photo never reached the chat message and the chat was told nothing about it: " ++ "the person sees the bot answer the line they typed beside the picture as if there were no " ++ "picture, with nothing to tell them to send it again")+ }+ if len(said) != 1 {+ t.Fatalf("the sender got %d notices for one abandoned message: %q", len(said), said)+ }+ if want := copyFor(DefaultLocale).MediaUnreadable; said[0] != want {+ t.Fatalf("the notice reads %q, want the line that tells them to send it again (%q)", said[0], want)+ }+}++// TestAnAttachmentCutOffByTheBudgetIsApologisedForOnce is the overlap: a file+// slower than the budget. The download is cut off mid-flight, so the resolver+// classifies it as unreadable and would say so; then the Router, having given+// up on the same message, says the identical sentence. Two in a row reads as+// the bot glitching rather than as one picture that did not make it.+func TestAnAttachmentCutOffByTheBudgetIsApologisedForOnce(t *testing.T) {+ t.Parallel()+ cos := stallingCOS(t, 400*time.Millisecond, []byte("\x89PNG\r\n\x1a\na slow upload"))+ defer cos.Close()++ senders, conn := liveSocketThatAcks(uuidOf(1))+ r := newTestResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), senders)+ msg := mediaMessage(t, "image", map[string]any{+ "image": map[string]any{"url": cos.URL, "aeskey": testAESKey},+ })++ asTheRouterDoes(t, r, time.Now().Add(80*time.Millisecond), mediaInstallation(), msg)++ said := noticesOn(t, conn)+ if len(said) == 0 {+ t.Fatal("the sender was told nothing at all about a photo that never made it")+ }+ if len(said) > 1 {+ t.Fatalf("the sender got %d notices for one failed attachment: %q — they read the same apology twice in a row", len(said), said)+ }+}++// TestTheVerdictTheSenderCanActOnSurvivesTheBudget is the carve-out. A "too+// big" verdict was reached on its own merits before the clock ran out, and it+// is the one line the sender can do something about (send a smaller file), so+// dropping the repeated line must not drop it too.+func TestTheVerdictTheSenderCanActOnSurvivesTheBudget(t *testing.T) {+ t.Parallel()+ got := withoutNotice([]mediaFailure{mediaFailureUnreadable, mediaFailureTooLarge}, mediaFailureUnreadable)+ if len(got) != 1 || got[0] != mediaFailureTooLarge {+ t.Fatalf("kept %v, want the too-large verdict to survive — it is the only one the sender can act on", got)+ }+ if left := withoutNotice([]mediaFailure{mediaFailureUnreadable}, mediaFailureUnreadable); len(left) != 0 {+ t.Fatalf("kept %v, want nothing: the Router is about to say that line itself", left)+ }+ // A refused address reads to the sender as "it did not arrive", the same+ // sentence the Router repeats, so it has to be dropped by which sentence+ // it would say rather than by which kind it is.+ if left := withoutNotice([]mediaFailure{mediaFailureBlocked}, mediaFailureUnreadable); len(left) != 0 {+ t.Fatalf("kept %v, want nothing: a blocked address says the same sentence the Router repeats", left)+ }+ if kept := withoutNotice([]mediaFailure{mediaFailureTooLarge}, mediaFailureUnreadable); len(kept) != 1 {+ t.Fatalf("kept %v, want the unrelated verdict untouched", kept)+ }+}++// TestAnAbandonedMessageWithNoAttachmentsSaysNothing: the Router's budget+// covers the whole detached path, and a message can reach it having had its+// attachments decoded away. Apologising for a picture nobody sent is its own+// small defect.+func TestAnAbandonedMessageWithNoAttachmentsSaysNothing(t *testing.T) {+ t.Parallel()+ senders, conn := liveSocketThatAcks(uuidOf(1))+ r := newTestResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), senders)+ notifier, ok := engine.MediaResolver(r).(engine.MediaAbandonNotifier)+ if !ok {+ t.Fatal("the wecom resolver does not implement engine.MediaAbandonNotifier")+ }++ notifier.NotifyMediaAbandoned(context.Background(), mediaInstallation(), mediaMessage(t, "text", map[string]any{+ "text": map[string]any{"content": "just a question"},+ }), engine.MediaAbandonment{Cause: context.DeadlineExceeded})++ if said := noticesOn(t, conn); len(said) != 0 {+ t.Fatalf("a message carrying no attachments was apologised for anyway: %q", said)+ }+}diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.goindex 5d426a634e..4beb3569e3 100644--- a/server/internal/integrations/wecom/resolvers_test.go+++ b/server/internal/integrations/wecom/resolvers_test.go@@ -189,7 +189,7 @@ func TestNewResolverSet_WiresAllResolvers(t *testing.T) {// And a configured one must actually reach the Router — this is the// whole wiring, and a resolver built at boot and dropped here would look// exactly like media ingestion never having been written.- media := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, testLogger())+ media := NewMediaResolver(&fakeMediaStorage{}, newFakeMediaLedger(nil), nil, nil, testLogger())withMedia := NewResolverSet(&Store{}, &fakeSessionBinder{}, nil, media)if withMedia.Media == nil {t.Fatal("a media resolver was passed and dropped")diff --git a/server/internal/integrations/wecom/senders_registry.go b/server/internal/integrations/wecom/senders_registry.goindex 894b51d798..1abbcd6bc4 100644--- a/server/internal/integrations/wecom/senders_registry.go+++ b/server/internal/integrations/wecom/senders_registry.go@@ -63,6 +63,13 @@ func (r *sendersRegistry) mx() Metrics {return r.metrics}+// RecordMediaFailure lets the media resolver report through the registry it+// already holds, rather than threading a second sink through a constructor+// that has no other reason to know about metrics.+func (r *sendersRegistry) RecordMediaFailure(reason string) {+ r.mx().RecordMediaFailure(reason)+}+// NewSendersRegistry is the public constructor boot uses to inject the// same registry into both the wecom ChannelDeps (writer side) and the// OutboundReplier (reader side). Kept exported so router.go can wire itdiff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex 9ef4cd3132..1172ada473 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -199,6 +199,12 @@ type copyPack struct {InboxDetailLink stringInboxTypeLabels map[string]stringInboxTypeFallback string+ // MediaTooLarge / MediaUnreadable tell the sender that an attachment did+ // not make it. Two reasons rather than one because the fix differs: a+ // file over the limit needs splitting or a link, whereas an expired or+ // undecryptable download just needs sending again.+ MediaTooLarge string+ MediaUnreadable string// MediaSendFailed / MediaSendUnknown / MediaLookupFailed go the other way:// the agent produced a file and it did not plainly reach the chat. The// answer is already on screen and may well point at the file, so silence@@ -297,6 +303,8 @@ var copyPacks = map[Locale]copyPack{StreamNoReplyWithFiles: "(这轮没有文字回复,附件在下面)",StreamNotStarted: "已收到,但这条暂时没能开始处理。",StreamFailed: "⚠️ 这次没跑通,请稍后再试一次。",+ MediaTooLarge: "抱歉,附件太大了,我这边收不下。",+ MediaUnreadable: "抱歉,有附件没能收到,麻烦重新发一次。",MediaSendFailed: "⚠️ 有文件没能发出来,我这边保留着,需要的话我再试一次。",MediaSendUnknown: "⚠️ 有文件我没收到企业微信的送达回执,可能已经发到了、也可能没有。我不会自动重发,免得发重了;你那边没看到的话说一声,我再发一次。",MediaLookupFailed: "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。",@@ -340,6 +348,8 @@ var copyPacks = map[Locale]copyPack{StreamNoReplyWithFiles: "(no text this round — the files follow)",StreamNotStarted: "Got it, but this one couldn't start processing.",StreamFailed: "⚠️ That run didn't go through. Please try again.",+ MediaTooLarge: "Sorry, that attachment is too big for me to take.",+ MediaUnreadable: "Sorry, an attachment didn't come through — please send it again.",MediaSendFailed: "⚠️ I couldn't send one of the files. It is still here — say the word and I'll try again.",MediaSendUnknown: "⚠️ WeCom never confirmed one of the files, so it may or may not have arrived. I won't resend it automatically in case that shows it twice — tell me if it isn't there and I'll send it again.",MediaLookupFailed: "⚠️ I couldn't check whether this answer had a file with it, so if it did, it didn't go out. Say the word and I'll try again.",diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.goindex 2ddb3f53f7..3c3ebe9187 100644--- a/server/internal/metrics/wecom.go+++ b/server/internal/metrics/wecom.go@@ -19,6 +19,7 @@ type WecomMetrics struct {StreamOpened prometheus.CounterStreamFinished prometheus.CounterStreamFellBack prometheus.Counter+ MediaFailures *prometheus.CounterVecOutboundDelivered prometheus.CounterOutboundDropped *prometheus.CounterVecOutboundSkipped *prometheus.CounterVec@@ -54,6 +55,10 @@ func NewWecomMetrics() *WecomMetrics {"Answers that landed in the bubble the question opened."),StreamFellBack: counter("stream_fell_back_total","Answers sent as a new message because the bubble refused the closing frame. The answer is not lost; the experience is the one the bubble was built to replace."),+ MediaFailures: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: "media_failures_total",+ Help: "Attachments the media resolver took on that never reached the agent, by reason. 'unreadable' is a download, decrypt or upload that failed on its own; 'too_large' is past the size ceiling; 'blocked_address' means the media host resolved somewhere the SSRF guard refuses, which is either WeCom moving its CDN or somebody pointing us inward; 'budget_expired' is the media budget running out before the attachment was bound, whether it never started, was cut off or finished too late; 'shutdown' is the server draining while it was queued or in flight.",+ }, []string{"reason"}),OutboundDelivered: counter("outbound_delivered_total","Agent replies this adapter put in front of a WeCom user. The denominator the drop breakdown is read against."),OutboundDropped: prometheus.NewCounterVec(prometheus.CounterOpts{@@ -92,6 +97,7 @@ func (m *WecomMetrics) Collectors() []prometheus.Collector {m.ConnectFailures, m.AuthFailures,m.CallbacksQueued, m.CallbackQueueBlocked,m.StreamOpened, m.StreamFinished, m.StreamFellBack,+ m.MediaFailures,m.OutboundDelivered, m.OutboundDropped, m.OutboundSkipped,m.AttachmentDelivered, m.AttachmentDropped, m.AttachmentSheds,m.OutboundUnconfirmed, m.AttachmentUnconfirmed,@@ -131,3 +137,6 @@ func (m *WecomMetrics) RecordRelayShed(kind string) {func (m *WecomMetrics) RecordStreamOpened() { m.StreamOpened.Inc() }func (m *WecomMetrics) RecordStreamFinished() { m.StreamFinished.Inc() }func (m *WecomMetrics) RecordStreamFellBack() { m.StreamFellBack.Inc() }+func (m *WecomMetrics) RecordMediaFailure(reason string) {+ m.MediaFailures.WithLabelValues(reason).Inc()+}diff --git a/server/internal/metrics/wecom_test.go b/server/internal/metrics/wecom_test.goindex a4419949b4..034fef4ce1 100644--- a/server/internal/metrics/wecom_test.go+++ b/server/internal/metrics/wecom_test.go@@ -194,3 +194,41 @@ func containsAny(s string, subs ...string) bool {}return false}++// A media failure is registered with the rest and lands under its reason — a+// collector left out of Collectors() would count into a series /metrics never+// shows.+func TestMediaFailuresAreCountedPerReason(t *testing.T) {+ reg := prometheus.NewRegistry()+ m := NewWecomMetrics()+ for _, collector := range m.Collectors() {+ if err := reg.Register(collector); err != nil {+ t.Fatalf("register WeCom collector: %v", err)+ }+ }++ m.RecordMediaFailure("unreadable")+ m.RecordMediaFailure("unreadable")+ m.RecordMediaFailure("blocked_address")++ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather WeCom metrics: %v", err)+ }+ got := map[string]float64{}+ for _, family := range families {+ if family.GetName() != "multica_wecom_media_failures_total" {+ continue+ }+ for _, metric := range family.GetMetric() {+ for _, label := range metric.GetLabel() {+ if label.GetName() == "reason" {+ got[label.GetValue()] = metric.GetCounter().GetValue()+ }+ }+ }+ }+ if got["unreadable"] != 2 || got["blocked_address"] != 1 || len(got) != 2 {+ t.Fatalf("media_failures_total by reason = %v, want unreadable=2 blocked_address=1", got)+ }+}