This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
event_stream.go
101 lines (81 loc) · 1.92 KB
/
event_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
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
package gateway
import (
"context"
"sync"
"github.com/golang/protobuf/proto"
"google.golang.org/grpc/metadata"
)
// ChaincodeEventServerStream implements gRPC server stream interfaces
type ChaincodeEventServerStream struct {
context context.Context
events chan *ChaincodeEvent
ready bool
opts []EventOpt
once sync.Once
}
func NewChaincodeEventServerStream(ctx context.Context, opts ...EventOpt) (stream *ChaincodeEventServerStream) {
stream = &ChaincodeEventServerStream{
context: ctx,
events: make(chan *ChaincodeEvent),
ready: true,
opts: opts,
}
go func() {
<-ctx.Done()
stream.Close()
}()
return stream
}
func (*ChaincodeEventServerStream) SetHeader(metadata.MD) error {
return nil
}
func (*ChaincodeEventServerStream) SendHeader(metadata.MD) error {
return nil
}
func (*ChaincodeEventServerStream) SetTrailer(metadata.MD) {
}
func (s *ChaincodeEventServerStream) Context() context.Context {
return s.context
}
func (s *ChaincodeEventServerStream) send(e *ChaincodeEvent) error {
if !s.ready {
return ErrEventChannelClosed
}
for _, o := range s.opts {
if err := o(e); err != nil {
return err
}
}
select {
case <-s.context.Done():
return s.context.Err()
case s.events <- e:
}
return nil
}
func (s *ChaincodeEventServerStream) SendMsg(m interface{}) error {
return s.send(proto.Clone(m.(*ChaincodeEvent)).(*ChaincodeEvent))
}
func (s *ChaincodeEventServerStream) Recv(e *ChaincodeEvent) error {
return s.recv(e)
}
func (s *ChaincodeEventServerStream) RecvMsg(m interface{}) error {
return s.recv(m.(*ChaincodeEvent))
}
func (s *ChaincodeEventServerStream) recv(ev *ChaincodeEvent) error {
_ = ev
if e, ok := <-s.events; ok {
ev = e
_ = ev
return nil
}
return ErrEventChannelClosed
}
func (s *ChaincodeEventServerStream) Events() <-chan *ChaincodeEvent {
return s.events
}
func (s *ChaincodeEventServerStream) Close() {
s.once.Do(func() {
s.ready = false
})
}