-
Notifications
You must be signed in to change notification settings - Fork 0
/
process_factory.go
97 lines (81 loc) · 1.87 KB
/
process_factory.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
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
package watch
import (
"context"
"io"
"time"
"github.com/liupzmin/weewoe/serialize"
"github.com/liupzmin/weewoe/internal/render"
pb "github.com/liupzmin/weewoe/proto"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
)
type ProcessFactory struct {
serialize.Serializable
conn *grpc.ClientConn
client pb.StateClient
stop chan struct{}
}
func (p ProcessFactory) SendCommand(i int64) error {
_, err := p.client.SendCommand(context.Background(), &pb.Command{
Kind: "process",
ID: i,
})
return err
}
func NewProcessFactory(conn *grpc.ClientConn) *ProcessFactory {
f := &ProcessFactory{
Serializable: serialize.ProcessGob{},
conn: conn,
stop: make(chan struct{}),
}
f.client = pb.NewStateClient(conn)
return f
}
func (p ProcessFactory) Terminate() {
close(p.stop)
}
func (p ProcessFactory) Stream(cat string) <-chan render.Rows {
ch := make(chan render.Rows)
go func() {
Repeat:
ctx, cancel := context.WithCancel(context.Background())
stream, err := p.client.Drain(ctx, &pb.Kind{
Name: cat,
})
if err != nil {
cancel()
time.Sleep(5 * time.Second)
log.Info().Msgf("GRPC Stream Call failed: %s, go to Repeat!", err)
goto Repeat
}
log.Info().Msgf("GRPC Stream Call Successful!")
go func() {
<-p.stop
_ = stream.CloseSend()
cancel()
}()
for {
data, err := stream.Recv()
if err == io.EOF {
log.Info().Msg("end of DrainProcessState, go to Repeat!")
goto Repeat
}
if err != nil {
if stream.Context().Err() == context.Canceled {
log.Info().Msg("DrainProcessState canceled!")
return
}
log.Error().Msgf("DrainProcessState recv failed: %s, go to Repeat!", err)
goto Repeat
}
b, err := p.Decode(data.Content)
if err != nil {
log.Error().Msgf("Decode failed: %s", err)
continue
}
log.Debug().Msgf("receive msg :%+v", b)
ch <- b
}
}()
return ch
}