Skip to content

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

Go

MUL-7314 fix(wecom): pace outbound pushes at WeCom's published rate, retry one throttle, best effort past it (#8345)

Xichang(Seacen) Zhaod3e0bae12bb9
diff --git a/server/internal/integrations/wecom/media_upload.go b/server/internal/integrations/wecom/media_upload.go
index 035d56caf7..2a2d47506d 100644
--- a/server/internal/integrations/wecom/media_upload.go
+++ b/server/internal/integrations/wecom/media_upload.go
@@ -325,7 +325,14 @@ func (s *wsSender) sendMedia(ctx context.Context, chatID string, chatType int, m
if err != nil {
return err
}
- if _, err := s.request(ctx, cmdSendMsg, body); err != nil {
+ // Through sendMsgFrame: a file and a piece of an answer are the same
+ // aibot_send_msg to WeCom and spend the same per-chat allowance, so a turn
+ // that answers in words and then sends three attachments has to count as
+ // four (rate_limit.go). The retry that comes with it is safe on this route
+ // for the reason spelled out below — a STATED refusal is the server saying
+ // it did not act on the frame, which is the one failure that cannot leave
+ // a copy of the file behind.
+ if err := s.sendMsgFrame(ctx, chatID, body); err != nil {
// A verdict that never came is not a refusal. The frame went out, and
// the read loop can simply have been busy. Resending on that would put
// the SAME media_id out a second time and the person sees the picture
diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.go
index 28b268e0b0..4b3d930755 100644
--- a/server/internal/integrations/wecom/outbound_media.go
+++ b/server/internal/integrations/wecom/outbound_media.go
@@ -475,13 +475,13 @@ func (o *Outbound) sendAttachment(ctx context.Context, sender *wsSender, row db.
// reader has. Only what fails before the write — a marshal error, a deadline
// the connection refused — is provably undelivered.
//
-// A context error lands on the same side, and less precisely than one would
-// like. wsSender.request returns the same ctx.Err() whether the context ended
-// before the frame was written or while waiting for its verdict, so from out
-// here the two cannot be told apart. Reading all of these as unknown is the
-// direction that costs least: an unknown is never resent and is described in
-// words that hold either way, so a send that never happened is under-claimed
-// rather than a send that did happen being denied.
+// A context error lands on the same side. One of the two request can raise
+// says so itself — errAckAbandoned, the frame written and the wait for its
+// verdict cut short — and the other, raised before any byte left, is read as
+// unknown anyway. That is the direction that costs least here: an unknown is
+// never resent and is described to the user in words that hold either way, so
+// a send that never happened is under-claimed rather than a send that did
+// happen being denied.
func sendOutcome(err error) deliveryState {
switch {
case err == nil:
diff --git a/server/internal/integrations/wecom/rate_limit.go b/server/internal/integrations/wecom/rate_limit.go
new file mode 100644
index 0000000000..6aa3a9202e
--- /dev/null
+++ b/server/internal/integrations/wecom/rate_limit.go
@@ -0,0 +1,482 @@
+package wecom
+
+// rate_limit.go — everything that keeps aibot_send_msg near WeCom's published
+// quota: a per-chat gate in front of the write, and one jittered retry for the
+// two errcodes that mean "not now" rather than "never".
+//
+// WHAT THIS DELIVERS, AND WHAT IT DOES NOT. A conversation that stays under 30
+// pushes a minute is untouched. One that goes a little over is DELAYED into
+// the next free slot rather than refused — reserve waits, inside a budget. One
+// that bursts far over is refused HERE, before the write: the 31st frame of a
+// burst is not delayed, it is turned away with a definite error and nothing on
+// the wire. Making that burst deliverable is not something this file can do;
+// that needs somewhere to keep the frame until the window moves, and this tree
+// has no such place since the outbound queue was retired.
+//
+// Refusing on our own side is still the improvement, because of what it
+// replaces. Without the gate the same burst goes to WeCom and comes back as
+// errcode 45009: ws_sender turns that into a *wecomAPIError, and every caller
+// on the outbound path reads a stated refusal as final — provablyNotSent says
+// no re-offer, classifyDrop files platform_refused, and the reply is gone. One
+// throttled frame is one answer the person never sees, with nothing on their
+// screen to say so. Our own refusal costs nothing on the platform side, spends
+// none of the chat's allowance, and stays provably unsent so the relay can
+// offer it elsewhere.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ mathrand "math/rand/v2"
+ "sort"
+ "sync"
+ "time"
+)
+
+// WeCom's published quota for messages into one CONVERSATION: 30 per minute,
+// 1000 per hour. The aibot page states it twice, once under aibot_respond_msg
+// and once under aibot_send_msg, in the same sentence both times — "无论是回复
+// 还是主动推送消息,总共给某个会话发消息的限制为 30 条/分钟,1000 条/小时"
+// (developer.work.weixin.qq.com/document/path/101463). Over-quota comes back
+// as errcode 45009, "接口调用超过限制" (.../path/90313).
+//
+// Two things follow from that sentence, and the gate is built on both. The
+// unit is the conversation, not the member, which is why the windows below are
+// keyed on chat id — in a group the whole room shares one allowance. And
+// replies and pushes draw on the SAME allowance, so a deployment that also
+// answers in-window is spending from this budget too.
+//
+// These are the documented ceilings THEMSELVES, not a margin under them, and
+// the comment does not claim otherwise. The retry below is what covers the
+// case where the real ceiling turns out to be lower or counted over some other
+// unit: a refusal gets a second chance instead of costing an answer.
+const (
+ rateLimitPerMinute = 30
+ rateLimitPerHour = 1000
+)
+
+// rateWaitBudget caps how long the gate holds a caller waiting for a slot.
+// The cap is not the whole answer: reserve also keeps its hands off the
+// write's own budget, so the wait that actually happens is
+// min(rateWaitBudget, deadline − ackTimeout).
+//
+// It has to work that way because the callers do not share one deadline. A
+// reply gets ten seconds for the whole delivery (outbound.go:155), an inbox
+// push gets five (outbound.go:415), an attachment gets five minutes
+// (outbound_media.go:83). Three seconds out of ten leaves a write seven; three
+// out of five leaves it two, and the ack alone is allowed five
+// (ws_sender.go:111). That write gets cut off mid-flight and request returns a
+// context error — "we may have written and cannot tell", which unconfirmedReason
+// has to file as unknown and an operator resolves by resending something the
+// person may already have. So on the five-second path the gate does not wait
+// at all; it refuses, and refusing is the honest failure because nothing was
+// written and the caller still has its whole budget to record that.
+const rateWaitBudget = 3 * time.Second
+
+// errRateLimited — this process's own gate declined to write, because the
+// chat's quota is spent and a slot will not free up inside the caller's
+// budget. Nothing reached the wire.
+//
+// Deliberately not a wrapped context error, even when it is a caller's
+// deadline that ended the wait. A context error on this path means "we may
+// have written and cannot tell" (unconfirmedReason), which is the opposite of
+// what happened here: the gate is upstream of the socket, so this is provably
+// nothing sent, and provablyNotSent's default answers it correctly. It lands
+// on transport_error, whose reason text already covers "this delivery's own
+// budget ran out before it got a turn on the wire".
+//
+// That default is also what makes one asymmetry worth knowing, and it is the
+// relay's rather than this file's. A frame that reaches the socket THROUGH the
+// relay is handed back to the scheduler when provablyNotSent says nothing was
+// written (relay_outbound.go:1276), so a refusal here costs it a retry chain
+// of roughly one and a half LeaseSettle and no more. The same frame produced
+// on the replica that already holds the lease never goes near that chain:
+// sendTextCtx returns the refusal to its caller and outbound.go files a drop
+// (outbound.go:162). So the relayed copy gets a second chance the direct one
+// does not. Giving the direct path a bounded re-offer of its own is a change
+// to the outbound path rather than to the gate, and is deliberately not here.
+var errRateLimited = errors.New("wecom: this chat's outbound quota is spent")
+
+// WeCom errcodes that mean the frame was refused for a reason that passes.
+// Both are throttles rather than verdicts on the content: the same bytes are
+// accepted once the window moves. Named the same way the connect path already
+// names them (wecom_channel.go, credential_probe.go), where they are likewise
+// treated as "come back later" and not as a rejection.
+const (
+ errCodeAPIFreqLimit = 45009 // api freq out of limit
+ errCodeAPIConcurrencyLimit = 45033 // api concurrency out of limit
+)
+
+// sendRetryBackoff is the base delay before a throttled frame's one retry.
+//
+// One cheap attempt at a refusal that may be momentary. NOT a wait for a slot:
+// this gate is a sliding count, so the next slot frees when the window's
+// oldest entry ages out of it, which for a burst is most of a whole window —
+// admit will happily report 59.999s. Waiting for a slot is what reserve is
+// for, and deriving a fixed delay from "30 a minute is one every two seconds"
+// would be reading an average off a limit that is deliberately not one.
+//
+// Two seconds is sized for 45033, the concurrency refusal, whose documented
+// remedy is exactly this and nothing more: "企业微信出于系统保护的考虑,会对同一个
+// 企业调用同一个接口做并发数的限制,出现这种限制错误后,请企业调低并发数"
+// (developer.work.weixin.qq.com/document/path/90313). No window has to turn
+// over for that one to lift — fewer callers at once is the entire fix.
+//
+// For 45009 it is a long shot, and the code treats it as one rather than
+// pretending otherwise. The same page says a frequency block lasts as long as
+// the period that earned it: "频率拦截时长一般与调用的限制时长相同,比如说是分钟
+// 级别的限制,则在中频率后的1分钟后自动解除". Two seconds cannot clear a
+// minute's block. What buys the one attempt anyway is the seam this gate
+// cannot see — a reconnect mints a fresh window (see sendQuota), so a 45009
+// can be raised against a count this process is not keeping. retryUnaffordable
+// is what stops that from turning into hammering: when OUR OWN window says the
+// next slot is far off, our count agrees with WeCom's, the block is the real
+// one, and the frame is not sent a second time. That also keeps us on the
+// right side of the same page's advice for this family of codes — "仅系统失败
+// 需要重试。其余错误码,应该排查下调用失败原因".
+//
+// Jittered by retryDelay, because a concurrency refusal hits every concurrent
+// caller at once and a fixed delay sends all of them back at the same instant,
+// which is the opposite of 调低并发数.
+//
+// A field on wsSender rather than a constant read at the call site, for the
+// same reason ackTimeout is one: a test that has to stand still for it is a
+// test nobody runs.
+const sendRetryBackoff = 2 * time.Second
+
+// sendMsgFrame writes one aibot_send_msg body under this chat's quota.
+//
+// The single door for that command: the two producers of one — a piece of an
+// agent's answer (ws_sender.go) and a media push (media_upload.go) — spend the
+// same per-conversation allowance, so a gate on either alone would be a gate
+// on neither.
+//
+// aibot_send_msg is also the only command this tree sends into a conversation
+// with, so gating it gates everything there is. That is a fact about the tree
+// and not a property of the quota: the sentence quoted above puts
+// aibot_respond_msg on the same allowance, so a reply path that writes frames
+// has to reserve here as well, and cannot be excused by carrying a throttle of
+// its own.
+//
+// A refusal is retried once, and only for a throttle the caller can still
+// afford (retryUnaffordable). Retrying a stated refusal is safe in a way
+// retrying a timeout is not: a non-zero errcode is the server saying it did
+// not act on the frame, so a second attempt cannot duplicate anything. A
+// verdict that never came (errAckTimeout) says nothing of the kind and is
+// returned untouched.
+//
+// Written as first attempt / decision / second attempt rather than a loop,
+// because the two attempts do not report failure the same way. The first one's
+// refusal is a FACT — the server named an errcode — and it stays in hand for
+// the rest of the function. As a loop it could not: the second pass's return
+// value was simply the function's, so a context error raised inside request
+// replaced a definite refusal with an unknown outcome, which is the one thing
+// on this path that sends a person to resend a message by hand.
+//
+// That fact has a limit, and the closing switch turns on it. The refusal is
+// the outcome of the FIRST frame. It can answer for the second attempt only
+// while that attempt put nothing new on the wire; once the second frame is
+// written, the refusal says nothing about where it ended up, and the unknown
+// the attempt came back with is the only honest report. request marks which
+// of the two happened — see errAckAbandoned.
+func (s *wsSender) sendMsgFrame(ctx context.Context, chatID string, body map[string]any) error {
+ if err := s.quota.reserve(ctx, chatID); err != nil {
+ // No chat id on either line. In a one-to-one chat the chat id IS
+ // the person's userid, and nothing else in this package puts one
+ // in the log; an operator needs to know the bot is at its ceiling,
+ // not who was talking to it.
+ s.log.Warn("wecom: a chat is at its outbound quota, frame not written",
+ "per_minute", rateLimitPerMinute, "per_hour", rateLimitPerHour)
+ return err
+ }
+ _, refusal := s.request(ctx, cmdSendMsg, body)
+ if refusal == nil || !throttled(refusal) {
+ return refusal
+ }
+
+ delay := s.retryDelay()
+ if reason := s.retryUnaffordable(ctx, chatID, delay); reason != "" {
+ s.log.Warn("wecom: push throttled, retry skipped",
+ "reason", reason, "backoff", delay, "error", refusal)
+ return refusal
+ }
+ s.log.Warn("wecom: push throttled, retrying once",
+ "backoff", delay, "error", refusal)
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ case <-ctx.Done():
+ // The REFUSAL, not the context error. What we know at this point is
+ // that the server refused the frame and nothing landed; reporting the
+ // cancellation instead would downgrade a definite outcome to an
+ // unknown one, and an unknown is the one an operator resolves by hand.
+ return refusal
+ }
+
+ if err := s.quota.reserve(ctx, chatID); err != nil {
+ return refusal
+ }
+ _, err := s.request(ctx, cmdSendMsg, body)
+ switch {
+ case err == nil:
+ return nil
+ case errors.Is(err, errAckTimeout), errors.Is(err, errWriteAttempted), errors.Is(err, errAckAbandoned):
+ // The retry's own outcome is genuinely unknown, and unknown outranks
+ // the first refusal here: the second frame may be in front of the
+ // person right now, and saying "refused" would deny a delivery that
+ // happened. This is the one direction in which the first refusal is
+ // NOT the better answer.
+ //
+ // errAckAbandoned is the case that looks most like the arm below and
+ // belongs here. It IS a context error — errors.Is answers yes for
+ // context.Canceled — but request raises it only after s.write returned
+ // without error, so the second frame is on the wire and the first
+ // attempt's errcode establishes nothing about where it ended up
+ // (ws_sender.go). Tested ahead of the context arm for that reason: the
+ // same error satisfies both, and the specific answer is the true one.
+ return err
+ case errors.Is(err, errRateLimited), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
+ // Nothing was written this time — the gate turned the frame away
+ // before the socket, or request's pre-write check did — so the first
+ // refusal is still the whole story and it is the better half of it. It
+ // files as platform_refused, it is provablyNotSent(false) either way
+ // so no duplicate can follow from it, and it does not send anybody to
+ // resend a message by hand.
+ return refusal
+ default:
+ return err
+ }
+}
+
+// retryDelay is sendRetryBackoff spread over ±50%, so the callers a
+// concurrency refusal caught together do not come back together.
+func (s *wsSender) retryDelay() time.Duration {
+ base := s.retryBackoff
+ if base <= 0 {
+ return 0
+ }
+ return base/2 + time.Duration(mathrand.Int64N(int64(base)))
+}
+
+// retryUnaffordable reports why the one retry should not be attempted, or ""
+// when it should. Two ways it is not worth a frame, and both are answered from
+// what this process knows rather than from hope.
+//
+// The caller has to be able to sit through it. request spends the caller's
+// context on the write AND on the wait for the verdict, so an attempt needs
+// delay + ackTimeout of deadline left; started with less, it comes back as a
+// context error, which is an unknown outcome standing where a definite refusal
+// used to be. The reply path has ten seconds for the whole delivery
+// (outbound.go:155) and a throttle late in one can leave less than that.
+//
+// And the gate has to be able to hand out a slot when the delay is up — admit
+// already knows when the next one frees, so ask it. A slot that is a minute
+// away means our own count has reached the ceiling too, which means the
+// refusal is the quota's rather than a stale count's, and WeCom holds a
+// frequency block for the rest of the period it was earned in (doc 90313,
+// quoted on sendRetryBackoff). Sending again into that costs a frame and
+// changes nothing.
+func (s *wsSender) retryUnaffordable(ctx context.Context, chatID string, delay time.Duration) string {
+ if d, ok := ctx.Deadline(); ok && time.Until(d) < delay+ackTimeout {
+ return "the caller has no budget for another attempt"
+ }
+ if wait := s.quota.nextSlot(chatID, time.Now().Add(delay)); wait > 0 {
+ return fmt.Sprintf("this chat's own quota has no slot for it either, the next one is %s off",
+ wait.Round(time.Millisecond))
+ }
+ return ""
+}
+
+// throttled reports whether a send failure was a throttle the platform will
+// lift by itself.
+func throttled(err error) bool {
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) {
+ return false
+ }
+ return apiErr.Code == errCodeAPIFreqLimit || apiErr.Code == errCodeAPIConcurrencyLimit
+}
+
+// quotaWindow is one of WeCom's published windows: at most limit sends in any
+// span-long stretch. limit is at least 1 — a window nothing can pass is a
+// deployment with the bot switched off, which belongs upstream of here.
+type quotaWindow struct {
+ span time.Duration
+ limit int
+}
+
+// sendQuota admits aibot_send_msg frames at the published rate, counted per
+// target chat.
+//
+// Why one map in one process is the whole accounting, with nothing shared:
+// WeCom counts per (application, recipient), and aibot has no REST outbound
+// path, so every frame for an installation is written by the replica holding
+// the lease on that installation's socket. One sendQuota lives on one
+// wsSender, which is one socket, which is one installation — so the frames
+// this gate sees are exactly the frames WeCom is counting. The DB-backed gate
+// this replaces needed shared state because the outbound queue let ANY replica
+// claim a row and send it; with the queue gone, so is the reason.
+//
+// The scope has one seam: a reconnect mints a new wsSender with an empty
+// window, so a socket that flaps mid-minute can put us over WeCom's count
+// while ours reads clean. That is the case sendMsgFrame's retry exists for,
+// and the reason this gate is not written as if it were exact.
+//
+// A sliding count rather than a token bucket, because the published figure is
+// a count in a window: a bucket of 30 refilling at 30/minute admits up to 60
+// inside one rolling minute, which is the number we are trying not to reach.
+type sendQuota struct {
+ mu sync.Mutex
+ // sent holds each chat's send times, ascending, trimmed to the longest
+ // window. Bounded by rateLimitPerHour entries per chat; quiet chats are
+ // dropped by sweep.
+ sent map[string][]time.Time
+ lastSweep time.Time
+
+ windows []quotaWindow
+ longest time.Duration
+ maxWait time.Duration
+ // writeBudget is what reserve refuses to spend out of a caller's deadline,
+ // because the write that follows needs it. ackTimeout, since that is what
+ // bounds the wait for the verdict (ws_sender.go).
+ writeBudget time.Duration
+}
+
+func newSendQuota() *sendQuota {
+ return newSendQuotaWith(rateWaitBudget,
+ quotaWindow{span: time.Minute, limit: rateLimitPerMinute},
+ quotaWindow{span: time.Hour, limit: rateLimitPerHour},
+ )
+}
+
+// newSendQuotaWith builds a gate with windows of its own. Tests use it to
+// exercise the waiting and refusing paths in milliseconds instead of minutes.
+func newSendQuotaWith(maxWait time.Duration, windows ...quotaWindow) *sendQuota {
+ q := &sendQuota{
+ sent: make(map[string][]time.Time),
+ windows: windows,
+ maxWait: maxWait,
+ writeBudget: ackTimeout,
+ }
+ for _, w := range windows {
+ if w.span > q.longest {
+ q.longest = w.span
+ }
+ }
+ return q
+}
+
+// reserve returns once this chat may take a slot, or fails without one.
+//
+// It waits when a slot is close enough to be worth waiting for — the point of
+// a gate is that a burst arrives late rather than not at all — and gives up
+// immediately when it is not, rather than spending a caller's whole budget to
+// arrive at the same answer with no time left to record it.
+func (q *sendQuota) reserve(ctx context.Context, chatID string) error {
+ giveUpAt := time.Now().Add(q.maxWait)
+ if d, ok := ctx.Deadline(); ok {
+ // deadline − writeBudget, not the deadline. A wait that merely fits
+ // inside the caller's deadline is not good enough: what comes after it
+ // is a write plus a wait for the verdict, and ackTimeout is how long
+ // that alone is allowed to take. Waiting past this point buys a turn
+ // on the wire the caller can no longer sit through, and request then
+ // returns a context error — an outcome nobody can classify, where the
+ // gate could have returned a definite one for free. See rateWaitBudget
+ // for the deadlines this actually bites on.
+ if latest := d.Add(-q.writeBudget); latest.Before(giveUpAt) {
+ giveUpAt = latest
+ }
+ }
+ for {
+ wait := q.admit(chatID, time.Now())
+ if wait == 0 {
+ // A slot was free, so no budget was needed. Deliberately checked
+ // before giveUpAt: a caller down to its last moment still gets its
+ // turn on the wire when the gate is not in the way.
+ return nil
+ }
+ if time.Now().Add(wait).After(giveUpAt) {
+ return fmt.Errorf("%w: the next slot is %s away", errRateLimited, wait.Round(time.Millisecond))
+ }
+ timer := time.NewTimer(wait)
+ select {
+ case <-timer.C:
+ case <-ctx.Done():
+ timer.Stop()
+ return fmt.Errorf("%w: the caller gave up while waiting for a slot", errRateLimited)
+ }
+ }
+}
+
+// admit records one send against chatID and returns 0, or leaves the count
+// untouched and returns how long until the earliest slot frees.
+func (q *sendQuota) admit(chatID string, now time.Time) time.Duration {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ q.sweep(now)
+
+ sent := trimBefore(q.sent[chatID], now.Add(-q.longest))
+ if wait := q.waitFor(sent, now); wait > 0 {
+ q.sent[chatID] = sent
+ return wait
+ }
+ q.sent[chatID] = append(sent, now)
+ return 0
+}
+
+// nextSlot is how long after at this chat's next slot frees, WITHOUT taking
+// one. The read-only twin of admit, for deciding whether an action is worth
+// starting — asking admit would answer the question by spending the thing
+// being asked about.
+func (q *sendQuota) nextSlot(chatID string, at time.Time) time.Duration {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ return q.waitFor(trimBefore(q.sent[chatID], at.Add(-q.longest)), at)
+}
+
+// waitFor is how long until sent has room in every window, 0 when it has room
+// now. The one place the windows are read, so admit and nextSlot cannot drift
+// into answering the same question differently. Caller holds mu.
+func (q *sendQuota) waitFor(sent []time.Time, now time.Time) time.Duration {
+ var wait time.Duration
+ for _, w := range q.windows {
+ first := indexAtOrAfter(sent, now.Add(-w.span))
+ inWindow := len(sent) - first
+ if inWindow < w.limit {
+ continue
+ }
+ // The window has no room until enough of its oldest entries age out
+ // of it — one of them for a window sitting exactly on the limit.
+ if free := sent[first+inWindow-w.limit].Add(w.span).Sub(now); free > wait {
+ wait = free
+ }
+ }
+ return wait
+}
+
+// sweep drops chats with nothing left inside the longest window. Without it a
+// process that has talked to many chats keeps a timestamp slice alive for
+// every one of them for as long as it runs. Caller holds mu.
+func (q *sendQuota) sweep(now time.Time) {
+ if now.Sub(q.lastSweep) < q.longest {
+ return
+ }
+ q.lastSweep = now
+ cutoff := now.Add(-q.longest)
+ for chat, sent := range q.sent {
+ if len(sent) == 0 || !sent[len(sent)-1].After(cutoff) {
+ delete(q.sent, chat)
+ }
+ }
+}
+
+// trimBefore drops the entries older than cutoff from an ascending slice.
+func trimBefore(sent []time.Time, cutoff time.Time) []time.Time {
+ return sent[indexAtOrAfter(sent, cutoff):]
+}
+
+// indexAtOrAfter is where cutoff falls in an ascending slice of send times.
+func indexAtOrAfter(sent []time.Time, cutoff time.Time) int {
+ return sort.Search(len(sent), func(i int) bool { return sent[i].After(cutoff) })
+}
diff --git a/server/internal/integrations/wecom/rate_limit_test.go b/server/internal/integrations/wecom/rate_limit_test.go
new file mode 100644
index 0000000000..879012a9a2
--- /dev/null
+++ b/server/internal/integrations/wecom/rate_limit_test.go
@@ -0,0 +1,830 @@
+package wecom
+
+// rate_limit_test.go — the gate and the retry that stand between an
+// over-quota aibot_send_msg and a reply the person never sees.
+//
+// WHY THESE TESTS ARE THE ONLY THING GUARDING THIS. When the outbound queue
+// was retired, the rate gate and the queue consumer's backoff went with it,
+// and nothing anywhere failed: the gate lived in channel/outbox, its wecom
+// half was a file of two constants, and no test in this package ever asserted
+// that a push was admitted by anything. `go build`, `go vet` and the whole
+// suite stayed green while the last defence against errcode 45009 left the
+// tree. Every test below is written to fail if that happens again — they
+// assert on what the socket carried and on which error came back, not on any
+// internal the next refactor is free to move.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// quotaConn answers each aibot_send_msg with the next errcode in codes,
+// and 0 once the script runs out. Recording only the pushes is deliberate:
+// these tests are about the command WeCom counts, and a ping or a stream
+// frame sharing the socket must not move the numbers they assert on.
+type quotaConn struct {
+ mu sync.Mutex
+ sender *wsSender
+ pushes []map[string]any
+ codes []int
+ writes int
+
+ // ackDelay holds every verdict back this long. A real server answers in a
+ // few hundred milliseconds, so this is how a test makes a write outlast
+ // whatever budget the caller had left for it — the failure the gate is
+ // supposed to make impossible rather than merely unlikely.
+ ackDelay time.Duration
+ // silentFrom is the 1-based push from which nothing answers at all, so a
+ // test can park the sender on a verdict that never comes.
+ silentFrom int
+ // onPush runs after each push is recorded, outside the lock, with its
+ // 1-based number. A hook rather than a channel because the tests that use
+ // it need to act DURING the write, not after it.
+ onPush func(n int)
+}
+
+func (c *quotaConn) WriteMessage(_ int, data []byte) error {
+ var env frameEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return err
+ }
+ c.mu.Lock()
+ code, n := 0, 0
+ if env.Cmd == cmdSendMsg {
+ var body map[string]any
+ _ = json.Unmarshal(env.Body, &body)
+ c.pushes = append(c.pushes, body)
+ if c.writes < len(c.codes) {
+ code = c.codes[c.writes]
+ }
+ c.writes++
+ n = c.writes
+ }
+ s, delay, silent, hook := c.sender, c.ackDelay, c.silentFrom, c.onPush
+ c.mu.Unlock()
+ if s != nil && (silent == 0 || n < silent) {
+ ack := frameEnvelope{
+ Headers: frameHeaders{ReqID: env.Headers.ReqID},
+ ErrCode: code,
+ ErrMsg: "scripted",
+ }
+ if delay > 0 {
+ time.AfterFunc(delay, func() { s.routeResponse(ack) })
+ } else {
+ s.routeResponse(ack)
+ }
+ }
+ if hook != nil && n > 0 {
+ hook(n)
+ }
+ return nil
+}
+
+func (c *quotaConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }
+func (c *quotaConn) SetReadDeadline(time.Time) error { return nil }
+func (c *quotaConn) SetWriteDeadline(time.Time) error { return nil }
+func (c *quotaConn) Close() error { return nil }
+
+func (c *quotaConn) pushCount() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.pushes)
+}
+
+func (c *quotaConn) pushedTo(chatID string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ n := 0
+ for _, b := range c.pushes {
+ if b["chatid"] == chatID {
+ n++
+ }
+ }
+ return n
+}
+
+// quotaSender wires a sender to a quotaConn with the backoff shortened,
+// so a test exercising the retry does not stand still for two seconds.
+func quotaSender(codes ...int) (*wsSender, *quotaConn) {
+ conn := &quotaConn{codes: codes}
+ s := newWSSender(conn, testLogger())
+ s.retryBackoff = time.Millisecond
+ conn.sender = s
+ return s, conn
+}
+
+// logHook calls fn the first time a record's message contains want, and passes
+// every record on. A log line is an unusual place to hang a test hook, and on
+// the retry path it is the only exact one: "the refusal is in hand, the retry
+// is decided, and nothing has been written yet" is a window sendMsgFrame is
+// inside for exactly one statement, and that statement is this WARN. Hooking
+// the conn instead would race the FIRST attempt's ack — both would be ready in
+// request's select and which one it takes is a coin toss.
+type logHook struct {
+ slog.Handler
+ want string
+ fn func()
+ once sync.Once
+ fired atomic.Bool
+}
+
+func (h *logHook) Handle(ctx context.Context, r slog.Record) error {
+ if strings.Contains(r.Message, h.want) {
+ h.once.Do(func() {
+ h.fired.Store(true)
+ h.fn()
+ })
+ }
+ return h.Handler.Handle(ctx, r)
+}
+
+// hookedSender is quotaSender with fn wired to run the moment msg is logged.
+func hookedSender(msg string, fn func(), codes ...int) (*wsSender, *quotaConn, *logHook) {
+ s, conn := quotaSender(codes...)
+ h := &logHook{Handler: slog.NewTextHandler(io.Discard, nil), want: msg, fn: fn}
+ s.log = slog.New(h)
+ return s, conn, h
+}
+
+// spentMinute is a gate running on WeCom's real published windows whose
+// per-minute allowance for chatID is already gone, with the next slot freeing
+// freeIn from now. The only way to reach the interesting states at the
+// published figures inside a test: a real minute is a real minute, and admit
+// takes the clock as an argument precisely so the timestamps can be placed.
+func spentMinute(chatID string, freeIn time.Duration) *sendQuota {
+ q := newSendQuota()
+ at := time.Now().Add(freeIn - time.Minute)
+ for i := 0; i < rateLimitPerMinute; i++ {
+ q.admit(chatID, at)
+ }
+ return q
+}
+
+// ---- what a cancellation from request establishes ----
+//
+// The retry's closing switch weighs the first attempt's refusal against
+// whatever the second attempt came back with, and for a cancellation the
+// answer flips on one fact: had the second frame been written yet. These two
+// pin that fact at the only place that holds it.
+
+// Cancelled before the write: request has to say so, and nothing may reach the
+// socket. This is what lets sendMsgFrame keep reporting the first refusal —
+// with no second frame on the wire there is no second delivery to deny.
+//
+// REVERSE VERIFICATION: delete the ctx.Err() check at the top of request and
+// this fails with
+//
+// 1 frame(s) reached the socket after a cancelled context, want 0
+func TestARequestCancelledBeforeTheWriteReportsNothingWritten(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ _, err := s.request(ctx, cmdSendMsg, map[string]any{"chatid": "CHAT_1"})
+
+ if got := conn.pushCount(); got != 0 {
+ t.Fatalf("%d frame(s) reached the socket after a cancelled context, want 0", got)
+ }
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("error = %v, want the caller's own cancellation", err)
+ }
+ if errors.Is(err, errAckAbandoned) {
+ t.Fatalf("error = %v claims the frame went out, and nothing was written", err)
+ }
+}
+
+// The context lost after the write, waiting for the verdict: request has to
+// mark it, whichever way it was lost. The frame is gone — WriteMessage took
+// the bytes — so the outcome is the same unknown errAckTimeout stands for, and
+// a caller weighing it against anything else in hand needs to see that from
+// the error itself.
+//
+// Both ways, because they are the two the reply path actually ends on: a
+// cancelled delivery and a deadline that ran out, and the write is equally
+// gone under either.
+//
+// REVERSE VERIFICATION: return a bare ctx.Err() from request's post-write
+// select and this fails with
+//
+// error = context canceled does not carry errAckAbandoned, so a caller cannot tell it from a cancellation that wrote nothing
+func TestARequestThatLosesItsContextAfterTheWriteSaysTheFrameWentOut(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ // ctxFor builds the caller's context and, for the cancelled case, the
+ // hook that ends it once the frame is on the wire. onPush runs after
+ // WriteMessage has taken the bytes, which is what makes "after the
+ // write" a fact here rather than a hope.
+ ctxFor func(t *testing.T, conn *quotaConn) context.Context
+ want error
+ }{
+ {
+ name: "the caller cancelled",
+ ctxFor: func(t *testing.T, conn *quotaConn) context.Context {
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ conn.onPush = func(n int) {
+ if n == 1 {
+ cancel()
+ }
+ }
+ return ctx
+ },
+ want: context.Canceled,
+ },
+ {
+ name: "the delivery's deadline ran out",
+ ctxFor: func(t *testing.T, conn *quotaConn) context.Context {
+ // Well inside ackTimeout, so the deadline is what ends the
+ // wait and not the ack timer.
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ t.Cleanup(cancel)
+ return ctx
+ },
+ want: context.DeadlineExceeded,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ conn.silentFrom = 1 // nothing answers, so the wait is the caller's to lose
+ ctx := tc.ctxFor(t, conn)
+
+ _, err := s.request(ctx, cmdSendMsg, map[string]any{"chatid": "CHAT_1"})
+
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d frame(s) reached the socket, want 1 — this test's premise is that the write happened", got)
+ }
+ if !errors.Is(err, errAckAbandoned) {
+ t.Fatalf("error = %v does not carry errAckAbandoned, so a caller cannot tell it from a cancellation that wrote nothing", err)
+ }
+ if !errors.Is(err, tc.want) {
+ t.Fatalf("error = %v no longer reads as %v; every existing errors.Is on this path stops matching", err, tc.want)
+ }
+ // And it keeps landing on the side of the classifiers that means
+ // "the user may already have this", which is what the wrapping is
+ // for: the mark is for the one caller that has something else to
+ // weigh it against, not a new outcome for everyone else.
+ if r := unconfirmedReason(err); r == "" {
+ t.Fatalf("error = %v files as a definite outcome", err)
+ }
+ if provablyNotSent(err) {
+ t.Fatalf("error = %v is reported as provably unsent, which hands the frame back for another offer and duplicates it", err)
+ }
+ })
+ }
+}
+
+// ---- the retry ----
+
+// A throttle is the platform saying "not now". Everything downstream reads a
+// stated refusal as final — provablyNotSent releases nothing, classifyDrop
+// files platform_refused — so without a retry here, one 45009 is one answer
+// that exists in the Multica transcript and nowhere on the person's screen.
+//
+// REVERSE VERIFICATION: delete the retry loop from sendMsgFrame (call
+// s.request once and return) and this fails on the returned error, with the
+// conn showing a single push. `go build`, `go vet` and `go test -race` on the
+// rest of the package stay silent — no other test in the tree sends a frame
+// WeCom refuses once and accepts next.
+func TestAThrottledPushIsRetriedInsteadOfLost(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIFreqLimit)
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the answer"); err != nil {
+ t.Fatalf("a push WeCom throttled once was reported as a failed reply: %v", err)
+ }
+ if got := conn.pushCount(); got != 2 {
+ t.Fatalf("%d push(es) reached the socket, want 2 — the refusal was not retried", got)
+ }
+}
+
+// 45033 is the other throttle on this route: concurrency rather than
+// frequency, same "come back in a moment" meaning. The connect path already
+// treats the pair alike (wecom_channel.go, credential_probe.go); the send path
+// has to agree, or which of the two WeCom picks decides whether the reply
+// survives.
+func TestAConcurrencyRefusalIsRetriedToo(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIConcurrencyLimit)
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the answer"); err != nil {
+ t.Fatalf("a push WeCom refused for concurrency was reported as a failed reply: %v", err)
+ }
+ if got := conn.pushCount(); got != 2 {
+ t.Fatalf("%d push(es) reached the socket, want 2", got)
+ }
+}
+
+// The retry is one, not a loop. A throttle that has not lifted by the second
+// attempt is a throttle we make worse by hammering — 45009's own documentation
+// says the ban lasts as long as the window it was earned in.
+func TestAThrottleThatDoesNotLiftIsReportedNotRetriedForever(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIFreqLimit, errCodeAPIFreqLimit, errCodeAPIFreqLimit)
+
+ err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the answer")
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) || apiErr.Code != errCodeAPIFreqLimit {
+ t.Fatalf("error = %v, want the 45009 refusal reported as it stands", err)
+ }
+ if got := conn.pushCount(); got != 2 {
+ t.Fatalf("%d push(es) reached the socket, want exactly 2 — one attempt and one retry", got)
+ }
+}
+
+// The guard on the retry. 45002 is the frame being too long: identical bytes
+// earn an identical refusal, so a second attempt spends another slot out of
+// the same quota this file exists to protect and cannot possibly help.
+func TestARefusalThatIsNotAThrottleIsNotRetried(t *testing.T) {
+ t.Parallel()
+ const errCodeMsgTooLong = 45002
+ s, conn := quotaSender(errCodeMsgTooLong)
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the answer"); err == nil {
+ t.Fatal("a frame WeCom refused outright was reported as delivered")
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1 — a permanent refusal was retried", got)
+ }
+}
+
+// The retry has to be affordable before it is attempted, because the frame it
+// costs is not the expensive part — the REPORT is. Once the backoff is over,
+// the second attempt spends the caller's context on a write and on the wait
+// for a verdict, and a context error raised in there used to become the
+// function's return value, replacing a refusal we were certain of with
+// "interrupted". unconfirmedReason files that as an unknown outcome, which
+// tells an operator the person may already have the message and somebody
+// should go and check — for a frame WeCom had stated, in so many words, that
+// it did not act on.
+//
+// Numbers from the reply path rather than invented: a throttle arriving with
+// 300ms left of a delivery cannot fund a 100ms backoff plus the five seconds
+// ackTimeout allows the verdict.
+//
+// REVERSE VERIFICATION: delete the retryUnaffordable check from sendMsgFrame
+// and this fails with
+//
+// 2 push(es) reached the socket, want 1 — the retry ran on a budget that could not hold it
+//
+// and with sendMsgFrame back in its reviewed shape (one loop, the second
+// pass's return value winning) with the reviewer's own probe output:
+//
+// error = context deadline exceeded, want the 45009 refusal the server stated
+func TestARetryTheCallerCannotAffordKeepsTheRefusal(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIFreqLimit)
+ s.retryBackoff = 100 * time.Millisecond
+ // Nothing answers a retry, which is the point: an attempt started without
+ // the budget to see it through does not get a verdict of its own, it gets
+ // the caller's deadline.
+ conn.silentFrom = 2
+
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+ err := s.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "the answer")
+
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) || apiErr.Code != errCodeAPIFreqLimit {
+ t.Fatalf("error = %v, want the 45009 refusal the server stated", err)
+ }
+ if r := unconfirmedReason(err); r != "" {
+ t.Errorf("the refusal was filed as an unknown outcome (%q); "+
+ "an operator reads that as 'the user may already have it' and resends by hand", r)
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1 — the retry ran on a budget that could not hold it", got)
+ }
+}
+
+// The retry was affordable and was about to run, and the caller went away
+// BEFORE the second frame could reach the socket. Nothing new can have been
+// delivered, so the first refusal is still the whole story — and it is the
+// better half of it: definite where a context error is ambiguous, and only one
+// of the two sends a person to resend a message by hand.
+//
+// The cancellation is driven off the retry's own WARN line, for the reason on
+// logHook: it is the one moment in this function that is provably after the
+// refusal and provably before the write.
+//
+// REVERSE VERIFICATION: return ctx.Err() rather than refusal from the context
+// arm of sendMsgFrame's backoff select and this fails with
+//
+// error = context canceled, want the 45009 refusal the server stated
+func TestASecondAttemptCutShortBeforeItWroteReportsTheFirstRefusal(t *testing.T) {
+ t.Parallel()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ s, conn, hook := hookedSender("push throttled, retrying once", cancel, errCodeAPIFreqLimit)
+ // Long enough that the backoff cannot elapse on its own: the only way out
+ // of it here is the cancellation, so a second push means the write went
+ // ahead after the caller was gone.
+ s.retryBackoff = time.Hour
+
+ err := s.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "the answer")
+
+ if !hook.fired.Load() {
+ t.Fatal("the retry was never started — this test's premise is a retry cut short, not one skipped")
+ }
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) || apiErr.Code != errCodeAPIFreqLimit {
+ t.Fatalf("error = %v, want the 45009 refusal the server stated", err)
+ }
+ if r := unconfirmedReason(err); r != "" {
+ t.Errorf("the refusal was filed as an unknown outcome (%q); nothing was written, so nothing is unknown", r)
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1", got)
+ }
+}
+
+// The same cancellation one step later, and the answer is the opposite. The
+// retry ran, the second frame IS on the wire, and the caller went away while
+// its verdict was outstanding.
+//
+// The first refusal is a fact about the FIRST attempt — WeCom stated it did not
+// act on that frame — and it establishes nothing about the second one, which
+// may be in front of the person right now. Reporting it here files
+// platform_refused and unconfirmedReason "", which together tell an operator
+// the reply was refused and never shown; the operator resends, and the person
+// gets the answer twice. The unknown is the honest report: nobody is told a
+// delivery failed that may have happened.
+//
+// REVERSE VERIFICATION: drop errAckAbandoned from the unknown arm of
+// sendMsgFrame's closing switch, so the context arm catches it again, and this
+// fails with
+//
+// error = wecom: aibot_send_msg rejected errcode=45009 errmsg=scripted, want the second attempt's own outcome — the first refusal is a fact about the first frame, and the second one is already out
+func TestASecondAttemptCutShortAfterItWroteKeepsTheUnknown(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIFreqLimit)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ // Nothing answers the retry, and the caller gives up once its frame is on
+ // the wire: onPush runs after WriteMessage has taken the bytes.
+ conn.silentFrom = 2
+ conn.onPush = func(n int) {
+ if n == 2 {
+ cancel()
+ }
+ }
+
+ err := s.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "the answer")
+
+ if got := conn.pushCount(); got != 2 {
+ t.Fatalf("%d push(es) reached the socket, want 2 — this test's premise is that the retry ran", got)
+ }
+ var apiErr *wecomAPIError
+ if errors.As(err, &apiErr) {
+ t.Fatalf("error = %v, want the second attempt's own outcome — the first refusal is a fact about the first frame, and the second one is already out", err)
+ }
+ if r := unconfirmedReason(err); r == "" {
+ t.Fatalf("error = %v is filed as a definite outcome; the frame went out and no verdict came back, so this reads as unknown", err)
+ }
+ if provablyNotSent(err) {
+ t.Fatalf("error = %v is reported as provably unsent, which hands the frame back for another offer and duplicates it", err)
+ }
+}
+
+// A throttle raised while OUR OWN window is spent is the quota's, not a stale
+// count's, and WeCom holds a frequency block for the rest of the period that
+// earned it (doc 90313). So there is nothing to come back to in two seconds,
+// and the decision is taken from admit — which already knows when the next
+// slot frees — rather than from a fixed sleep.
+//
+// The real sendRetryBackoff on purpose: the proof is that the call returns
+// long before two seconds have passed.
+//
+// REVERSE VERIFICATION: delete the slot arm from retryUnaffordable and this
+// fails with
+//
+// the call took 2.976430042s — it served a backoff instead of asking admit when the next slot frees
+func TestAThrottleIsNotRetriedWhenOurOwnWindowIsSpentToo(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender(errCodeAPIFreqLimit)
+ s.retryBackoff = sendRetryBackoff
+ // 29 spent, so this send is the minute's 30th: admitted, then refused by
+ // the server, with the window full behind it.
+ q := newSendQuota()
+ at := time.Now()
+ for i := 0; i < rateLimitPerMinute-1; i++ {
+ q.admit("CHAT_1", at)
+ }
+ s.quota = q
+
+ start := time.Now()
+ err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the answer")
+ elapsed := time.Since(start)
+
+ var apiErr *wecomAPIError
+ if !errors.As(err, &apiErr) || apiErr.Code != errCodeAPIFreqLimit {
+ t.Fatalf("error = %v, want the 45009 refusal the server stated", err)
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1 — a frame was spent on a block that lasts the minute out", got)
+ }
+ if elapsed > sendRetryBackoff/2 {
+ t.Fatalf("the call took %s — it served a backoff instead of asking admit when the next slot frees", elapsed)
+ }
+}
+
+// The delay is spread, because a concurrency refusal catches every caller that
+// was in flight at once and a fixed delay sends all of them back at the same
+// instant. 45033's documented remedy is the opposite of that: "出现这种限制错误
+// 后,请企业调低并发数" (doc 90313).
+//
+// REVERSE VERIFICATION: return s.retryBackoff unchanged from retryDelay and
+// this fails with
+//
+// 50 draws produced 1 distinct delay(s) — every caller one refusal caught comes back at the same instant
+func TestTheRetryBackoffIsSpreadAcrossCallers(t *testing.T) {
+ t.Parallel()
+ s, _ := quotaSender()
+ s.retryBackoff = sendRetryBackoff
+
+ low, high := s.retryBackoff/2, s.retryBackoff+s.retryBackoff/2
+ seen := make(map[time.Duration]bool)
+ for i := 0; i < 50; i++ {
+ d := s.retryDelay()
+ if d < low || d >= high {
+ t.Fatalf("retryDelay() = %s, want inside [%s, %s)", d, low, high)
+ }
+ seen[d] = true
+ }
+ if len(seen) < 2 {
+ t.Fatalf("50 draws produced %d distinct delay(s) — every caller one refusal caught comes back at the same instant", len(seen))
+ }
+}
+
+// ---- the gate ----
+
+// The gate waits for a slot, but never so long that the write it is waiting
+// for can no longer be seen through. The wait has to fit inside the caller's
+// deadline MINUS ackTimeout, not merely inside the deadline.
+//
+// The numbers are the inbox push path's, unchanged: five seconds for the whole
+// delivery (outbound.go:415), and a slot 2.5s away — comfortably inside
+// rateWaitBudget, so a gate that only checked the deadline would wait for it
+// and hand the write the 2.5s that were left, for a verdict ackTimeout allows
+// five seconds to arrive. That write is cut off mid-flight and reported as an
+// unknown outcome. Refusing before it is the honest failure: nothing on the
+// wire, a definite error, and the caller's whole budget still there to record
+// it with.
+//
+// REVERSE VERIFICATION: drop the writeBudget subtraction from reserve (check
+// the deadline itself) and this fails after the full five seconds with
+//
+// error = context deadline exceeded, want errRateLimited
+func TestTheGateLeavesTheWriteItsAckBudget(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ conn.ackDelay = 3 * time.Second // slower than what 2.5s of waiting leaves
+ s.quota = spentMinute("CHAT_1", 2500*time.Millisecond)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ start := time.Now()
+ err := s.sendTextCtx(ctx, "CHAT_1", chatTypeSingleInt, "you have a new item")
+ elapsed := time.Since(start)
+
+ if !errors.Is(err, errRateLimited) {
+ t.Fatalf("error = %v, want errRateLimited", err)
+ }
+ if r := unconfirmedReason(err); r != "" {
+ t.Errorf("a frame the gate never wrote was filed as an unknown outcome (%q)", r)
+ }
+ if got := conn.pushCount(); got != 0 {
+ t.Fatalf("%d push(es) reached the socket, want 0 — the gate spent the write's own budget waiting", got)
+ }
+ if elapsed > time.Second {
+ t.Fatalf("the refusal took %s — the gate waited for a slot it could not afford to use", elapsed)
+ }
+}
+
+// The gate's promise, at the published figures and nowhere near them: a chat
+// that goes a LITTLE over 30 a minute has its next frame delayed into the slot
+// that is about to free, and the frame goes out.
+//
+// At WeCom's real windows, which is the whole point of this one — the same
+// claim at a 150ms window and a limit of 2 is true by construction, because a
+// wait that short cannot outlast any budget worth naming.
+//
+// REVERSE VERIFICATION: drop the s.quota.reserve call from sendMsgFrame and
+// this fails with
+//
+// the send returned after 439.417µs — the frame was never held back
+func TestABurstJustOverThePublishedRateIsDelayedNotLost(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ s.quota = spentMinute("CHAT_1", 400*time.Millisecond)
+
+ start := time.Now()
+ err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "piece")
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("a send 400ms short of a free slot failed instead of waiting for it: %v", err)
+ }
+ if elapsed < 300*time.Millisecond {
+ t.Fatalf("the send returned after %s — the frame was never held back", elapsed)
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1 — waiting must not cost a message", got)
+ }
+}
+
+// And the limit of that promise, pinned rather than described. A burst of 31
+// into one chat at the published figures does NOT arrive late: the 31st frame
+// is refused where it stands, because the next slot is a whole window away and
+// no caller on this path has a minute to give. Nothing is written, nothing
+// tells the person, and the drop is filed under transport_error.
+//
+// transport_error rather than platform_refused is deliberate and is asserted
+// here so it stays deliberate: WeCom refused nothing, this process did, and
+// the reason text on that counter already covers a delivery whose own budget
+// ran out before it got a turn on the wire. What must not change is the last
+// assertion — errRateLimited stays provably unsent, which is what lets the
+// relay offer the frame somewhere else instead of writing it off.
+//
+// REVERSE VERIFICATION: drop the s.quota.reserve call from sendMsgFrame and
+// this fails with
+//
+// error = <nil>, want errRateLimited on frame 31 of a burst
+func TestTheThirtyFirstFrameOfABurstIsRefusedNotDelayed(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+
+ for i := 0; i < rateLimitPerMinute; i++ {
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "piece"); err != nil {
+ t.Fatalf("send %d of the minute's %d failed: %v", i+1, rateLimitPerMinute, err)
+ }
+ }
+
+ start := time.Now()
+ err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "the one past the ceiling")
+ elapsed := time.Since(start)
+
+ if !errors.Is(err, errRateLimited) {
+ t.Fatalf("error = %v, want errRateLimited on frame %d of a burst", err, rateLimitPerMinute+1)
+ }
+ if !strings.Contains(err.Error(), "the next slot is") {
+ t.Errorf("error = %q, want it to say how far off the next slot is — that distance is the whole reason it was refused", err)
+ }
+ if elapsed >= rateWaitBudget {
+ t.Errorf("the refusal took %s — a wait of nearly a whole window was served instead of refused", elapsed)
+ }
+ if got := conn.pushCount(); got != rateLimitPerMinute {
+ t.Fatalf("%d push(es) reached the socket, want %d — the refused frame was written anyway", got, rateLimitPerMinute)
+ }
+ if got := classifyDrop(err); got != dropTransport {
+ t.Errorf("classifyDrop = %q, want %q — WeCom refused nothing here, this process did", got, dropTransport)
+ }
+ if r := unconfirmedReason(err); r != "" {
+ t.Errorf("a frame the gate never wrote was filed as an unknown outcome (%q)", r)
+ }
+ if !provablyNotSent(err) {
+ t.Error("a frame the gate never wrote was not reported as provably unsent, so the relay will not offer it anywhere else")
+ }
+}
+
+// When the wait would outlast the caller, the gate says so BEFORE writing.
+// This is the one outcome where a reply is knowingly given up on, and it has
+// to be the honest kind: nothing on the wire, a definite error, and a reason
+// an operator can read. errRateLimited is deliberately not a context error —
+// unconfirmedReason would file that as "may already have arrived" and send
+// somebody to resend a message the user never got.
+func TestAWaitLongerThanTheCallerHasIsRefusedBeforeTheWrite(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ s.quota = newSendQuotaWith(0, quotaWindow{span: time.Hour, limit: 1})
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "first"); err != nil {
+ t.Fatalf("the first send failed: %v", err)
+ }
+ err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "second")
+ if !errors.Is(err, errRateLimited) {
+ t.Fatalf("error = %v, want errRateLimited", err)
+ }
+ if unconfirmedReason(err) != "" {
+ t.Errorf("a frame the gate never wrote was filed as an unknown outcome (%q); "+
+ "an operator reads that as 'the user may already have it'", unconfirmedReason(err))
+ }
+ if !provablyNotSent(err) {
+ t.Error("a frame the gate never wrote was not reported as provably unsent, so the relay will not offer it anywhere else")
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1 — the refused frame was written anyway", got)
+ }
+}
+
+// The quota WeCom publishes is per recipient, so one busy conversation must
+// not silence every other person the bot is talking to. Keyed per chat is
+// also what makes the in-process gate sound: it counts what the platform
+// counts.
+func TestOneBusyChatDoesNotThrottleTheOthers(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ s.quota = newSendQuotaWith(0, quotaWindow{span: time.Hour, limit: 1})
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "first"); err != nil {
+ t.Fatalf("CHAT_1's first send failed: %v", err)
+ }
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "second"); !errors.Is(err, errRateLimited) {
+ t.Fatalf("CHAT_1's second send: error = %v, want errRateLimited — this test's premise is gone", err)
+ }
+ if err := s.sendTextCtx(context.Background(), "CHAT_2", chatTypeSingleInt, "hello"); err != nil {
+ t.Fatalf("CHAT_2 was refused because CHAT_1 spent its own quota: %v", err)
+ }
+ if got := conn.pushedTo("CHAT_2"); got != 1 {
+ t.Fatalf("%d push(es) reached CHAT_2, want 1", got)
+ }
+}
+
+// A file and a piece of an answer are the same command to WeCom and spend the
+// same allowance. A gate on the text route alone would be no gate at all on a
+// turn that answers in words and then sends attachments one frame each.
+func TestAMediaPushSpendsTheSameQuotaAsAnAnswer(t *testing.T) {
+ t.Parallel()
+ s, conn := quotaSender()
+ s.quota = newSendQuotaWith(0, quotaWindow{span: time.Hour, limit: 1})
+
+ if err := s.sendTextCtx(context.Background(), "CHAT_1", chatTypeSingleInt, "here it is"); err != nil {
+ t.Fatalf("the answer failed: %v", err)
+ }
+ err := s.sendMedia(context.Background(), "CHAT_1", chatTypeSingleInt, mediaSend{Kind: mediaTypeImage, MediaID: "MEDIA_1"})
+ if !errors.Is(err, errRateLimited) {
+ t.Fatalf("media push error = %v, want errRateLimited — the file route is not behind the gate", err)
+ }
+ if got := conn.pushCount(); got != 1 {
+ t.Fatalf("%d push(es) reached the socket, want 1", got)
+ }
+}
+
+// ---- the published numbers ----
+
+// The figures themselves, pinned to the windows the gate runs on: 30 a minute
+// and 1000 an hour, per recipient (WeCom doc 90454, read 2026-08-22). Nothing
+// else in the tree checks them — the file that held them last was deleted
+// whole, with its numbers, and nothing went red.
+func TestTheGateRunsOnWeComsPublishedFigures(t *testing.T) {
+ t.Parallel()
+ q := newSendQuota()
+ base := time.Now()
+
+ for i := 0; i < rateLimitPerMinute; i++ {
+ if wait := q.admit("CHAT_1", base); wait != 0 {
+ t.Fatalf("send %d of %d was held back by %s; the minute's allowance is not being spent", i+1, rateLimitPerMinute, wait)
+ }
+ }
+ if wait := q.admit("CHAT_1", base); wait == 0 {
+ t.Fatalf("send %d in the same instant was admitted; the per-minute ceiling is %d", rateLimitPerMinute+1, rateLimitPerMinute)
+ }
+ // A minute on, the first send has aged out and its slot is free again.
+ if wait := q.admit("CHAT_1", base.Add(time.Minute+time.Millisecond)); wait != 0 {
+ t.Fatalf("a send a minute later was held back by %s; the window does not slide", wait)
+ }
+
+ // The hour is the second ceiling, and it binds even when no minute does:
+ // spaced three seconds apart, nothing ever comes close to 30 a minute.
+ spread := newSendQuota()
+ for i := 0; i < rateLimitPerHour; i++ {
+ at := base.Add(time.Duration(i) * 3 * time.Second)
+ if wait := spread.admit("CHAT_1", at); wait != 0 {
+ t.Fatalf("send %d of %d was held back by %s; the hour's allowance is not being spent", i+1, rateLimitPerHour, wait)
+ }
+ }
+ last := base.Add(time.Duration(rateLimitPerHour) * 3 * time.Second)
+ if wait := spread.admit("CHAT_1", last); wait == 0 {
+ t.Fatalf("send %d was admitted; the per-hour ceiling is %d", rateLimitPerHour+1, rateLimitPerHour)
+ }
+}
+
+// Chats that go quiet must not stay in the map for the life of the process: a
+// bot talks to a new person every day, and each one would keep its timestamps
+// alive forever.
+func TestQuietChatsAreForgotten(t *testing.T) {
+ t.Parallel()
+ q := newSendQuota()
+ base := time.Now()
+ q.admit("CHAT_OLD", base)
+
+ q.admit("CHAT_NEW", base.Add(2*time.Hour))
+
+ q.mu.Lock()
+ _, stillThere := q.sent["CHAT_OLD"]
+ q.mu.Unlock()
+ if stillThere {
+ t.Error("a chat with nothing inside the longest window is still holding memory")
+ }
+}
diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.go
index 2da5283a8b..1920b3263a 100644
--- a/server/internal/integrations/wecom/relay_outbound.go
+++ b/server/internal/integrations/wecom/relay_outbound.go
@@ -1336,11 +1336,18 @@ func (o *Outbound) ownsSocket(installationID string) bool {
// provablyNotSent reports whether a send error is one that certainly occurred
// before any byte could leave. ws_sender marks the boundary itself: a failure
// raised by the write is wrapped in errWriteAttempted, a missing verdict is
-// errAckTimeout, and a stated refusal is a *wecomAPIError — all three mean the
-// peer may have (or, for a refusal, definitely did) see the frame. A bare
-// context error is ambiguous — request() returns one both from its pre-write
-// check and from the post-write wait — so it is treated as possibly sent,
-// which costs an un-retried delivery rather than a duplicate.
+// errAckTimeout, a verdict the caller stopped waiting for is errAckAbandoned,
+// and a stated refusal is a *wecomAPIError — all four mean the peer may have
+// (or, for a refusal, definitely did) see the frame.
+//
+// A bare context error is read the same way, and that is a choice rather than
+// an inability. request() marks the post-write case itself now, so what is
+// left is a cancellation raised before anything was written. Releasing the
+// claim on it would be correct and is deliberately not done here: this is the
+// last gate before the frame is offered to another replica, the two mistakes
+// cost different amounts — an un-retried delivery against a second copy of the
+// answer in the person's chat — and widening what gets re-offered is a change
+// to the relay's retry behaviour, not to how an error is read.
func provablyNotSent(err error) bool {
var apiErr *wecomAPIError
switch {
diff --git a/server/internal/integrations/wecom/send_verdict_test.go b/server/internal/integrations/wecom/send_verdict_test.go
index e8b25c0288..9b0a7475ed 100644
--- a/server/internal/integrations/wecom/send_verdict_test.go
+++ b/server/internal/integrations/wecom/send_verdict_test.go
@@ -7,11 +7,17 @@ package wecom
import (
"errors"
"testing"
+ "time"
)
func TestSendTextReportsAServerRefusal(t *testing.T) {
conn := &recordingConn{refuseCode: 45009, refuseMsg: "rate limit"}
sender := conn.autoAck(newWSSender(conn, nil))
+ // 45009 is a throttle, so this send is retried once (rate_limit.go). The
+ // retry is not what this test is about, but the two seconds it waits for
+ // by default would be: shortened, so the assertion below is the only thing
+ // the test spends time on.
+ sender.retryBackoff = time.Millisecond
err := sender.sendText("CHAT", chatTypeSingleInt, "hello")
if err == nil {
diff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.go
index 5f2e2312ad..91b518bb10 100644
--- a/server/internal/integrations/wecom/ws_sender.go
+++ b/server/internal/integrations/wecom/ws_sender.go
@@ -77,6 +77,13 @@ type wsSender struct {
ackMu sync.Mutex
replies map[string]*replyWaiter
+ // quota holds this connection's aibot_send_msg allowance, per target chat,
+ // and retryBackoff is what a throttled push waits before its one retry.
+ // One quota per socket is the whole accounting — see rate_limit.go for why
+ // that is the right scope and where the numbers come from.
+ quota *sendQuota
+ retryBackoff time.Duration
+
// seq numbers outbound frames in the order they reach the socket.
// Guarded by mu, so it is the wire order by construction, and it is what
// pairs a traced send attempt with its outcome — req_id cannot do that
@@ -89,7 +96,13 @@ func newWSSender(conn wsConn, log *slog.Logger) *wsSender {
if log == nil {
log = slog.Default()
}
- return &wsSender{conn: conn, log: log, replies: make(map[string]*replyWaiter)}
+ return &wsSender{
+ conn: conn,
+ log: log,
+ replies: make(map[string]*replyWaiter),
+ quota: newSendQuota(),
+ retryBackoff: sendRetryBackoff,
+ }
}
// ackTimeout caps the wait for a verdict. WeCom answers in a few hundred
@@ -217,7 +230,13 @@ func (s *wsSender) request(ctx context.Context, cmd string, body map[string]any)
case <-timer.C:
return nil, errAckTimeout
case <-ctx.Done():
- return nil, ctx.Err()
+ // Marked, because this is not the same fact as the context error at
+ // the top of this function. That one is raised before anything is
+ // written; this one is raised after s.write returned without error,
+ // which means WriteMessage completed and the bytes are gone. A caller
+ // that cannot tell the two apart has to guess about a frame that may
+ // be in front of the person right now.
+ return nil, fmt.Errorf("%w: %w", errAckAbandoned, ctx.Err())
}
}
@@ -277,6 +296,23 @@ func (s *wsSender) write(frame map[string]any) error {
// and a caller may report them as definite.
var errWriteAttempted = errors.New("wecom: frame write attempted")
+// errAckAbandoned — the frame went out and the caller's context ended before a
+// verdict came back. errAckTimeout's sibling: the same fact about the wire, a
+// different reason the verdict is missing. It wraps the context error rather
+// than replacing it, so every errors.Is(err, context.Canceled) reader keeps
+// working and the outcome still files as "interrupted".
+//
+// It exists because request returns ctx.Err() from two places that mean
+// opposite things — the check ahead of the write, where nothing left this
+// process, and the wait after it, where the peer may already hold the frame.
+// Until this mark, the two differed only in the line that raised them, which
+// is not something a caller can see. A caller weighing a cancellation against
+// another outcome it already holds then has to read every cancellation the
+// same way, and either one of those readings is wrong. sendMsgFrame is that
+// caller: it holds a refusal WeCom stated for a first frame, and must not let
+// it speak for a second one that is already on the wire.
+var errAckAbandoned = errors.New("wecom: the wait for the verdict was cut short after the frame went out")
+
// sendText pushes an aibot_send_msg (proactive push) with plain text to a
// specific chat. Callers pass channel.ChatType so the aibot chat_type int
// (1=single, 2=group) is decided at the wecom-side boundary, not the
@@ -299,6 +335,5 @@ func (s *wsSender) sendTextCtx(ctx context.Context, chatID string, chatTypeInt i
if err != nil {
return err
}
- _, err = s.request(ctx, cmdSendMsg, body)
- return err
+ return s.sendMsgFrame(ctx, chatID, body)
}