Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(wecom): tell a refused handshake apart from an unreachable one, on a dashboard (#6626)
Xichang(Seacen) Zhao1fe956eb86d9
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 0ef0243dbe..a251d1bff7 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -343,6 +343,7 @@ func main() {var businessMetrics *obsmetrics.BusinessMetricsvar samplerPool *pgxpool.Poolvar channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics+ var wecomMetrics *obsmetrics.WecomMetricsif metricsConfig.Enabled() {// Build a dedicated tiny pool for the BusinessSamplerCollector// so a stalled scrape can never starve business traffic. If the@@ -371,6 +372,7 @@ func main() {httpMetrics = metricsRegistry.HTTPbusinessMetrics = metricsRegistry.BusinesschannelMediaMetrics = metricsRegistry.ChannelMedia+ wecomMetrics = metricsRegistry.Wecom// Forward inbound daemon WS frames into the per-kind counter so// dashboards can split heartbeat / unknown / invalid traffic.if daemonHub != nil {@@ -397,6 +399,7 @@ func main() {r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{HTTPMetrics: httpMetrics,BusinessMetrics: businessMetrics,+ WecomMetrics: wecomMetrics,DaemonHub: daemonHub,DaemonWakeup: daemonWakeup,FeatureFlags: flags,diff --git a/server/cmd/server/metrics_test.go b/server/cmd/server/metrics_test.goindex 5e06c99978..07ee235bbe 100644--- a/server/cmd/server/metrics_test.go+++ b/server/cmd/server/metrics_test.go@@ -7,6 +7,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/realtime")@@ -21,3 +22,22 @@ func TestMainRouterDoesNotExposePrometheusMetrics(t *testing.T) {t.Fatalf("main API /metrics status = %d, want %d", rec.Code, http.StatusNotFound)}}++// With /metrics off, main.go leaves the *WecomMetrics nil. Assigning that+// pointer straight into the adapter's interface field would produce an+// interface that is not nil while the pointer inside it is, so the adapter's+// own nil check would pass and the first counter call would panic — on the one+// configuration nobody runs in staging.+func TestNilWecomMetricsBecomesANilInterface(t *testing.T) {+ var off *obsmetrics.WecomMetrics+ if got := wecomMetricsOrNil(off); got != nil {+ t.Fatal("a nil *WecomMetrics produced a non-nil interface; the adapter would call through a nil pointer")+ }++ on := obsmetrics.NewWecomMetrics()+ got := wecomMetricsOrNil(on)+ if got == nil {+ t.Fatal("a real sink was dropped")+ }+ got.RecordAuthFailure() // must reach the counter, not a no-op+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ee81652ee3..c2fed60ba6 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -174,9 +174,12 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticstype RouterOptions struct {HTTPMetrics *obsmetrics.HTTPMetricsBusinessMetrics *obsmetrics.BusinessMetrics- DaemonHub *daemonws.Hub- DaemonWakeup service.TaskWakeupNotifier- FeatureFlags *featureflag.Service+ // WecomMetrics is the WeCom adapter's health sink. Nil discards every+ // counter, which is what a deployment with /metrics turned off gets.+ WecomMetrics *obsmetrics.WecomMetrics+ DaemonHub *daemonws.Hub+ DaemonWakeup service.TaskWakeupNotifier+ FeatureFlags *featureflag.Service// HeartbeatScheduler, when non-nil, replaces the default synchronous// passthrough scheduler on the constructed Handler. main.go injects a// BatchedHeartbeatScheduler here so the caller can also drive Run/Stop;@@ -695,6 +698,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Buswecom.RegisterWecom(channelRegistry, wecom.ChannelDeps{Credentials: credsResolver,Senders: wecomSenders,+ Metrics: wecomMetricsOrNil(opts.WecomMetrics),Logger: slog.Default(),})channelRouter.Register(wecom.TypeWecom, wecom.NewResolverSet(@@ -1887,3 +1891,14 @@ func composioCallbackBaseURL(publicURL string) string {}return appURLFromEnv()}++// wecomMetricsOrNil keeps a typed nil out of the adapter's interface field.+// A *WecomMetrics that is nil still satisfies wecom.Metrics, so assigning it+// directly would give the adapter a non-nil interface holding a nil pointer —+// and the first counter call would panic on a deployment with /metrics off.+func wecomMetricsOrNil(m *obsmetrics.WecomMetrics) wecom.Metrics {+ if m == nil {+ return nil+ }+ return m+}diff --git a/server/internal/integrations/wecom/metrics.go b/server/internal/integrations/wecom/metrics.gonew file mode 100644index 0000000000..d8674f3854--- /dev/null+++ b/server/internal/integrations/wecom/metrics.go@@ -0,0 +1,72 @@+package wecom++// metrics.go — the health signals this adapter emits.+//+// Every failure in the connection path degrades quietly by design. A dial that+// fails and a handshake the server refuses hand the connection back to the+// Supervisor for backoff and retry; a full ingest queue parks the read loop+// instead, and the socket stops being drained until the worker catches up.+// Quiet is the right behaviour for the person in front of the chat and the+// wrong behaviour for the operator behind it — nothing on a dashboard changes+// when a bot has been unable to connect for an hour.+//+// The counters here are chosen for what somebody would page on rather than for+// completeness: the connection is not coming up, and if so whether that needs a+// person or just time; and the read loop is being made to wait by an ingest+// worker that cannot keep up.+//+// No installation id anywhere. It is an unbounded identifier and the metrics+// package rejects that class of label outright (forbiddenMetricLabels in+// internal/metrics/labels.go). What attribution exists is in the structured+// logs, and it is not uniform: the two connection counters have it, because+// the failure they count is also returned to the Supervisor, which logs it+// with installation_id. The two inbound counters have nothing beside them —+// a queue that blocks writes no log line at all, so the counter tells an+// operator that some bot is behind and not which one.++// Metrics is the sink this adapter reports to. Every method must tolerate being+// called concurrently, and none of them may block: they run on the read loop.+type Metrics interface {+ // RecordConnectFailure — a dial, a handshake write or a handshake read+ // that did not complete, or a handshake the server answered with a code+ // that classifySubscribeAck could not verify (a throttle, a platform-side+ // failure). Excludes an outright credential rejection, which has its own+ // counter: everything counted here recovers on its own, that one needs an+ // admin.+ RecordConnectFailure()+ // RecordAuthFailure — aibot_subscribe was refused on the credentials, as+ // classifySubscribeAck judges it (ErrCredentialsRejected: 40001 / 40013).+ // Deliberately not every non-zero errcode — the codes that only mean "could+ // not verify" go to RecordConnectFailure, because paging an operator to+ // rotate a good secret costs a second outage. The bot will not connect+ // until somebody fixes the credentials, so a sustained rate here is an+ // alert and not a blip.+ RecordAuthFailure()++ // RecordCallbackQueued — one inbound callback handed to the worker. The+ // baseline every other inbound number is read against.+ RecordCallbackQueued()+ // RecordCallbackQueueBlocked — the worker queue was full and the read+ // loop had to wait. Backpressure, deliberately: it is how a slow ingest+ // stops rather than a message being dropped. A rising rate says the+ // engine is not keeping up with one bot's traffic, and past a point+ // WeCom stops seeing the socket drained and replaces the connection.+ RecordCallbackQueueBlocked()+}++// nopMetrics is what the constructor falls back to. A nil sink must never be a+// nil-pointer dereference on the read loop.+type nopMetrics struct{}++func (nopMetrics) RecordConnectFailure() {}+func (nopMetrics) RecordAuthFailure() {}+func (nopMetrics) RecordCallbackQueued() {}+func (nopMetrics) RecordCallbackQueueBlocked() {}++// orNopMetrics turns an unset sink into one that is safe to call.+func orNopMetrics(m Metrics) Metrics {+ if m == nil {+ return nopMetrics{}+ }+ return m+}diff --git a/server/internal/integrations/wecom/metrics_test.go b/server/internal/integrations/wecom/metrics_test.gonew file mode 100644index 0000000000..1c30368daa--- /dev/null+++ b/server/internal/integrations/wecom/metrics_test.go@@ -0,0 +1,403 @@+package wecom++// metrics_test.go — the counters an operator reads.+//+// These assert the signal fires on the path it claims to describe. A counter+// wired to the wrong branch is worse than no counter: it reads as evidence the+// thing is being watched.++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/gorilla/websocket"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+)++// countingMetrics records every call so a test can assert on the shape of what+// was reported rather than on a number in a registry.+type countingMetrics struct {+ mu sync.Mutex+ counts map[string]int+}++func newCountingMetrics() *countingMetrics {+ return &countingMetrics{counts: map[string]int{}}+}++func (m *countingMetrics) bump(k string) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.counts[k]+++}++func (m *countingMetrics) get(k string) int {+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.counts[k]+}++func (m *countingMetrics) RecordConnectFailure() { m.bump("connect_failure") }+func (m *countingMetrics) RecordAuthFailure() { m.bump("auth_failure") }+func (m *countingMetrics) RecordCallbackQueued() { m.bump("callback_queued") }+func (m *countingMetrics) RecordCallbackQueueBlocked() { m.bump("callback_blocked") }++var _ Metrics = (*countingMetrics)(nil)++// waitFor polls until cond holds or the budget runs out. The read loop runs on+// its own goroutine, so the counter it bumps is observed from here a moment+// after the event that caused it.+func waitFor(t *testing.T, what string, cond func() bool) {+ t.Helper()+ deadline := time.Now().Add(3 * time.Second)+ for time.Now().Before(deadline) {+ if cond() {+ return+ }+ time.Sleep(2 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", what)+}++// A handshake the server refused and a socket that never came up are the two+// causes an operator has to tell apart: the first needs somebody to fix the+// installation and will repeat identically on every backoff until they do, the+// second usually clears on its own. One "cannot connect" number cannot say+// which, so they are counted separately.+func TestARefusedHandshakeIsNotCountedAsAConnectFailure(t *testing.T) {+ t.Parallel()++ mx := newCountingMetrics()+ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error { return nil },+ dialer: scriptedDialer{conn: refusingConn(40001, "invalid credential")},+ wsURL: "wss://example.test/ws",+ metrics: mx,+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ err := c.Connect(ctx)+ if err == nil {+ t.Fatal("Connect succeeded against a server that refused the handshake")+ }+ // The counter and the error the Supervisor receives have to agree about+ // what happened; a counter that says "credentials" while the error says+ // something else is the drift this whole split exists to prevent.+ if !errors.Is(err, ErrCredentialsRejected) {+ t.Fatalf("Connect error = %v, want it to carry ErrCredentialsRejected", err)+ }+ if got := mx.get("auth_failure"); got != 1 {+ t.Fatalf("auth_failure = %d, want the rejection reported as a credential problem", got)+ }+ if got := mx.get("connect_failure"); got != 0 {+ t.Fatalf("connect_failure = %d for a socket that dialled and answered fine", got)+ }+}++// The other half of that verdict. 45009 is a throttle: the bot is fine, WeCom+// is rate-limiting, and classifySubscribeAck answers ErrCredentialsUnverifiable+// rather than ErrCredentialsRejected. The counter has to follow that answer+// instead of testing the errcode itself — an operator paged to rotate a+// perfectly good secret because of a throttle has been sent to cause a second+// outage. This is the case that would regress if somebody re-derived the+// classification beside the counter.+func TestAnUnverifiableHandshakeIsNotCountedAsACredentialFailure(t *testing.T) {+ t.Parallel()++ mx := newCountingMetrics()+ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error { return nil },+ dialer: scriptedDialer{conn: refusingConn(45009, "api freq out of limit")},+ wsURL: "wss://example.test/ws",+ metrics: mx,+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ err := c.Connect(ctx)+ if err == nil {+ t.Fatal("Connect succeeded against a server that refused the handshake")+ }+ if !errors.Is(err, ErrCredentialsUnverifiable) {+ t.Fatalf("Connect error = %v, want it to carry ErrCredentialsUnverifiable", err)+ }+ if got := mx.get("auth_failure"); got != 0 {+ t.Fatalf("auth_failure = %d for a throttle; nobody's credentials are wrong", got)+ }+ if got := mx.get("connect_failure"); got != 1 {+ t.Fatalf("connect_failure = %d, want the unverifiable ack counted on the side that clears on its own", got)+ }+}++// The other side of the same split: a dial that never lands is infrastructure,+// and must not show up as a credential problem — an operator who rotates a+// perfectly good secret because of it has been sent the wrong way.+func TestADialThatNeverLandsIsAConnectFailure(t *testing.T) {+ t.Parallel()++ mx := newCountingMetrics()+ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error { return nil },+ dialer: failingDialer{err: errors.New("dial tcp: connection refused")},+ wsURL: "wss://example.test/ws",+ metrics: mx,+ }++ if err := c.Connect(context.Background()); err == nil {+ t.Fatal("Connect succeeded with a dialer that always fails")+ }+ if got := mx.get("connect_failure"); got != 1 {+ t.Fatalf("connect_failure = %d, want the failed dial reported", got)+ }+ if got := mx.get("auth_failure"); got != 0 {+ t.Fatalf("auth_failure = %d for a socket that never opened; nobody's credentials are wrong", got)+ }+}++// A handshake that is written and then never answered is the same class as a+// failed dial. It is the one the subscribeTimeout produces, and it is the one+// most likely to be misread as "the secret is wrong".+func TestAHandshakeThatIsNeverAnsweredIsAConnectFailure(t *testing.T) {+ t.Parallel()++ mx := newCountingMetrics()+ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error { return nil },+ dialer: scriptedDialer{conn: &silentSubscribeConn{}},+ wsURL: "wss://example.test/ws",+ metrics: mx,+ }++ if err := c.Connect(context.Background()); err == nil {+ t.Fatal("Connect succeeded against a server that never acked the handshake")+ }+ if got := mx.get("connect_failure"); got != 1 {+ t.Fatalf("connect_failure = %d, want the unanswered handshake reported", got)+ }+ if got := mx.get("auth_failure"); got != 0 {+ t.Fatalf("auth_failure = %d for a handshake the server never answered either way", got)+ }+}++// Backpressure is invisible from the outside: the read loop parks, the socket+// stops being drained, and the only outward sign is a connection WeCom+// eventually replaces. It has to be a number before it is an incident.+func TestAFullIngestQueueIsReportedAsBackpressure(t *testing.T) {+ t.Parallel()++ // One frame the worker holds, callbackQueueDepth more to fill the buffer,+ // and one that finds it full.+ total := callbackQueueDepth + 2+ frames := make([][]byte, 0, total)+ for i := 0; i < total; 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.+ // Every later one returns immediately.+ var calls atomic.Int32+ release := make(chan struct{})++ mx := newCountingMetrics()+ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error {+ if calls.Add(1) == 1 {+ <-release+ }+ return nil+ },+ dialer: scriptedDialer{conn: conn},+ wsURL: "wss://example.test/ws",+ metrics: mx,+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() { done <- c.Connect(ctx) }()++ waitFor(t, "the read loop to report a full ingest queue", func() bool {+ return mx.get("callback_blocked") >= 1+ })+ // The buffer really did fill, and the frames still outstanding are held by+ // a parked read loop rather than dropped. (Whether the worker had already+ // taken the first frame when the buffer filled is a race, so the count at+ // this instant is one of two values, not one.)+ queuedWhileBlocked := mx.get("callback_queued")+ if queuedWhileBlocked < callbackQueueDepth {+ t.Fatalf("callback_queued = %d when the queue reported full, want at least %d", queuedWhileBlocked, callbackQueueDepth)+ }+ if queuedWhileBlocked >= total {+ t.Fatalf("callback_queued = %d while the read loop is parked; it cannot have handed over all %d", queuedWhileBlocked, total)+ }++ close(release)+ waitFor(t, "the queue to drain", func() bool {+ return mx.get("callback_queued") == total+ })++ cancel()+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("Connect did not return after ctx cancel")+ }+}++// A channel built without a sink must not be a nil-pointer dereference on the+// read loop. This is the deployment with /metrics turned off, which is the one+// least likely to be exercised anywhere else.+func TestAChannelWithNoSinkStillRuns(t *testing.T) {+ t.Parallel()++ c := &wecomChannel{+ installationID: mustTestUUID(t),+ botID: "bot-1",+ secret: "secret-1",+ handler: func(context.Context, channel.InboundMessage) error { return nil },+ dialer: scriptedDialer{conn: refusingConn(40001, "invalid credential")},+ wsURL: "wss://example.test/ws",+ }+ if err := c.Connect(context.Background()); err == nil {+ t.Fatal("Connect succeeded against a server that refused the handshake")+ }+}++// The factory is the other way a nil sink reaches the read loop, and it has to+// substitute the no-op rather than store the nil.+func TestTheFactorySubstitutesTheNoOpSink(t *testing.T) {+ t.Parallel()++ factory := newWecomFactory(ChannelDeps{Credentials: fixedCredentials{}})+ ch, err := factory(channel.Config{+ ID: mustTestUUID(t),+ Raw: []byte(`{"bot_id":"bot-1"}`),+ Handler: func(context.Context, channel.InboundMessage) error { return nil },+ })+ if err != nil {+ t.Fatalf("factory: %v", err)+ }+ wc, ok := ch.(*wecomChannel)+ if !ok {+ t.Fatalf("factory returned %T, want *wecomChannel", ch)+ }+ if wc.metrics == nil {+ t.Fatal("factory stored a nil sink; the read loop would dereference it")+ }+ wc.metrics.RecordConnectFailure() // must not panic+}++// fixedCredentials is a CredentialsResolver that hands back whatever bot id the+// installation config carried, with no decryption.+type fixedCredentials struct{}++func (fixedCredentials) Credentials(inst Installation) (InstallationCredentials, error) {+ return InstallationCredentials{BotID: inst.BotID, Secret: "secret-1"}, nil+}++// rejectingSubscribeConn completes the handshake exchange and answers it with+// the errcode it was built with.+type rejectingSubscribeConn struct {+ errCode int+ errMsg string+ mu sync.Mutex+ ack []byte+ unblock chan struct{}+ closeOne sync.Once+}++// refusingConn answers the handshake with one WeCom errcode. Which counter+// that lands on is classifySubscribeAck's decision, which is the whole point+// of driving these tests through a real code rather than a bool.+func refusingConn(code int, msg string) *rejectingSubscribeConn {+ return &rejectingSubscribeConn{errCode: code, errMsg: msg}+}++func (c *rejectingSubscribeConn) WriteMessage(_ int, data []byte) error {+ var env frameEnvelope+ if err := json.Unmarshal(data, &env); err == nil && env.Cmd == cmdSubscribe {+ ack, _ := json.Marshal(frameEnvelope{+ Headers: frameHeaders{ReqID: env.Headers.ReqID},+ ErrCode: c.errCode,+ ErrMsg: c.errMsg,+ })+ c.mu.Lock()+ c.ack = ack+ c.mu.Unlock()+ }+ return nil+}++func (c *rejectingSubscribeConn) ReadMessage() (int, []byte, error) {+ c.mu.Lock()+ if c.ack != nil {+ ack := c.ack+ c.ack = nil+ c.mu.Unlock()+ return websocket.TextMessage, ack, nil+ }+ c.mu.Unlock()+ return 0, nil, errors.New("closed")+}++func (c *rejectingSubscribeConn) SetReadDeadline(time.Time) error { return nil }+func (c *rejectingSubscribeConn) SetWriteDeadline(time.Time) error { return nil }+func (c *rejectingSubscribeConn) Close() error {+ c.closeOne.Do(func() {+ if c.unblock != nil {+ close(c.unblock)+ }+ })+ return nil+}++// silentSubscribeConn accepts the handshake write and then never answers —+// the socket the subscribeTimeout exists for.+type silentSubscribeConn struct{}++func (silentSubscribeConn) WriteMessage(int, []byte) error { return nil }+func (silentSubscribeConn) ReadMessage() (int, []byte, error) {+ return 0, nil, errors.New("i/o timeout")+}+func (silentSubscribeConn) SetReadDeadline(time.Time) error { return nil }+func (silentSubscribeConn) SetWriteDeadline(time.Time) error { return nil }+func (silentSubscribeConn) Close() error { return nil }++// failingDialer never opens a socket.+type failingDialer struct{ err error }++func (d failingDialer) DialContext(context.Context, string, http.Header) (wsConn, *http.Response, error) {+ return nil, nil, d.err+}diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.goindex 67d9e8d4d2..3b291c6ae4 100644--- a/server/internal/integrations/wecom/wecom_channel.go+++ b/server/internal/integrations/wecom/wecom_channel.go@@ -81,12 +81,26 @@ type wecomChannel struct {// itself on entry and clear on exit. nil in tests that don't exercise// the OutboundReplier path.senders *sendersRegistry+ // metrics is the health sink (metrics.go). Never read directly — go+ // through mx(), which substitutes the no-op sink for a channel built+ // without one.+ metrics Metrics}var _ channel.Channel = (*wecomChannel)(nil)func (c *wecomChannel) Type() channel.Type { return TypeWecom }+// mx returns a sink that is always safe to call. Tests construct+// wecomChannel literals without one, and a deployment with /metrics off+// wires nil deliberately.+func (c *wecomChannel) mx() Metrics {+ if c.metrics == nil {+ return nopMetrics{}+ }+ return c.metrics+}+// Capabilities declares what the aibot adapter supports today. Text is the// only fully wired capability; attachments arrive as MsgTypeImage / File /// Audio / Video but we do not yet download the media (WeCom's aibot API@@ -135,6 +149,7 @@ func (c *wecomChannel) Connect(ctx context.Context) (err error) {conn, _, err := dialer.DialContext(ctx, wsURL, nil)if err != nil {+ c.mx().RecordConnectFailure()return fmt.Errorf("wecom: dial %s: %w", wsURL, err)}defer conn.Close()@@ -284,6 +299,18 @@ func (c *wecomChannel) Connect(ctx context.Context) (err error) {case cmdMsgCallback, cmdEventCallback:select {case callbacks <- env:+ c.mx().RecordCallbackQueued()+ continue+ default:+ // The worker is behind. Blocking is the deliberate choice+ // (see below), and it is also the thing an operator wants to+ // know about — from here on the socket stops being drained,+ // and if it lasts, WeCom replaces the connection.+ c.mx().RecordCallbackQueueBlocked()+ }+ select {+ case callbacks <- env:+ c.mx().RecordCallbackQueued()case <-cbDone:// The worker has stopped, so this send has no receiver — and// no closer either: the queue is closed by a defer that@@ -337,6 +364,7 @@ func (c *wecomChannel) subscribe(ctx context.Context, conn wsConn, sender *wsSen"headers": frameHeaders{ReqID: reqID},"body": subscribeBody(c.botID, c.secret),}); err != nil {+ c.mx().RecordConnectFailure()return fmt.Errorf("wecom: send subscribe: %w", err)}@@ -352,6 +380,13 @@ func (c *wecomChannel) subscribe(ctx context.Context, conn wsConn, sender *wsSen}typ, payload, err := conn.ReadMessage()if err != nil {+ // The socket died, the ack never arrived inside+ // subscribeTimeout, or our own ctx was cancelled mid-read and+ // the watchdog closed the socket under us. Infrastructure or a+ // shutdown — nobody has to be told either way, and the next+ // backoff may well succeed. A rolling restart therefore adds a+ // few counts here; the rate matters, a handful does not.+ c.mx().RecordConnectFailure()return fmt.Errorf("wecom: subscribe read: %w", err)}if typ != websocket.TextMessage && typ != websocket.BinaryMessage {@@ -369,7 +404,28 @@ func (c *wecomChannel) subscribe(ctx context.Context, conn wsConn, sender *wsSencontinue}if env.ErrCode != 0 {- return classifySubscribeAck(log, env.ErrCode, env.ErrMsg)+ // Which of the two counters this is depends on what the ack+ // means, and classifySubscribeAck already decides that — the+ // same verdict the install-time credential probe gets. Branch on+ // its answer rather than testing the errcode again here: a+ // second copy of rejectionErrCodes would be free to drift from+ // the probe's, and then the dashboard and the install screen+ // would disagree about the same code.+ err := classifySubscribeAck(log, env.ErrCode, env.ErrMsg)+ if errors.Is(err, ErrCredentialsRejected) {+ // Refused on its merits: a wrong secret, a deleted bot.+ // Counted apart from every other connection failure because+ // it is the only one that repeats identically on every+ // backoff until a person changes something.+ c.mx().RecordAuthFailure()+ } else {+ // Unverifiable — a throttle, or a platform-side failure.+ // It clears on its own, exactly like a dial that did not+ // land, so it belongs on that counter and not on the one an+ // operator reads as "go rotate a credential".+ c.mx().RecordConnectFailure()+ }+ return err}return nil}@@ -527,6 +583,11 @@ type ChannelDeps struct {// constructor. Nil in tests that don't exercise outbound.Senders *sendersRegistry+ // Metrics is the health sink every built channel reports through. Nil+ // discards every counter, which is what a deployment with /metrics+ // turned off gets.+ Metrics Metrics+// Dialer overrides the default gorilla dialer. Tests point it at an// httptest server; production leaves this nil.Dialer Dialer@@ -577,6 +638,7 @@ func newWecomFactory(deps ChannelDeps) channel.Factory {wsURL: deps.WSURL,logger: logger,senders: deps.Senders,+ metrics: orNopMetrics(deps.Metrics),}, nil}}diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.goindex 34842ae5c2..63853ace6b 100644--- a/server/internal/metrics/registry.go+++ b/server/internal/metrics/registry.go@@ -31,6 +31,7 @@ type Registry struct {HTTP *HTTPMetricsBusiness *BusinessMetricsChannelMedia *ChannelMediaReconcilerMetrics+ Wecom *WecomMetrics// Sampler is non-nil only when RegistryOptions.BusinessSampler was// supplied with a valid Pool. Exposed so the cmd/server entrypoint// can plumb the same instance into health checks if it ever wants to.@@ -58,6 +59,9 @@ func NewRegistry(opts RegistryOptions) *Registry {channelMedia := NewChannelMediaReconcilerMetrics()reg.MustRegister(channelMedia.Collectors()...)+ wecomMetrics := NewWecomMetrics()+ reg.MustRegister(wecomMetrics.Collectors()...)+if opts.Pool != nil {reg.MustRegister(NewDBCollector(opts.Pool))}@@ -78,6 +82,7 @@ func NewRegistry(opts RegistryOptions) *Registry {HTTP: httpMetrics,Business: businessMetrics,ChannelMedia: channelMedia,+ Wecom: wecomMetrics,Sampler: sampler,}}diff --git a/server/internal/metrics/wecom.go b/server/internal/metrics/wecom.gonew file mode 100644index 0000000000..5820d8542d--- /dev/null+++ b/server/internal/metrics/wecom.go@@ -0,0 +1,72 @@+package metrics++import "github.com/prometheus/client_golang/prometheus"++// WecomMetrics is the production sink behind the WeCom adapter's Metrics+// interface (server/internal/integrations/wecom/metrics.go).+//+// The adapter is built to degrade quietly. A dial that fails and a handshake+// the server refuses both yield the connection back to the Supervisor, which+// backs off and tries again; an ingest queue the read loop has to wait on+// yields nothing and simply stops draining the socket until the worker+// catches up. None of the three changes anything an operator can see. A bot+// that has been down since Tuesday and a bot nobody happened to message today+// produce the same silence.+//+// The two connection counters are deliberately separate. A dial or a read that+// fails is infrastructure and usually recovers on its own; a handshake the+// server refuses on its merits is a wrong secret or a deleted bot, and it will+// repeat identically on every backoff until a person fixes the installation.+// Summed into one number the operator cannot tell "wait" from "rotate the+// credential".+//+// Which side of that line an ack falls on is classifySubscribeAck's call, in+// the adapter, and this package only counts the verdict. An ack it cannot+// verify — a throttle, a platform-side failure — is a connect failure, on the+// "wait" side, because rotating a credential that was fine costs a second+// outage.+//+// No installation_id label anywhere. It is the same class of unbounded+// identifier as workspace_id and session_id, which forbiddenMetricLabels+// rejects outright. Attribution falls to the structured logs and is uneven+// there: the two connection failures reach the Supervisor as a returned error+// and are logged with installation_id, while a blocked ingest queue is+// counted and nothing else — the counter says some bot is behind, not which.+type WecomMetrics struct {+ ConnectFailures prometheus.Counter+ AuthFailures prometheus.Counter+ CallbacksQueued prometheus.Counter+ CallbackQueueBlocked prometheus.Counter+}++func NewWecomMetrics() *WecomMetrics {+ counter := func(name, help string) prometheus.Counter {+ return prometheus.NewCounter(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "wecom", Name: name, Help: help,+ })+ }+ return &WecomMetrics{+ ConnectFailures: counter("connect_failures_total",+ "Long-connection attempts that failed for a reason nobody has to act on: the socket never came up, or the server answered the handshake with a code that only means it could not verify the bot (a throttle, a platform-side failure). Excludes credential rejections, which are counted apart."),+ AuthFailures: counter("auth_failures_total",+ "Long-connection handshakes the server refused on the credentials themselves (WeCom errcode 40001 / 40013). The bot stays down until somebody fixes the installation."),+ CallbacksQueued: counter("inbound_callbacks_total",+ "Inbound callbacks handed to the ingest worker. The baseline every other inbound number is read against."),+ CallbackQueueBlocked: counter("inbound_queue_blocked_total",+ "Times the read loop had to wait on a full ingest queue. Backpressure by design; a rising rate means the engine is behind and the socket is about to stop being drained."),+ }+}++func (m *WecomMetrics) Collectors() []prometheus.Collector {+ return []prometheus.Collector{+ m.ConnectFailures, m.AuthFailures,+ m.CallbacksQueued, m.CallbackQueueBlocked,+ }+}++// ---- the adapter's Metrics interface ----++func (m *WecomMetrics) RecordConnectFailure() { m.ConnectFailures.Inc() }+func (m *WecomMetrics) RecordAuthFailure() { m.AuthFailures.Inc() }+func (m *WecomMetrics) RecordCallbackQueued() { m.CallbacksQueued.Inc() }+func (m *WecomMetrics) RecordCallbackQueueBlocked() { m.CallbackQueueBlocked.Inc() }diff --git a/server/internal/metrics/wecom_test.go b/server/internal/metrics/wecom_test.gonew file mode 100644index 0000000000..df03dba79b--- /dev/null+++ b/server/internal/metrics/wecom_test.go@@ -0,0 +1,159 @@+package metrics++import (+ "testing"++ "github.com/prometheus/client_golang/prometheus"+ dto "github.com/prometheus/client_model/go"+)++// Every collector has to be registrable together. A duplicate name or a+// malformed help string only surfaces at MustRegister, which in production is+// process start.+func TestWecomMetricsRegisterCleanly(t *testing.T) {+ reg := prometheus.NewRegistry()+ for _, c := range NewWecomMetrics().Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register: %v", err)+ }+ }+}++// The adapter's Metrics interface and this implementation must not drift. The+// compile-time check lives in the adapter; this one catches a method that+// exists but does nothing.+func TestEveryWecomCounterActuallyCounts(t *testing.T) {+ reg := prometheus.NewRegistry()+ m := NewWecomMetrics()+ for _, c := range m.Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register: %v", err)+ }+ }++ m.RecordConnectFailure()+ m.RecordAuthFailure()+ m.RecordCallbackQueued()+ m.RecordCallbackQueueBlocked()++ seen := gatherWecomValues(t, reg)+ for _, want := range []string{+ "multica_wecom_connect_failures_total",+ "multica_wecom_auth_failures_total",+ "multica_wecom_inbound_callbacks_total",+ "multica_wecom_inbound_queue_blocked_total",+ } {+ if seen[want] != 1 {+ t.Errorf("%s = %v, want 1 — the counter is wired to nothing", want, seen[want])+ }+ }+}++// The whole point of two connection counters is that an operator can tell a+// wrong secret from a dead network. Sharing a series would put them back to+// guessing.+func TestAuthAndConnectFailuresAreSeparateSeries(t *testing.T) {+ reg := prometheus.NewRegistry()+ m := NewWecomMetrics()+ for _, c := range m.Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register: %v", err)+ }+ }++ m.RecordAuthFailure()+ m.RecordAuthFailure()+ m.RecordConnectFailure()++ seen := gatherWecomValues(t, reg)+ if got := seen["multica_wecom_auth_failures_total"]; got != 2 {+ t.Errorf("auth failures = %v, want 2", got)+ }+ if got := seen["multica_wecom_connect_failures_total"]; got != 1 {+ t.Errorf("connect failures = %v, want 1", got)+ }+}++// No metric here may carry an unbounded identifier as a label — the same rule+// labels.go enforces for the rest of the codebase. installation_id is the one+// that would be tempting to add, and it belongs in the logs instead. Those+// carry it for the two connection failures, which reach the Supervisor as a+// returned error; the two inbound counters have no log line beside them, so+// leaving the label off really does cost the answer to "which bot" on those+// two. That is the trade this test pins, not a free win.+func TestWecomMetricsCarryNoUnboundedLabels(t *testing.T) {+ reg := prometheus.NewRegistry()+ m := NewWecomMetrics()+ for _, c := range m.Collectors() {+ if err := reg.Register(c); err != nil {+ t.Fatalf("register: %v", err)+ }+ }+ m.RecordConnectFailure()+ m.RecordAuthFailure()+ m.RecordCallbackQueued()+ m.RecordCallbackQueueBlocked()++ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather: %v", err)+ }+ for _, f := range families {+ for _, metric := range f.GetMetric() {+ for _, l := range metric.GetLabel() {+ if _, forbidden := forbiddenMetricLabels[l.GetName()]; forbidden {+ t.Errorf("%s carries the unbounded label %q", f.GetName(), l.GetName())+ }+ if l.GetName() == "installation_id" {+ t.Errorf("%s labels by installation_id; that belongs in the logs", f.GetName())+ }+ }+ }+ }+}++// The registry is what production actually scrapes; a collector that is built+// but never registered exports nothing.+func TestTheRegistryExposesTheWecomCounters(t *testing.T) {+ r := NewRegistry(RegistryOptions{})+ if r.Wecom == nil {+ t.Fatal("Registry.Wecom is nil; nothing can report through it")+ }+ r.Wecom.RecordAuthFailure()++ families, err := r.Gatherer.Gather()+ if err != nil {+ t.Fatalf("gather: %v", err)+ }+ for _, f := range families {+ if f.GetName() == "multica_wecom_auth_failures_total" {+ return+ }+ }+ t.Fatal("multica_wecom_auth_failures_total is not on the registry the metrics server scrapes")+}++func gatherWecomValues(t *testing.T, reg prometheus.Gatherer) map[string]float64 {+ t.Helper()+ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("gather: %v", err)+ }+ out := map[string]float64{}+ for _, f := range families {+ for _, metric := range f.GetMetric() {+ out[f.GetName()] = wecomValueOf(metric)+ }+ }+ return out+}++func wecomValueOf(m *dto.Metric) float64 {+ if c := m.GetCounter(); c != nil {+ return c.GetValue()+ }+ if g := m.GetGauge(); g != nil {+ return g.GetValue()+ }+ return 0+}