summaryrefslogtreecommitdiff
path: root/internal/quorum/quorum.go
blob: cb8f01e0d51c8da64a9a9fd087a1df9b24c8b36f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package quorum

import (
	"context"
	"log"
	"sort"
	"time"

	"codeberg.org/snonux/gorum/internal/config"
	"codeberg.org/snonux/gorum/internal/vote"
)

type Quorum struct {
	conf config.Config
	// My own vote, sending to the partners
	myVote vote.Vote

	// From partners received votes
	voteCh chan vote.Vote
	votes  map[string]vote.Vote
}

type Score struct {
	ID    string
	Value int
}

func New(conf config.Config) Quorum {
	return Quorum{
		conf:   conf,
		votes:  make(map[string]vote.Vote),
		voteCh: make(chan vote.Vote),
	}
}

func (quo Quorum) Start(ctx context.Context) <-chan vote.Vote {
	ch := make(chan vote.Vote)

	interval := time.Second * time.Duration(quo.conf.LoopIntervalS)
	if vote.Expiry <= interval {
		log.Fatal("quorum: LoopIntervalS ", quo.conf.LoopIntervalS,
			" should be less than the vote expiry of ", vote.Expiry)
	}

	go func() {
		defer close(ch)

		for {
			select {
			case <-time.After(interval):
				myVote, _ := quo.makeMyVote()
				log.Println("quorum: made my vote:", myVote)
				ch <- myVote
			case v := <-quo.voteCh:
				quo.vote(v)
				if myVote, changed := quo.makeMyVote(); changed {
					log.Println("quorum: changed my vote:", myVote)
					ch <- myVote
				}
				quo.score()
			case <-ctx.Done():
				return
			}
		}
	}()

	return ch
}

func (quo Quorum) Vote(v vote.Vote) {
	log.Printf("quorum: queing vote %v", v)
	quo.voteCh <- v
}

func (quo Quorum) vote(v vote.Vote) {
	log.Printf("quorum: adding vote %v", v)
	quo.votes[v.FromID] = v
}

func (quo Quorum) score() (scores []Score) {
	scoreMap := make(map[string]int)

	for _, vote := range quo.votes {
		if vote.Expired() {
			continue
		}
		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 {
		if scores[i].Value != scores[j].Value {
			return scores[i].Value > scores[j].Value
		}

		// Score tie, use node number.
		i_, _ := quo.conf.NodeNumber(scores[i].ID)
		j_, _ := quo.conf.NodeNumber(scores[j].ID)
		return i_ < j_
	})

	log.Println("quorum: scores are ", scores)
	return
}

func (quo *Quorum) makeMyVote() (vote.Vote, bool) {
	newVote, err := quo.pruneVotes()
	if err != nil {
		log.Println("quorum:", err)
		return quo.myVote, false
	}

	if quo.myVote.Equal(newVote) {
		return quo.myVote, false
	}

	quo.myVote = newVote
	return quo.myVote, true
}

func (quo Quorum) pruneVotes() (vote.Vote, error) {
	var expired []string
	var live []string

	for fromNode, vote := range quo.votes {
		if vote.Expired() {
			expired = append(expired, fromNode)
			continue
		}
		live = append(live, fromNode)
	}

	for _, e := range expired {
		delete(quo.votes, e)
	}

	return vote.New(quo.conf, live)
}