-
Notifications
You must be signed in to change notification settings - Fork 1
/
slave.go
62 lines (55 loc) · 1.13 KB
/
slave.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 Onyx
import (
"context"
pb "github.com/go-gems/Onyx/stream"
"github.com/google/uuid"
"google.golang.org/grpc"
"io"
"log"
)
type Slave struct {
Id string
*connectionCollection
*actionCollection
}
func NewSlave() *Slave {
s := &Slave{
Id: uuid.New().String(),
connectionCollection: newConnectionCollection(),
actionCollection: newActionCollection(),
}
s.On("_", func(slave *Stream, in *IncomingMessage) error {
return nil
})
return s
}
func (s Slave) Join(masterAddress string) error {
conn, err := grpc.Dial(masterAddress, grpc.WithInsecure())
if err != nil {
return err
}
client := pb.NewStreamServiceClient(conn)
stream, err := client.Connect(context.Background())
if err != nil {
return err
}
go func() {
for {
instruction, err := stream.Recv()
if err == io.EOF || instruction == nil {
debugPrintln("empty instruction")
log.Println(err)
}
master := s.fetchOrCreate(instruction.From, s.Id, nil, stream)
if err != nil {
log.Fatalln(err)
return
}
if err = s.do(master, instruction)
err != nil {
log.Fatalln(err)
}
}
}()
return nil
}