summaryrefslogtreecommitdiff
path: root/internal/client/client.go
blob: f05fcbac67241ef50f19c2aae985f6b73df3efc4 (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
package client

import (
	"context"
	"log"
	"time"

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

func Start(ctx context.Context, conf config.Config, myVoteCh <-chan vote.Vote) {
	log.Println("client: starting")
	fanOut := make([]chan vote.Vote, len(conf.Nodes))

	nodeNum := 0
	for _, node := range conf.Nodes {
		fanOut[nodeNum] = startConnection(ctx, node.Hostname)
		nodeNum++
	}

	go func() {
		defer func() {
			for _, ch := range fanOut {
				close(ch)
			}
		}()

		for {
			select {
			case myVote := <-myVoteCh:
				log.Printf("client: notifying live nodes %v to all partner nodes", myVote)
				for _, ch := range fanOut {
					// First, clear previous element of the channel, if any
					select {
					case <-ch:
					default:
					}
					// Now, update channel with the new live nodes.
					ch <- myVote
				}
			case <-ctx.Done():
				return
			}
		}
	}()
}

func startConnection(ctx context.Context, node string) chan vote.Vote {
	ch := make(chan vote.Vote, 1)

	go func() {
		for {
			log.Println("client: starting connection", node)
			if err := tcpClientRun(ctx, node, ch); err != nil {
				log.Println("client: not connected to node", node, "anymore:", err)
			}

			select {
			case <-time.After(time.Second * 10):
			case <-ctx.Done():
				return
			}
		}
	}()

	return ch
}