-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
subscribeToEventsWithCurrentState.go
209 lines (193 loc) · 6.86 KB
/
subscribeToEventsWithCurrentState.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package client
import (
"context"
"fmt"
"sync"
"time"
"github.com/plgd-dev/hub/v2/grpc-gateway/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
type GrpcGateway_SubscribeToEventsClient struct {
subClient pb.GrpcGateway_SubscribeToEventsClient
grpcClient pb.GrpcGatewayClient
deduplicateExpiration time.Duration
events []*pb.Event
removeSubs sync.Map
newSubs sync.Map
subs sync.Map
}
// Header returns the header metadata received from the server if there
// is any. It blocks if the metadata is not ready to read.
func (c *GrpcGateway_SubscribeToEventsClient) Header() (metadata.MD, error) {
return c.subClient.Header()
}
// Trailer returns the trailer metadata from the server, if there is any.
// It must only be called after stream.CloseAndRecv has returned, or
// stream.Recv has returned a non-nil error (including io.EOF).
func (c *GrpcGateway_SubscribeToEventsClient) Trailer() metadata.MD {
return c.subClient.Trailer()
}
// CloseSend closes the send direction of the stream. It closes the stream
// when non-nil error is met. It is also not safe to call CloseSend
// concurrently with SendMsg.
func (c *GrpcGateway_SubscribeToEventsClient) CloseSend() error {
return c.subClient.CloseSend()
}
// Context returns the context for this stream.
//
// It should not be called until after Header or RecvMsg has returned. Once
// called, subsequent client-side retries are disabled.
func (c *GrpcGateway_SubscribeToEventsClient) Context() context.Context {
return c.subClient.Context()
}
// SendMsg is generally called by generated code. On error, SendMsg aborts
// the stream. If the error was generated by the client, the status is
// returned directly; otherwise, io.EOF is returned and the status of
// the stream may be discovered using RecvMsg.
//
// SendMsg blocks until:
// - There is sufficient flow control to schedule m with the transport, or
// - The stream is done, or
// - The stream breaks.
//
// SendMsg does not wait until the message is received by the server. An
// untimely stream closure may result in lost messages. To ensure delivery,
// users should ensure the RPC completed successfully using RecvMsg.
//
// It is safe to have a goroutine calling SendMsg and another goroutine
// calling RecvMsg on the same stream at the same time, but it is not safe
// to call SendMsg on the same stream in different goroutines. It is also
// not safe to call CloseSend concurrently with SendMsg.
func (c *GrpcGateway_SubscribeToEventsClient) SendMsg(m interface{}) error {
req, ok := m.(*pb.SubscribeToEvents)
if !ok {
return fmt.Errorf("invalid type('%T')", m)
}
if req.GetCreateSubscription() != nil {
_, ok := c.subs.Load(req.GetCorrelationId())
if ok {
return fmt.Errorf("duplicit correlationID(%v)", req.GetCorrelationId())
}
_, ok = c.newSubs.Load(req.GetCorrelationId())
if ok {
return fmt.Errorf("duplicit correlationID(%v)", req.GetCorrelationId())
}
sub := NewSub(c.subClient.Context(), c.grpcClient, c.send, req.GetCorrelationId(), c.deduplicateExpiration, req.GetCreateSubscription())
c.newSubs.Store(req.GetCorrelationId(), sub)
}
if req.GetCancelSubscription() != nil {
c.removeSubs.Store(req.GetCancelSubscription().GetSubscriptionId(), true)
}
return c.subClient.SendMsg(m)
}
func copyEvent(dst, src *pb.Event) {
dst.CorrelationId = src.GetCorrelationId()
dst.SubscriptionId = src.GetSubscriptionId()
dst.Type = src.GetType()
}
func (c *GrpcGateway_SubscribeToEventsClient) handleRecvEventOperationProcessed(event *pb.Event) {
ev := event.GetOperationProcessed()
s, ok := c.newSubs.LoadAndDelete(event.GetCorrelationId())
if !ok {
if _, ok := c.removeSubs.LoadAndDelete(event.GetSubscriptionId()); ok {
c.subs.Delete(event.GetSubscriptionId())
}
return
}
if ev.GetErrorStatus().GetCode() != pb.Event_OperationProcessed_ErrorStatus_OK {
return
}
sub := s.(*Sub)
err := sub.Init(event.GetSubscriptionId())
if err != nil {
ev.ErrorStatus = &pb.Event_OperationProcessed_ErrorStatus{
Code: pb.Event_OperationProcessed_ErrorStatus_ERROR,
Message: err.Error(),
}
return
}
c.subs.Store(event.GetSubscriptionId(), sub)
}
// RecvMsg blocks until it receives a message into m or the stream is
// done. It returns io.EOF when the stream completes successfully. On
// any other error, the stream is aborted and the error contains the RPC
// status.
//
// It is safe to have a goroutine calling SendMsg and another goroutine
// calling RecvMsg on the same stream at the same time, but it is not
// safe to call RecvMsg on the same stream in different goroutines.
//
// When new devices appear, it retrieves all current state of filtered events.
// And for that, duplication of an event can occur.
func (c *GrpcGateway_SubscribeToEventsClient) RecvMsg(m interface{}) error {
for {
if len(c.events) > 0 {
ev := c.events[0]
c.events = c.events[1:]
event := m.(*pb.Event)
copyEvent(event, ev)
return nil
}
start := time.Now()
event := new(pb.Event)
err := c.subClient.RecvMsg(event)
if err != nil {
return err
}
timeDiff := time.Since(start)
eventOrig := m.(*pb.Event)
copyEvent(eventOrig, event)
switch event.GetType().(type) {
case *pb.Event_OperationProcessed_:
c.handleRecvEventOperationProcessed(event)
return nil
case *pb.Event_SubscriptionCanceled_:
c.subs.Delete(event.GetSubscriptionId())
return nil
default:
s, ok := c.subs.Load(event.GetSubscriptionId())
if !ok {
return nil
}
sub := s.(*Sub)
if timeDiff > time.Second {
sub.DropDeduplicateEvents()
}
err := sub.ProcessEvent(event)
if err != nil {
return err
}
continue
}
}
}
func (c *GrpcGateway_SubscribeToEventsClient) Send(m *pb.SubscribeToEvents) error {
return c.SendMsg(m)
}
func (c *GrpcGateway_SubscribeToEventsClient) Recv() (*pb.Event, error) {
m := new(pb.Event)
if err := c.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *GrpcGateway_SubscribeToEventsClient) send(event *pb.Event) error {
c.events = append(c.events, event)
return nil
}
// SubscribeToEventsWithCurrentState creates subscribe to events with included the current state.
// It can provide duplicity events when lots of events are in the batch. The deduplicate is driven by deduplicateExpiration argument.
// Subscription doesn't guarantee that all events will be sent to the client. The client is responsible for synchronizing events.
func (c *Client) SubscribeToEventsWithCurrentState(ctx context.Context, deduplicateExpiration time.Duration, opts ...grpc.CallOption) (pb.GrpcGateway_SubscribeToEventsClient, error) {
subClient, err := c.gateway.SubscribeToEvents(ctx, opts...)
if err != nil {
return subClient, err
}
return &GrpcGateway_SubscribeToEventsClient{
subClient: subClient,
grpcClient: c.gateway,
deduplicateExpiration: deduplicateExpiration,
events: make([]*pb.Event, 0, 1024),
}, nil
}