summaryrefslogtreecommitdiff
path: root/internal/quorum/quorum.go
blob: d730fed262b2b3d61d5b0e6f195b1bf7246c3f86 (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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package quorum

import (
	"context"
	"log"
	"sort"
	"strconv"
	"strings"
	"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
}

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, <-chan string) {
	voteCh := make(chan vote.Vote)
	scoreCh := make(chan string)

	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(voteCh)
		defer close(scoreCh)

		var (
			myVote  vote.Vote
			changed bool
		)

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

	return voteCh, scoreCh
}

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) scores() (scores Scores) {
	scoreMap := make(map[string]int)

	for _, vote := range quo.votes {
		if vote.Expired() {
			continue
		}
		for _, id := range vote.IDs {
			score := scoreMap[id]
			priority, err := quo.conf.NodePriority(id)
			if err != nil {
				log.Println(err)
				scoreMap[id] = score
				continue
			}
			scoreMap[id] = 10*score + priority
		}
	}

	for id, score_ := range scoreMap {
		scores = append(scores, Score{id, score_, time.Now()})
	}

	sort.Slice(scores, func(i, j int) bool {
		return scores[i].Value > scores[j].Value
	})

	return
}

func (quo *Quorum) strs() string {
	scores := quo.scores()
	log.Println("quorum scores:", scores)
	winner, err := scores.Winner()
	if err != nil {
		log.Println("the winner is", winner.ID)
	}

	var sb strings.Builder

	for i, score := range scores {
		sb.WriteString("At position ")
		sb.WriteString(strconv.Itoa(i + 1))

		if score.ID == quo.conf.MyID {
			sb.WriteString(" is current node ")
		} else {
			sb.WriteString(" is partner node ")
		}
		sb.WriteString(score.ID)

		sb.WriteString(" (priority ")
		priority, _ := quo.conf.NodePriority(score.ID)
		sb.WriteString(strconv.Itoa(priority))

		sb.WriteString(") with total score of ")
		sb.WriteString(strconv.Itoa(score.Value))

		sb.WriteString("\n")
	}

	return sb.String()
}

func (quo *Quorum) makeMyVote() (vote.Vote, bool) {
	newVote, err := quo.expireOldVotes()
	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) expireOldVotes() (vote.Vote, error) {
	var expired []string
	var live []string

	for fromNode, vote := range quo.votes {
		if vote.Expired() {
			log.Println("quorum: vote", vote, "from node", fromNode, "expired!")
			expired = append(expired, fromNode)
			continue
		}
		live = append(live, fromNode)
	}

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

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