-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_chat_ingest.go
124 lines (101 loc) · 2.34 KB
/
client_chat_ingest.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
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
package seabird
import (
"context"
"errors"
"sync"
"time"
"github.com/seabird-chat/seabird-go/pb"
"google.golang.org/grpc"
)
type ChatIngestClient struct {
grpcChannel *grpc.ClientConn
Inner pb.ChatIngestClient
}
func NewChatIngestClient(seabirdCoreUrl, seabirdCoreToken string) (*ChatIngestClient, error) {
grpcChannel, err := newGRPCClient(seabirdCoreUrl, seabirdCoreToken)
if err != nil {
return nil, err
}
return &ChatIngestClient{
grpcChannel: grpcChannel,
Inner: pb.NewChatIngestClient(grpcChannel),
}, nil
}
func (c *ChatIngestClient) Close() error {
return c.grpcChannel.Close()
}
func (c *ChatIngestClient) IngestEvents(backendType, backendID string) (*SeabirdChatIngestStream, error) {
ctx, cancel := context.WithCancel(context.Background())
inner, err := c.Inner.IngestEvents(ctx)
if err != nil {
cancel()
return nil, err
}
// Send the proper hello event to get things started
err = inner.Send(&pb.ChatEvent{
Inner: &pb.ChatEvent_Hello{
Hello: &pb.HelloChatEvent{
BackendInfo: &pb.Backend{
Type: backendType,
Id: backendID,
},
},
},
})
if err != nil {
cancel()
return nil, err
}
// Because our input channel will drop events, we make sure it's buffered in
// case some come in while we're handling messages.
in := make(chan *pb.ChatRequest, 10)
// Make sure the channel is buffered so we can store a value.
errChan := make(chan error, 1)
s := &SeabirdChatIngestStream{
inner: inner,
cancelFunc: cancel,
errChan: errChan,
C: in,
}
go func() {
done := ctx.Done()
for {
event, err := inner.Recv()
if err != nil {
select {
case errChan <- err:
default:
}
close(in)
return
}
select {
case in <- event:
case <-done:
}
}
}()
return s, nil
}
type SeabirdChatIngestStream struct {
sendLock sync.Mutex
inner pb.ChatIngest_IngestEventsClient
cancelFunc func()
cancelOnce sync.Once
errChan chan error
C <-chan *pb.ChatRequest
}
func (s *SeabirdChatIngestStream) Send(event *pb.ChatEvent) error {
s.sendLock.Lock()
defer s.sendLock.Unlock()
return s.inner.Send(event)
}
func (s *SeabirdChatIngestStream) Close() error {
s.cancelOnce.Do(s.cancelFunc)
select {
case err := <-s.errChan:
return err
case <-time.After(1 * time.Second):
return errors.New("timeout when closing")
}
}