Skip to content

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

Go

feat(wecom): read the server's verdict on an outbound send (MUL-5887) (#6590)

Xichang(Seacen) Zhao0ab271235651
diff --git a/server/internal/integrations/wecom/dispatch_test.go b/server/internal/integrations/wecom/dispatch_test.go
index d4090d4d91..97818a2471 100644
--- a/server/internal/integrations/wecom/dispatch_test.go
+++ b/server/internal/integrations/wecom/dispatch_test.go
@@ -40,7 +40,7 @@ func TestDispatchFrame_TextReachesHandler(t *testing.T) {
return nil
})
conn := &recordingConn{}
- err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "text", "hello"), newWSSender(conn, nil), slog.Default())
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "text", "hello"), conn.autoAck(newWSSender(conn, nil)), slog.Default())
if err != nil {
t.Fatalf("dispatchFrame: %v", err)
}
@@ -63,7 +63,7 @@ func TestDispatchFrame_NonTextGetsReceiptAndSkipsHandler(t *testing.T) {
return nil
})
conn := &recordingConn{}
- err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "image", ""), newWSSender(conn, nil), slog.Default())
+ err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "image", ""), conn.autoAck(newWSSender(conn, nil)), slog.Default())
if err != nil {
t.Fatalf("dispatchFrame: %v", err)
}
@@ -95,7 +95,7 @@ func TestDispatchFrame_ServerPingIsPonged(t *testing.T) {
t.Parallel()
c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
conn := &recordingConn{}
- err := c.dispatchFrame(context.Background(), frameEnvelope{Cmd: cmdServerPing, Headers: frameHeaders{ReqID: "r1"}}, newWSSender(conn, nil), slog.Default())
+ err := c.dispatchFrame(context.Background(), frameEnvelope{Cmd: cmdServerPing, Headers: frameHeaders{ReqID: "r1"}}, conn.autoAck(newWSSender(conn, nil)), slog.Default())
if err != nil {
t.Fatalf("dispatchFrame: %v", err)
}
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 36026ca774..f6eaa4c201 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -136,7 +136,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return errors.New("wecom: connection not ready on this replica")
}
chatType := aibotChatTypeFromChannel(channel.ChatType(binding.ChatType))
- return sender.sendText(binding.ChannelChatID, chatType, content)
+ return sender.sendTextCtx(ctx, binding.ChannelChatID, chatType, content)
}
// chatDoneContent extracts the reply text from an EventChatDone payload
@@ -228,7 +228,7 @@ func (o *Outbound) tryDeliverInbox(ctx context.Context, item map[string]any, rec
// Smart-bot inbox notifications are 1:1 pushes to the bound user. The
// binding row's channel_user_id is the bot-scoped T-* userid — WeCom
// treats that as the chatid for a single (chat_type=1) send.
- if err := sender.sendText(binding.ChannelUserID, chatTypeSingleInt, content); err != nil {
+ if err := sender.sendTextCtx(ctx, binding.ChannelUserID, chatTypeSingleInt, content); err != nil {
o.logger.WarnContext(ctx, "wecom outbound: inbox push failed",
"error", err, "installation_id", uuidStringPub(binding.InstallationID),
"recipient_id", recipientIDStr)
diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.go
index 7794d6678b..19c64bb69b 100644
--- a/server/internal/integrations/wecom/outbound_test.go
+++ b/server/internal/integrations/wecom/outbound_test.go
@@ -57,7 +57,7 @@ func newOutboundWithConn(t *testing.T, q outboundQueries) (*Outbound, pgtype.UUI
reg := newSendersRegistry()
instID := mustTestUUID(t)
conn := &recordingConn{}
- reg.set(instID, newWSSender(conn, nil))
+ reg.set(instID, conn.autoAck(newWSSender(conn, nil)))
return NewOutbound(q, reg, slog.Default()), instID, conn
}
diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.go
index 75f2441374..be32f6ab26 100644
--- a/server/internal/integrations/wecom/replier.go
+++ b/server/internal/integrations/wecom/replier.go
@@ -170,7 +170,7 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res
// the link privately to the sender's own userid with chat_type=1 (the same
// address outbound.go uses for inbox pushes), never to the room. Lark's
// SendBindingPromptCard targets the sender's OpenID for the same reason.
- if err := r.postPrivate(inst, sender, text); err != nil {
+ if err := r.postPrivate(ctx, inst, sender, text); err != nil {
return err
}
// A group trigger still needs an answer — silence reads as a broken bot —
@@ -186,7 +186,7 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res
// postPrivate delivers text to a single user's 1:1 chat (chat_type=1),
// regardless of which room triggered the message. Used for bearer-credential
// content (the binding link) that must never land in a group.
-func (r *OutboundReplier) postPrivate(inst engine.ResolvedInstallation, userID, text string) error {
+func (r *OutboundReplier) postPrivate(ctx context.Context, inst engine.ResolvedInstallation, userID, text string) error {
if r.senders == nil {
return errors.New("wecom: sender registry not configured")
}
@@ -200,7 +200,7 @@ func (r *OutboundReplier) postPrivate(inst engine.ResolvedInstallation, userID,
if sender == nil {
return errors.New("wecom: connection not ready")
}
- return sender.sendText(userID, chatTypeSingleInt, text)
+ return sender.sendTextCtx(ctx, userID, chatTypeSingleInt, text)
}
// post looks up the installation's live wsSender in the registry and
@@ -208,7 +208,6 @@ func (r *OutboundReplier) postPrivate(inst engine.ResolvedInstallation, userID,
// ready" when the Supervisor has no active connection (mid-reconnect
// after lease flip, or right after Revoke).
func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
- _ = ctx
if r.senders == nil {
return errors.New("wecom: sender registry not configured")
}
@@ -224,7 +223,7 @@ func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstalla
return errors.New("wecom: missing chat_id")
}
chatType := aibotChatTypeFromChannel(msg.Source.ChatType)
- return sender.sendText(chatID, chatType, text)
+ return sender.sendTextCtx(ctx, chatID, chatType, text)
}
func issueCreatedText(res engine.Result) string {
diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.go
index 47b3cab6cd..eeca595be5 100644
--- a/server/internal/integrations/wecom/replier_test.go
+++ b/server/internal/integrations/wecom/replier_test.go
@@ -13,6 +13,7 @@ package wecom
import (
"context"
"encoding/json"
+ "errors"
"strings"
"sync"
"testing"
@@ -44,6 +45,23 @@ func (f fakeBinder) Mint(context.Context, pgtype.UUID, pgtype.UUID, string) (Bin
type recordingConn struct {
mu sync.Mutex
frames []frameEnvelope
+
+ // sender, when set, makes this double answer its writes the way the real
+ // server does: an ack frame echoing the req_id with errcode 0. Senders
+ // that read their verdict block until one arrives, so a double that never
+ // answers turns every send into a 5-second timeout.
+ //
+ // Set refuseCode to make the server refuse instead.
+ sender *wsSender
+ refuseCode int
+ refuseMsg string
+}
+
+// autoAck wires the double to answer the sender's writes. Call it after
+// newWSSender, which needs the conn first.
+func (c *recordingConn) autoAck(s *wsSender) *wsSender {
+ c.sender = s
+ return s
}
func (c *recordingConn) WriteMessage(_ int, data []byte) error {
@@ -53,7 +71,16 @@ func (c *recordingConn) WriteMessage(_ int, data []byte) error {
}
c.mu.Lock()
c.frames = append(c.frames, env)
+ s := c.sender
+ code, msg := c.refuseCode, c.refuseMsg
c.mu.Unlock()
+ if s != nil {
+ s.routeResponse(frameEnvelope{
+ Headers: frameHeaders{ReqID: env.Headers.ReqID},
+ ErrCode: code,
+ ErrMsg: msg,
+ })
+ }
return nil
}
func (c *recordingConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
@@ -81,7 +108,7 @@ func newReplierWithConn(t *testing.T) (*OutboundReplier, engine.ResolvedInstalla
reg := newSendersRegistry()
inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
conn := &recordingConn{}
- reg.set(inst.ID, newWSSender(conn, nil))
+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))
r := NewOutboundReplier(OutboundReplierConfig{Senders: reg, AppURL: "https://multica.example"})
return r, inst, conn
}
@@ -92,7 +119,7 @@ func TestPostPrivate_AddressesUserWithSingleChatType(t *testing.T) {
const senderUserID = "SENDER_USERID"
const secretURL = "https://multica.example/wecom/bind?token=SECRET_TOKEN"
- if err := r.postPrivate(inst, senderUserID, secretURL); err != nil {
+ if err := r.postPrivate(context.Background(), inst, senderUserID, secretURL); err != nil {
t.Fatalf("postPrivate: %v", err)
}
@@ -118,7 +145,7 @@ func TestPost_AddressesRoomChatID(t *testing.T) {
ChatType: channel.ChatTypeGroup,
SenderID: "SENDER_USERID",
}}
- if err := r.post(nil, inst, msg, "a token-less line"); err != nil {
+ if err := r.post(context.Background(), inst, msg, "a token-less line"); err != nil {
t.Fatalf("post: %v", err)
}
@@ -145,7 +172,7 @@ func TestSendBindingPrompt_GroupNeverLeaksToken(t *testing.T) {
reg := newSendersRegistry()
inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
conn := &recordingConn{}
- reg.set(inst.ID, newWSSender(conn, nil))
+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))
r := NewOutboundReplier(OutboundReplierConfig{
Binding: nil, // set the interface field directly with the fake below
Senders: reg,
@@ -217,7 +244,7 @@ func TestSendBindingPrompt_P2PSendsOnlyPrivately(t *testing.T) {
reg := newSendersRegistry()
inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
conn := &recordingConn{}
- reg.set(inst.ID, newWSSender(conn, nil))
+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))
r := NewOutboundReplier(OutboundReplierConfig{Senders: reg, AppURL: "https://multica.example"})
r.binding = fakeBinder{raw: rawToken}
@@ -251,7 +278,7 @@ func TestSendBindingPrompt_ThrottledSendsNoURL(t *testing.T) {
reg := newSendersRegistry()
inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
conn := &recordingConn{}
- reg.set(inst.ID, newWSSender(conn, nil))
+ reg.set(inst.ID, conn.autoAck(newWSSender(conn, nil)))
r := NewOutboundReplier(OutboundReplierConfig{
Senders: reg,
AppURL: "https://multica.example",
@@ -301,3 +328,40 @@ func TestSendBindingPrompt_ThrottledSendsNoURL(t *testing.T) {
t.Errorf("expected exactly one privately-addressed frame, got %d", privateFrames)
}
}
+
+// TestPost_HonoursTheCallersDeadline guards the budget the calling code
+// already believed it had. Bus delivery is synchronous, so the reply path runs
+// on the publishing goroutine; outbound.go and handleInboxNew each build a
+// bounded ctx precisely so a stalled WeCom round trip cannot hold it. Waiting
+// for the server's verdict on a hardcoded context.Background() made those
+// bounds decorative — a lost ack cost the full ackTimeout per subscriber, in
+// series, on an HTTP handler's goroutine.
+//
+// A ctx that is already done is the cheap, deterministic stand-in: it must come
+// back at once rather than serve out the ack wait.
+func TestPost_HonoursTheCallersDeadline(t *testing.T) {
+ t.Parallel()
+ r, inst, _ := newReplierWithConn(t)
+
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "GROUP_CHAT_ID",
+ ChatType: channel.ChatTypeGroup,
+ SenderID: "SENDER_USERID",
+ }}
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ done := make(chan error, 1)
+ go func() { done <- r.post(ctx, inst, msg, "a line nobody is waiting for") }()
+
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("post on a cancelled ctx returned %v, want context.Canceled", err)
+ }
+ case <-time.After(ackTimeout / 2):
+ t.Fatal("post ignored the caller's cancelled ctx and sat on the ack wait — " +
+ "the deadline the publishing goroutine budgeted for is not being applied")
+ }
+}
diff --git a/server/internal/integrations/wecom/send_verdict_test.go b/server/internal/integrations/wecom/send_verdict_test.go
new file mode 100644
index 0000000000..6dbd7e0bc0
--- /dev/null
+++ b/server/internal/integrations/wecom/send_verdict_test.go
@@ -0,0 +1,61 @@
+package wecom
+
+// send_verdict_test.go — a push used to return nil as soon as the bytes left
+// the process. WeCom's answer comes back in a separate ack frame, so a frame
+// the server refused was indistinguishable from one it accepted.
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestSendTextReportsAServerRefusal(t *testing.T) {
+ conn := &recordingConn{refuseCode: 45009, refuseMsg: "rate limit"}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ err := sender.sendText("CHAT", chatTypeSingleInt, "hello")
+ if err == nil {
+ t.Fatal("a send WeCom refused reported success — the caller records a delivery that never happened")
+ }
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("error is not a *wecomAPIError, so a caller cannot tell a permanent refusal from a transient one: %v", err)
+ }
+ if apiErr.Code != 45009 {
+ t.Errorf("errcode = %d, want 45009", apiErr.Code)
+ }
+ if apiErr.Cmd != cmdSendMsg {
+ t.Errorf("cmd = %q, want %q", apiErr.Cmd, cmdSendMsg)
+ }
+}
+
+func TestSendTextSucceedsOnAZeroErrcode(t *testing.T) {
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ if err := sender.sendText("CHAT", chatTypeSingleInt, "hello"); err != nil {
+ t.Fatalf("an accepted send reported failure: %v", err)
+ }
+ conn.mu.Lock()
+ n := len(conn.frames)
+ conn.mu.Unlock()
+ if n != 1 {
+ t.Fatalf("wrote %d frames, want 1", n)
+ }
+}
+
+// A verdict that never arrives must not be reported as a refusal: the message
+// may well have been delivered, so the two call for opposite responses.
+func TestSendTextDistinguishesALostAckFromARefusal(t *testing.T) {
+ conn := &recordingConn{} // no autoAck: nothing ever answers
+ sender := newWSSender(conn, nil)
+
+ err := sender.sendText("CHAT", chatTypeSingleInt, "hello")
+ if !errors.Is(err, errAckTimeout) {
+ t.Fatalf("a lost ack reported as %v, want errAckTimeout", err)
+ }
+ var apiErr *wecomAPIError
+ if errors.As(err, &apiErr) {
+ t.Error("a lost ack was reported as a server refusal")
+ }
+}
diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.go
index 61e9953920..3691c05772 100644
--- a/server/internal/integrations/wecom/wecom_channel.go
+++ b/server/internal/integrations/wecom/wecom_channel.go
@@ -102,7 +102,7 @@ func (c *wecomChannel) Disconnect(ctx context.Context) error { return nil }
// goroutine to observe it, so a transient failure tears the live connection
// down before the Supervisor reconnects — no leaked socket goroutine
// consuming events into an unread channel.
-func (c *wecomChannel) Connect(ctx context.Context) error {
+func (c *wecomChannel) Connect(ctx context.Context) (err error) {
if c.handler == nil {
return errors.New("wecom: inbound handler not configured")
}
@@ -190,14 +190,75 @@ func (c *wecomChannel) Connect(ctx context.Context) error {
<-pingDone
}()
+ // Inbound callbacks run on their own worker, not on the read loop. The
+ // read loop is the sole deliverer of server verdicts, so anything that
+ // handles a callback inline cannot also wait for the ack of a frame it
+ // writes — it would be waiting on itself. DingTalk's adapter is already
+ // shaped this way.
+ //
+ // ONE worker, not a pool: WeCom delivers a chat's messages in order, and
+ // the engine's dedup and turn batching assume that order survives.
+ //
+ // A full queue BLOCKS the read loop rather than dropping. Backpressure
+ // costs a reconnect; dropping costs a user's message with nothing to say
+ // so. That only holds while somebody is still receiving, so the read
+ // loop's send also watches cbDone — see the send site below.
+ callbacks := make(chan frameEnvelope, callbackQueueDepth)
+ cbDone := make(chan struct{})
+ var cbErr error
+ go func() {
+ defer close(cbDone)
+ for env := range callbacks {
+ if e := c.dispatchFrame(ctx, env, sender, log); e != nil {
+ cbErr = e
+ // Wake the read loop if it is parked in ReadMessage; a
+ // cancelled context alone will not move it. A read loop
+ // parked on the queue send is woken by cbDone instead —
+ // closing a socket does not move a channel send.
+ _ = conn.Close()
+ return
+ }
+ }
+ }()
+ defer func() {
+ close(callbacks)
+ <-cbDone
+ // The worker's error is the real cause; the read error that followed
+ // it is just the socket we closed to get here. Only on a live ctx: a
+ // shutdown or a lease-loss cancel that catches a callback mid-flight
+ // is an ordinary stop, and promoting that callback's error would
+ // report a spurious "connection exited with error".
+ if cbErr != nil && ctx.Err() == nil {
+ err = cbErr
+ }
+ }()
+
// Read loop. Every frame comes back through the same decode → dispatch
// → (maybe) reply path. A single bad frame does NOT tear the socket
// down — only transport / handler errors escalate.
- _ = conn.SetReadDeadline(time.Now().Add(readDeadline))
for {
if ctx.Err() != nil {
return nil
}
+ // Armed immediately before the read, and nowhere else.
+ //
+ // It used to be armed after ReadMessage returned, which put
+ // everything the loop then did inside the window. Only the server's
+ // pong resets the deadline on a quiet bot and our ping goes out every
+ // 30s, so on a loaded pool the next read could time out on a socket
+ // that was perfectly healthy. The idle window should measure idleness.
+ //
+ // The error is no longer discarded: a socket that refuses a deadline
+ // is not one to keep reading from.
+ if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
+ // The shutdown path closes the socket, and a closed socket
+ // refuses a deadline. That is an ordinary stop, not a failure to
+ // report to the Supervisor.
+ if ctx.Err() != nil {
+ return nil
+ }
+ return fmt.Errorf("wecom: set read deadline: %w", err)
+ }
typ, payload, err := conn.ReadMessage()
if err != nil {
if ctx.Err() != nil {
@@ -205,7 +266,6 @@ func (c *wecomChannel) Connect(ctx context.Context) error {
}
return fmt.Errorf("wecom: read: %w", err)
}
- _ = conn.SetReadDeadline(time.Now().Add(readDeadline))
if typ != websocket.TextMessage && typ != websocket.BinaryMessage {
continue
}
@@ -215,12 +275,43 @@ func (c *wecomChannel) Connect(ctx context.Context) error {
log.Warn("wecom: bad frame envelope", "error", err, "size", len(payload))
continue
}
- if err := c.dispatchFrame(ctx, env, sender, log); err != nil {
- return err
+ switch env.Cmd {
+ case cmdMsgCallback, cmdEventCallback:
+ select {
+ case callbacks <- env:
+ case <-cbDone:
+ // The worker has stopped, so this send has no receiver — and
+ // no closer either: the queue is closed by a defer that
+ // cannot run until this loop returns. With a full queue that
+ // is a permanent park, because the worker's conn.Close()
+ // wakes a read loop sitting in ReadMessage, not one sitting
+ // on a send, and ctx stays live on this path. Nothing would
+ // ever reconnect: the Supervisor would keep renewing the
+ // lease for a connection that had stopped reading.
+ //
+ // Return and let the deferred handler substitute the
+ // worker's error, which is the real cause.
+ return nil
+ case <-ctx.Done():
+ return nil
+ }
+ default:
+ // Acks, pings and pongs stay on the read loop: they are the
+ // frames the worker's own writes are waiting for.
+ if err := c.dispatchFrame(ctx, env, sender, log); err != nil {
+ return err
+ }
}
}
}
+// callbackQueueDepth is how far the callback worker may fall behind the read
+// loop before the read loop blocks. Past this the socket stops being drained,
+// WeCom notices, and the connection is replaced — which is the correct
+// outcome: a replica that cannot keep up should hand the bot to one that can,
+// not quietly discard the messages it could not reach.
+const callbackQueueDepth = 64
+
// subscribe sends the aibot_subscribe frame and waits (up to
// subscribeTimeout) for the server's ack. The ack shape is a frame with
// echoed headers.req_id + errcode; errcode == 0 means good, anything else
@@ -330,6 +421,12 @@ func (c *wecomChannel) dispatchFrame(ctx context.Context, env frameEnvelope, sen
// (e.g. wrong msgtype, rate limit, chat not writable). Log the
// error so a failed outbound is visible without having to
// packet-capture the socket.
+ // Hand it to whoever wrote the frame, if anybody is waiting. An
+ // unclaimed ack is not an error — the pushes that do not wait for a
+ // verdict share this connection.
+ if sender.routeResponse(env) {
+ return nil
+ }
if env.ErrCode != 0 {
log.Warn("wecom: server ack error",
"errcode", env.ErrCode,
diff --git a/server/internal/integrations/wecom/wecom_channel_test.go b/server/internal/integrations/wecom/wecom_channel_test.go
index ca7bfbcd96..90b6da07ac 100644
--- a/server/internal/integrations/wecom/wecom_channel_test.go
+++ b/server/internal/integrations/wecom/wecom_channel_test.go
@@ -15,6 +15,7 @@ import (
"errors"
"net/http"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -191,3 +192,149 @@ func mustTestUUID(t *testing.T) pgtype.UUID {
}
return u
}
+
+// floodConn acks subscribe, hands out a fixed run of msg_callback frames
+// back-to-back, then blocks until Close. It reports (via delivered) the moment
+// the last frame has left it, which is the moment the read loop is committed
+// to a send the dead worker can no longer receive.
+type floodConn struct {
+ mu sync.Mutex
+ ack []byte
+ acked bool
+ frames [][]byte
+ sent int
+ delivered chan struct{}
+ unblock chan struct{}
+ closeOne sync.Once
+}
+
+func (c *floodConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err == nil && env.Cmd == cmdSubscribe {
+ c.mu.Lock()
+ c.ack, _ = json.Marshal(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}})
+ c.mu.Unlock()
+ }
+ return nil
+}
+
+func (c *floodConn) ReadMessage() (int, []byte, error) {
+ c.mu.Lock()
+ if !c.acked && c.ack != nil {
+ c.acked = true
+ ack := c.ack
+ c.mu.Unlock()
+ return websocket.TextMessage, ack, nil
+ }
+ if c.sent < len(c.frames) {
+ f := c.frames[c.sent]
+ c.sent++
+ last := c.sent == len(c.frames)
+ c.mu.Unlock()
+ if last {
+ close(c.delivered)
+ }
+ return websocket.TextMessage, f, nil
+ }
+ c.mu.Unlock()
+ <-c.unblock
+ return 0, nil, errors.New("closed")
+}
+
+func (c *floodConn) SetReadDeadline(time.Time) error { return nil }
+func (c *floodConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *floodConn) Close() error {
+ c.closeOne.Do(func() { close(c.unblock) })
+ return nil
+}
+
+// TestConnectReturnsWhenCallbackWorkerDiesWithAFullQueue drives the one
+// arrangement in which the callback hand-off has no receiver and no closer:
+// the worker returns on its first dispatch error while the read loop is parked
+// on a send into a full queue.
+//
+// The worker closes the socket on its way out, which wakes a read loop parked
+// in ReadMessage — but a parked channel send is not a read, and closing a
+// socket does not move it. Nothing else closes the queue either: that happens
+// in a defer that cannot run until the read loop returns. Only ctx
+// cancellation would break the cycle, and on this path ctx is live: the
+// Supervisor holds the lease open and reports the installation connected, so
+// the bot stops answering that installation until the process restarts.
+//
+// The frame count is deliberate: the worker holds one frame while its handler
+// blocks, callbackQueueDepth more fill the buffer, and the next send is the
+// one with nowhere to go.
+func TestConnectReturnsWhenCallbackWorkerDiesWithAFullQueue(t *testing.T) {
+ t.Parallel()
+
+ frames := make([][]byte, 0, callbackQueueDepth+2)
+ for i := 0; i < callbackQueueDepth+2; i++ {
+ payload, err := json.Marshal(msgCallbackFrame(t, "text", "hello"))
+ if err != nil {
+ t.Fatalf("marshal frame: %v", err)
+ }
+ frames = append(frames, payload)
+ }
+
+ conn := &floodConn{
+ frames: frames,
+ delivered: make(chan struct{}),
+ unblock: make(chan struct{}),
+ }
+
+ // The first callback's handler parks until the queue behind it is full,
+ // then fails. Every later one would succeed — they never get the chance,
+ // which is the point.
+ var calls atomic.Int32
+ firstIn := make(chan struct{})
+ release := make(chan struct{})
+ wantErr := errors.New("handler failed")
+
+ c := &wecomChannel{
+ installationID: mustTestUUID(t),
+ botID: "bot-1",
+ secret: "secret-1",
+ handler: func(context.Context, channel.InboundMessage) error {
+ if calls.Add(1) == 1 {
+ close(firstIn)
+ <-release
+ return wantErr
+ }
+ return nil
+ },
+ dialer: scriptedDialer{conn: conn},
+ wsURL: "wss://example.test/ws",
+ senders: newSendersRegistry(),
+ }
+
+ // Cancelling at the end releases a Connect this test proved is stuck, so a
+ // failure here does not also strand a goroutine for the rest of the run.
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ errCh := make(chan error, 1)
+ go func() { errCh <- c.Connect(ctx) }()
+
+ select {
+ case <-firstIn:
+ case <-time.After(3 * time.Second):
+ t.Fatal("the first callback never reached the handler; the worker is not running")
+ }
+ select {
+ case <-conn.delivered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("the read loop never took every frame, so the queue never filled and this test proves nothing")
+ }
+
+ close(release) // the worker's dispatch now fails and it returns
+
+ select {
+ case err := <-errCh:
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("Connect returned %v, want the dispatch error %v", err, wantErr)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("Connect did not return within 3s after the callback worker died with a full queue — " +
+ "the read loop is parked on a send with no receiver and no close, and only ctx cancellation can free it")
+ }
+}
diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.go
index ea493f0a0c..4d07553caa 100644
--- a/server/internal/integrations/wecom/ws_sender.go
+++ b/server/internal/integrations/wecom/ws_sender.go
@@ -8,6 +8,7 @@ package wecom
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"net/http"
@@ -69,13 +70,148 @@ type wsSender struct {
conn wsConn
mu sync.Mutex
log *slog.Logger
+
+ // replies holds the callers waiting on a server verdict, keyed by the
+ // req_id they wrote. Only the read loop delivers into these, which is why
+ // inbound callbacks must not run on it — see the note on sendTextCtx.
+ ackMu sync.Mutex
+ replies map[string]*replyWaiter
}
func newWSSender(conn wsConn, log *slog.Logger) *wsSender {
if log == nil {
log = slog.Default()
}
- return &wsSender{conn: conn, log: log}
+ return &wsSender{conn: conn, log: log, replies: make(map[string]*replyWaiter)}
+}
+
+// ackTimeout caps the wait for a verdict. WeCom answers in a few hundred
+// milliseconds; past this we assume the ack was lost rather than the frame
+// refused, which matters because the two call for opposite responses.
+const ackTimeout = 5 * time.Second
+
+// errAckTimeout — the frame went out and no verdict came back. Distinct from a
+// refusal: the message may well have been delivered, so a caller retries at
+// its own risk rather than reporting failure.
+var errAckTimeout = errors.New("wecom: timed out waiting for the server verdict")
+
+// wecomAPIError is a refusal the server stated. Carrying the errcode rather
+// than a string is what lets a caller tell a permanent refusal (bad frame,
+// bot removed from the chat) from a transient one (rate limited) instead of
+// pattern-matching prose.
+type wecomAPIError struct {
+ Cmd string
+ Code int
+ Msg string
+}
+
+func (e *wecomAPIError) Error() string {
+ return fmt.Sprintf("wecom: %s rejected errcode=%d errmsg=%s", e.Cmd, e.Code, e.Msg)
+}
+
+// replyWaiter is one caller parked on one req_id.
+type replyWaiter struct{ ch chan replyResult }
+
+// replyResult is a server answer. body is nil for the acks that carry nothing
+// but a verdict.
+type replyResult struct {
+ code int
+ msg string
+ body json.RawMessage
+}
+
+// routeResponse hands a server response to whoever is waiting for it and
+// reports whether anybody was. The read loop calls it for every frame that
+// answers one of our writes; an unclaimed ack is not an error, since the
+// pushes that do not wait share this connection.
+func (s *wsSender) routeResponse(env frameEnvelope) bool {
+ return s.deliverReply(env)
+}
+
+// awaitReply registers interest in the response for the frame about to be
+// written. false means the req_id is already spoken for — with minted ids
+// that is a collision we would rather fail on than silently cross wires.
+func (s *wsSender) awaitReply(reqID string) (*replyWaiter, bool) {
+ s.ackMu.Lock()
+ defer s.ackMu.Unlock()
+ if _, taken := s.replies[reqID]; taken {
+ return nil, false
+ }
+ w := &replyWaiter{ch: make(chan replyResult, 1)}
+ s.replies[reqID] = w
+ return w, true
+}
+
+// cancelReply retires a waiter. Called on every exit path including the happy
+// one — a request is one frame and one answer, so the entry is never useful
+// twice, and leaving it would leak an entry per send.
+func (s *wsSender) cancelReply(reqID string, w *replyWaiter) {
+ s.ackMu.Lock()
+ defer s.ackMu.Unlock()
+ if cur, ok := s.replies[reqID]; ok && cur == w {
+ delete(s.replies, reqID)
+ }
+}
+
+// deliverReply hands a response to the request that asked for it, if there is
+// one, and reports whether it was taken.
+func (s *wsSender) deliverReply(env frameEnvelope) bool {
+ if env.Headers.ReqID == "" {
+ return false
+ }
+ s.ackMu.Lock()
+ w, ok := s.replies[env.Headers.ReqID]
+ if ok {
+ delete(s.replies, env.Headers.ReqID)
+ }
+ s.ackMu.Unlock()
+ if !ok {
+ return false
+ }
+ // Buffered channel, and the entry is removed above, so this never blocks
+ // and never delivers twice.
+ select {
+ case w.ch <- replyResult{code: env.ErrCode, msg: env.ErrMsg, body: env.Body}:
+ default:
+ }
+ return true
+}
+
+// request writes one frame under a req_id of our own and waits for the whole
+// answer. A non-nil error is either a *wecomAPIError carrying the server's
+// errcode, errAckTimeout, or a transport failure.
+func (s *wsSender) request(ctx context.Context, cmd string, body map[string]any) (json.RawMessage, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ reqID := newReqID()
+ w, ok := s.awaitReply(reqID)
+ if !ok {
+ return nil, fmt.Errorf("wecom: %s req_id %s is already awaiting a response", cmd, reqID)
+ }
+ defer s.cancelReply(reqID, w)
+
+ if err := s.write(map[string]any{
+ "cmd": cmd,
+ "headers": frameHeaders{ReqID: reqID},
+ "body": body,
+ }); err != nil {
+ return nil, err
+ }
+
+ timer := time.NewTimer(ackTimeout)
+ defer timer.Stop()
+ select {
+ case res := <-w.ch:
+ if res.code != 0 {
+ return nil, &wecomAPIError{Cmd: cmd, Code: res.code, Msg: res.msg}
+ }
+ return res.body, nil
+ case <-timer.C:
+ return nil, errAckTimeout
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
}
// write marshals frame to JSON and pushes it under the writer mutex. The
@@ -99,13 +235,23 @@ func (s *wsSender) write(frame map[string]any) error {
// (1=single, 2=group) is decided at the wecom-side boundary, not the
// engine's. Used by OutboundReplier and Outbound.
func (s *wsSender) sendText(chatID string, chatTypeInt int, content string) error {
+ return s.sendTextCtx(context.Background(), chatID, chatTypeInt, content)
+}
+
+// sendTextCtx is sendText that reads the server's verdict. Before this, a push
+// was fire-and-forget: a frame WeCom refused — over the size cap, addressed to
+// a chat the bot is no longer in, rate limited — returned nil, so the caller
+// recorded a delivery that never happened and the operator saw only
+// unattributed ack lines go past.
+//
+// Safe to block here only because inbound callbacks no longer run on the read
+// loop (wecom_channel.go): the read loop is the sole deliverer of acks, so a
+// send that waited for one from inside a callback would have waited on itself.
+func (s *wsSender) sendTextCtx(ctx context.Context, chatID string, chatTypeInt int, content string) error {
body, err := sendMsgTextBody(chatID, chatTypeInt, content)
if err != nil {
return err
}
- return s.write(map[string]any{
- "cmd": cmdSendMsg,
- "headers": frameHeaders{ReqID: newReqID()},
- "body": body,
- })
+ _, err = s.request(ctx, cmdSendMsg, body)
+ return err
}