Skip to content

Commit

Permalink
fix: continue leader failed should close leader component (#56)
Browse files Browse the repository at this point in the history
* fix: continue leader failed should close leader component

* test: add case for LeaderChangeHandler
  • Loading branch information
yannan authored May 20, 2024
1 parent 6ddfd94 commit 6e8a32c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion fastflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ func (l *LeaderChangedHandler) Handle(cxt context.Context, e goevent.Event) {
log.Println("leader initial")
}
// continue leader failed
if !lcEvent.IsLeader && len(l.leaderCloser) == 0 {
if !lcEvent.IsLeader && len(l.leaderCloser) != 0 {
l.Close()
}
}
Expand Down
47 changes: 47 additions & 0 deletions fastflow_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package fastflow

import (
"context"
"fmt"
"testing"
"time"

"github.com/shiningrush/fastflow/pkg/entity"
"github.com/shiningrush/fastflow/pkg/event"
"github.com/shiningrush/fastflow/pkg/mod"
"github.com/shiningrush/fastflow/pkg/utils"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -190,3 +192,48 @@ tasks:
})
}
}

func Test_LeaderChangeHandler(t *testing.T) {
tests := []struct {
isLeader bool
calledEnsured []bool
closerLenth int
}{
{
isLeader: true,
calledEnsured: []bool{},
closerLenth: 1,
},
{
isLeader: false,
calledEnsured: []bool{true},
closerLenth: 0,
},
}

for _, tc := range tests {
called := []bool{}
keeper := &mod.MockKeeper{}
handler := &LeaderChangedHandler{
opt: &InitialOption{
Keeper: keeper,
},
leaderCloser: []mod.Closer{},
}

closer := &mod.MockCloser{}
closer.On("Close").Run(func(args mock.Arguments) {
called = append(called, true)
}).Return(nil)
handler.leaderCloser = append(handler.leaderCloser, closer)

mockEvent := &event.LeaderChanged{IsLeader: tc.isLeader, WorkerKey: "worker-key"}
ctx := context.Background()

// Simulate the event that leads to leadership
handler.Handle(ctx, mockEvent)

assert.Equal(t, tc.calledEnsured, called)
assert.Equal(t, tc.closerLenth, len(handler.leaderCloser))
}
}

0 comments on commit 6e8a32c

Please sign in to comment.