-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathiteration.go
61 lines (53 loc) · 1.36 KB
/
iteration.go
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
package mtg
import (
"context"
"database/sql"
)
const (
IterationActionAdd = 11
IterationActionRemove = 12
)
// a node joins or leaves the group with an iteration
// this is for the evolution mechanism of MTG
// TODO not implemented yet
type Iteration struct {
Action int
NodeId string
Threshold int
CreatedAt uint64
}
var iterationCols = []string{"action", "node_id", "threshold", "created_at"}
func (i *Iteration) values() []any {
return []any{i.Action, i.NodeId, i.Threshold, i.CreatedAt}
}
func iterationFromRow(row Row) (*Iteration, error) {
var i Iteration
err := row.Scan(&i.Action, &i.NodeId, &i.Threshold, &i.CreatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
return &i, err
}
func (grp *Group) AddNode(ctx context.Context, id string, threshold int, epoch uint64) error {
ir := &Iteration{
Action: IterationActionAdd,
NodeId: id,
Threshold: threshold,
CreatedAt: epoch,
}
return grp.store.WriteIteration(ctx, ir)
}
func (grp *Group) ListActiveNodes(ctx context.Context) ([]string, int, uint64, error) {
irs, err := grp.store.ListIterations(ctx)
var actives []string
for _, ir := range irs {
if ir.Action == IterationActionAdd {
actives = append(actives, ir.NodeId)
}
}
if err != nil || len(actives) == 0 {
return nil, 0, 0, err
}
last := irs[len(irs)-1]
return actives, last.Threshold, last.CreatedAt, nil
}