fix(im): recover after leader lock loss

main
zhangzherui 2026-07-28 10:58:01 +08:00 committed by lyingbug
parent 0f8232b7eb
commit d59151d872
2 changed files with 72 additions and 2 deletions

View File

@ -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}

View File

@ -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)
}
}