Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(im): handle disabled channels in IM callback and improve connection lifecycle management

wizardchen9714eaa9a73e
diff --git a/internal/handler/im.go b/internal/handler/im.go
index d04818a54..64268fa52 100644
--- a/internal/handler/im.go
+++ b/internal/handler/im.go
@@ -376,6 +376,11 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
+ if errors.Is(err, im.ErrChannelDisabled) {
+ logger.Errorf(ctx, "[IM] Channel disabled for callback: %s", channelID)
+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel is disabled"})
+ return
+ }
logger.Errorf(ctx, "[IM] Channel unavailable for callback %s: %v", channelID, err)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel not available"})
return
diff --git a/internal/im/service.go b/internal/im/service.go
index 26eb0230a..c029c9870 100644
--- a/internal/im/service.go
+++ b/internal/im/service.go
@@ -353,6 +353,10 @@ const (
defaultRateLimitMaxRequests = 10
)
+// ErrChannelDisabled reports that a channel row exists but is disabled, so
+// callers can tell it apart from a missing channel or a transient failure.
+var ErrChannelDisabled = errors.New("channel is disabled")
+
// channelState holds runtime state for a running IM channel.
type channelState struct {
Channel *IMChannel
@@ -1116,6 +1120,20 @@ func (s *Service) startChannelInternal(channel *IMChannel, factory AdapterFactor
}
s.mu.Lock()
+ // Stop() may have drained the channel map while the factory was connecting
+ // above, since the factory runs unlocked. Re-check under the lock, otherwise
+ // this adapter's long connection would outlive process shutdown.
+ if s.stopped.Load() {
+ s.mu.Unlock()
+ if leaderCancel != nil {
+ leaderCancel()
+ }
+ if cancelFn != nil {
+ cancelFn()
+ }
+ s.releaseWSLeader(channel.ID)
+ return fmt.Errorf("im service is stopped")
+ }
// Idempotency: another goroutine may have started this channel while
// factory was running above (factory is called unlocked). Stop the old
// state before overwriting so its adapter / long connection doesn't leak.
@@ -1505,7 +1523,7 @@ func (s *Service) EnsureChannelAdapter(channelID string) (Adapter, *IMChannel, e
}
if !fresh.Enabled {
s.StopChannel(channelID)
- return nil, fresh, fmt.Errorf("channel is disabled")
+ return nil, fresh, ErrChannelDisabled
}
adapter, cached, ok := s.GetChannelAdapter(channelID)
diff --git a/internal/im/service_lifecycle_test.go b/internal/im/service_lifecycle_test.go
index 934835e5c..41c66d558 100644
--- a/internal/im/service_lifecycle_test.go
+++ b/internal/im/service_lifecycle_test.go
@@ -280,6 +280,50 @@ func TestServiceStopIsIdempotent(t *testing.T) {
}
}
+// A factory can block for seconds while dialing, so Stop() may drain the
+// channel map after StartChannel's pre-flight check but before registration.
+// The adapter created in that window must be torn down instead of outliving
+// shutdown with an open connection.
+func TestStartChannelDoesNotLeakAdapterWhenStoppedDuringFactory(t *testing.T) {
+ db := newLifecycleTestDB(t)
+ channel := createLifecycleChannel(t, db, "channel-stop-race", "agent")
+ counters := &lifecycleFactoryCounters{}
+ svc := newLifecycleTestService(db, nil, "instance-one")
+
+ factoryEntered := make(chan struct{})
+ releaseFactory := make(chan struct{})
+ inner := counters.factory()
+ svc.RegisterAdapterFactory("test", func(
+ ctx context.Context,
+ ch *IMChannel,
+ handler func(context.Context, *IncomingMessage) error,
+ ) (Adapter, context.CancelFunc, error) {
+ close(factoryEntered)
+ <-releaseFactory
+ return inner(ctx, ch, handler)
+ })
+
+ startErr := make(chan error, 1)
+ go func() { startErr <- svc.StartChannel(channel) }()
+
+ <-factoryEntered
+ svc.Stop()
+ close(releaseFactory)
+
+ if err := <-startErr; err == nil {
+ t.Fatal("StartChannel() succeeded even though the service was stopped")
+ }
+ if _, _, ok := svc.GetChannelAdapter(channel.ID); ok {
+ t.Fatal("adapter was registered after shutdown")
+ }
+ if counters.starts.Load() != 1 {
+ t.Fatalf("factory starts = %d, want 1", counters.starts.Load())
+ }
+ if counters.stops.Load() != 1 {
+ t.Fatalf("cleanup calls = %d, want 1 so the connection is not leaked", counters.stops.Load())
+ }
+}
+
func TestSameChannelRuntimeConfigUsesSemanticCredentials(t *testing.T) {
now := time.Now()
cached := &IMChannel{
diff --git a/internal/im/wecom/longconn.go b/internal/im/wecom/longconn.go
index addd6b41c..f038b7e56 100644
--- a/internal/im/wecom/longconn.go
+++ b/internal/im/wecom/longconn.go
@@ -43,6 +43,12 @@ const (
// heartbeat pong) before treating the connection as dead. Set to 3× heartbeat
// interval so a single missed pong does not cause a spurious reconnect.
readTimeout = 3 * defaultHeartbeatInterval
+
+ // writeTimeout bounds a single frame write. Without it a stalled peer can
+ // block a write while holding c.mu, which in turn blocks Stop() and — since
+ // the IM service tears channels down while holding its own channel-map lock
+ // — every other channel operation in the process.
+ writeTimeout = 10 * time.Second
)
// wsFrame is the JSON frame exchanged over the WeCom bot WebSocket.
@@ -775,6 +781,7 @@ func (c *LongConnClient) writeJSON(v interface{}) error {
if c.conn == nil {
return fmt.Errorf("connection closed")
}
+ _ = c.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
return c.conn.WriteJSON(v)
}