-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstream.go
58 lines (44 loc) · 968 Bytes
/
stream.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
package messaging
import (
"sync"
"time"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
messagingpb "github.com/code-payments/code-protobuf-api/generated/go/messaging/v1"
)
type messageStream struct {
sync.Mutex
closed bool
streamCh chan *messagingpb.Message
}
func newMessageStream(bufferSize int) *messageStream {
return &messageStream{
streamCh: make(chan *messagingpb.Message, bufferSize),
}
}
func (s *messageStream) notify(msg *messagingpb.Message, timeout time.Duration) error {
m := proto.Clone(msg).(*messagingpb.Message)
s.Lock()
if s.closed {
s.Unlock()
return errors.New("cannot notify closed stream")
}
select {
case s.streamCh <- m:
case <-time.After(timeout):
s.Unlock()
s.close()
return errors.New("timed out sending message to streamCh")
}
s.Unlock()
return nil
}
func (s *messageStream) close() {
s.Lock()
defer s.Unlock()
if s.closed {
return
}
s.closed = true
close(s.streamCh)
}