From d59151d872dc1ce1d1f87b7107ca0472711ed3ae Mon Sep 17 00:00:00 2001 From: zhangzherui Date: Tue, 28 Jul 2026 10:58:01 +0800 Subject: [PATCH] fix(im): recover after leader lock loss --- internal/im/service.go | 21 ++++++++++- internal/im/service_lifecycle_test.go | 53 +++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/internal/im/service.go b/internal/im/service.go index c029c987..f34add79 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -1247,8 +1247,8 @@ func (s *Service) wsLeaderRenewLoop(ctx context.Context, channelID string) { result, err := script.Run(ctx, s.redis, []string{key}, s.instanceID, wsLeaderTTL.Milliseconds()).Int64() if err != nil || result == 0 { logger.Warnf(context.Background(), - "[IM] Lost leadership for channel %s, stopping adapter", channelID) - s.StopChannel(channelID) + "[IM] Lost leadership for channel %s, stopping adapter and scheduling recovery", channelID) + s.handleWSLeadershipLoss(channelID) return } // Still the leader — verify the channel is still active. A @@ -1298,6 +1298,23 @@ func (s *Service) wsLeaderRenewLoop(ctx context.Context, channelID string) { } } +// handleWSLeadershipLoss tears down the adapter that no longer owns its lease +// and puts the enabled channel back into the existing takeover loop. The retry +// loop re-reads the durable channel row before reconnecting, so a concurrent +// delete, disable, or config update cannot resurrect a stale runtime. +func (s *Service) handleWSLeadershipLoss(channelID string) { + _, channel, running := s.GetChannelAdapter(channelID) + if !running || channel == nil { + return + } + + s.StopChannel(channelID) + if s.stopped.Load() { + return + } + s.scheduleWSLeaderRetry(channel) +} + func (s *Service) scheduleWSLeaderRetry(channel *IMChannel) { retryCtx, cancel := context.WithCancel(context.Background()) state := &leaderRetryState{cancel: cancel} diff --git a/internal/im/service_lifecycle_test.go b/internal/im/service_lifecycle_test.go index 41c66d55..3a6ad62c 100644 --- a/internal/im/service_lifecycle_test.go +++ b/internal/im/service_lifecycle_test.go @@ -378,3 +378,56 @@ func TestLeaderElectionFailsClosedWhenRedisUnavailable(t *testing.T) { t.Fatalf("leader retry goroutines = %d, want one per channel", retryCount) } } + +func TestLeadershipLossStopsAdapterAndSchedulesRecovery(t *testing.T) { + db := newLifecycleTestDB(t) + channel := createLifecycleChannel(t, db, "channel-leader-loss", "agent") + channel.Mode = "websocket" + if err := db.Model(&IMChannel{}).Where("id = ?", channel.ID). + Update("mode", channel.Mode).Error; err != nil { + t.Fatalf("persist websocket mode: %v", err) + } + + redisServer := miniredis.RunT(t) + redisClient := redis.NewClient(&redis.Options{Addr: redisServer.Addr()}) + t.Cleanup(func() { _ = redisClient.Close() }) + + counters := &lifecycleFactoryCounters{} + svc := newLifecycleTestService(db, redisClient, "instance-one") + svc.RegisterAdapterFactory("test", counters.factory()) + t.Cleanup(svc.Stop) + + if err := svc.StartChannel(channel); err != nil { + t.Fatalf("start websocket channel: %v", err) + } + if counters.starts.Load() != 1 { + t.Fatalf("factory starts = %d, want 1", counters.starts.Load()) + } + + // Simulate another owner replacing the lease before the next renewal. + key := RedisKeyLeader + channel.ID + redisServer.Set(key, "instance-two") + svc.handleWSLeadershipLoss(channel.ID) + + if _, _, ok := svc.GetChannelAdapter(channel.ID); ok { + t.Fatal("adapter remained active after leadership loss") + } + if counters.stops.Load() != 1 { + t.Fatalf("adapter stops = %d, want 1", counters.stops.Load()) + } + svc.mu.RLock() + retryCount := len(svc.leaderRetries) + svc.mu.RUnlock() + if retryCount != 1 { + t.Fatalf("leader retry goroutines = %d, want one recovery path", retryCount) + } + + // Repeated loss handling after teardown must not create duplicate retries. + svc.handleWSLeadershipLoss(channel.ID) + svc.mu.RLock() + retryCount = len(svc.leaderRetries) + svc.mu.RUnlock() + if retryCount != 1 { + t.Fatalf("leader retry goroutines after duplicate loss = %d, want one", retryCount) + } +}