From 5b62dff074a0ef52c9ba1bb87ced6947d9bf6782 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sat, 20 May 2023 00:37:27 +0300 Subject: can test clean expiry --- internal/quorum.go | 39 +++++++++++++++++++++++++++++++-------- internal/quorum_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 internal/quorum_test.go (limited to 'internal') diff --git a/internal/quorum.go b/internal/quorum.go index 1c8e451..964d465 100644 --- a/internal/quorum.go +++ b/internal/quorum.go @@ -2,6 +2,7 @@ package internal import ( "log" + "sort" ) type quorumMap map[string]vote @@ -17,15 +18,37 @@ func (q quorumMap) vote(v vote) { } func (q quorumMap) score() (scores []score) { - /* - scoreMap := make(map[string]int) - var expired []string + q.cleanExpired() + scoreMap := make(map[string]int) - for from, vote := range q { - - for _, id := range vote.ids { - } + for _, vote := range q { + for _, id := range vote.ids { + score, _ := scoreMap[id] + scoreMap[id] = score + 1 } - */ + } + + for id, score_ := range scoreMap { + scores = append(scores, score{id, score_}) + } + + sort.Slice(scores, func(i, j int) bool { + return scores[i].score < scores[j].score + }) + return } + +func (q quorumMap) cleanExpired() { + var expired []string + + for from, vote := range q { + if vote.expired() { + expired = append(expired, from) + } + } + + for _, e := range expired { + delete(q, e) + } +} diff --git a/internal/quorum_test.go b/internal/quorum_test.go new file mode 100644 index 0000000..80c4598 --- /dev/null +++ b/internal/quorum_test.go @@ -0,0 +1,28 @@ +package internal + +import ( + "testing" + "time" +) + +func TestCleanExpired(t *testing.T) { + quorum := make(quorumMap) + config := config{Participants: []string{"foo:1234", "bay:4321"}} + + vote1 := newVote(config, "earth:334234", " foo bar baz bay\n") + vote1.expiresAt = time.Now().Add(1 * time.Hour) + quorum.vote(vote1) + + vote2 := newVote(config, "bay:334234", " foo bar baz bay\n") + vote2.expiresAt = time.Now() + quorum.vote(vote2) + + if len(quorum) != 2 { + t.Errorf("Expected to have two votes before expiry: %v", quorum) + } + + quorum.cleanExpired() + if len(quorum) != 1 { + t.Errorf("Expected to have only one vote after expiry: %v", quorum) + } +} -- cgit v1.2.3