summaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2023-05-20 01:35:31 +0300
committerPaul Buetow <paul@buetow.org>2023-05-20 01:35:31 +0300
commit7e33bdc70eb397882fbe989fee1fa00385335917 (patch)
treebfa10c6eb41f60fbb879950f9c6e489ee3dc6a52 /internal
parent62f88b8d92b3358213f9af765422f871494ed93b (diff)
can determine the winner
Diffstat (limited to 'internal')
-rw-r--r--internal/quorum.go9
-rw-r--r--internal/quorum_test.go10
-rw-r--r--internal/run.go7
3 files changed, 26 insertions, 0 deletions
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
}