From 7e33bdc70eb397882fbe989fee1fa00385335917 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sat, 20 May 2023 01:35:31 +0300 Subject: can determine the winner --- internal/quorum.go | 9 +++++++++ internal/quorum_test.go | 10 ++++++++++ internal/run.go | 7 +++++++ 3 files changed, 26 insertions(+) (limited to 'internal') diff --git a/internal/quorum.go b/internal/quorum.go index 032ebc8..b506bfb 100644 --- a/internal/quorum.go +++ b/internal/quorum.go @@ -1,6 +1,7 @@ package internal import ( + "fmt" "log" "sort" ) @@ -17,6 +18,14 @@ func (q quorumMap) vote(v vote) { q[v.from] = v } +func (q quorumMap) winner(config config) (string, error) { + scores := q.score(config) + if len(scores) == 0 { + return "", fmt.Errorf("unable to find a winner, empty score list") + } + return scores[0].id, nil +} + func (q quorumMap) score(config config) (scores []score) { q.cleanExpired() scoreMap := make(map[string]int) diff --git a/internal/quorum_test.go b/internal/quorum_test.go index da2abdd..d4790f9 100644 --- a/internal/quorum_test.go +++ b/internal/quorum_test.go @@ -64,6 +64,11 @@ func TestTieScore(t *testing.T) { if scores[0].id != "foo" || scores[0].score != 3 { t.Errorf("Expected score[0] to be {foo,3}: %v", scores[0]) } + + winner, _ := quorum.winner(config) + if winner != "foo" { + t.Errorf("Expected the winner to be foo but is: %s", winner) + } }) t.Run("Second tie score test", func(t *testing.T) { @@ -80,6 +85,11 @@ func TestTieScore(t *testing.T) { if scores[0].id != "bar" || scores[0].score != 3 { t.Errorf("Expected score[0] to be {bar,3}: %v", scores[0]) } + + winner, _ := quorum.winner(config) + if winner != "bar" { + t.Errorf("Expected the winner to be bar but is: %s", winner) + } }) } diff --git a/internal/run.go b/internal/run.go index 8b7faa9..8f73b19 100644 --- a/internal/run.go +++ b/internal/run.go @@ -2,6 +2,7 @@ package internal import ( "context" + "log" ) func Run(ctx context.Context, configFile string) { @@ -18,6 +19,12 @@ func Run(ctx context.Context, configFile string) { select { case vote := <-ch: quorum.vote(vote) + winner, err := quorum.winner(config) + if err != nil { + log.Println(err.Error()) + continue + } + log.Printf("The current leader node is %s", winner) case <-ctx.Done(): return } -- cgit v1.2.3