-
Notifications
You must be signed in to change notification settings - Fork 56
/
invocation_service.go
299 lines (277 loc) · 8 KB
/
invocation_service.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
* Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package invocation
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/hazelcast/hazelcast-go-client/hzerrors"
"github.com/hazelcast/hazelcast-go-client/internal/cb"
"github.com/hazelcast/hazelcast-go-client/internal/event"
"github.com/hazelcast/hazelcast-go-client/internal/logger"
"github.com/hazelcast/hazelcast-go-client/internal/proto"
)
var (
serviceSubID = event.NextSubscriptionID()
stateSubID = event.NextSubscriptionID()
)
type Handler interface {
Invoke(invocation Invocation) (groupID int64, err error)
}
type Service struct {
handler Handler
requestCh chan Invocation
responseCh chan *proto.ClientMessage
doneCh chan struct{}
groupLostCh chan *GroupLostEvent
invocations map[int64]Invocation
urgentRequestCh chan Invocation
eventDispatcher *event.DispatchService
// removeCh carries correlationIDs to be removed
removeCh chan int64
executor *stripeExecutor
logger logger.LogAdaptor
stateMu *sync.RWMutex
running bool
paused int32
}
func NewService(handler Handler, ed *event.DispatchService, lg logger.LogAdaptor) *Service {
s := &Service{
requestCh: make(chan Invocation),
urgentRequestCh: make(chan Invocation),
responseCh: make(chan *proto.ClientMessage),
removeCh: make(chan int64),
doneCh: make(chan struct{}),
groupLostCh: make(chan *GroupLostEvent),
invocations: map[int64]Invocation{},
handler: handler,
eventDispatcher: ed,
logger: lg,
stateMu: &sync.RWMutex{},
running: true,
executor: newStripeExecutor(),
}
s.eventDispatcher.Subscribe(EventGroupLost, serviceSubID, func(event event.Event) {
go func() {
select {
case s.groupLostCh <- event.(*GroupLostEvent):
return
case <-s.doneCh:
return
}
}()
})
s.executor.start()
go s.processIncoming()
return s
}
func (s *Service) Stop() {
s.stateMu.Lock()
defer s.stateMu.Unlock()
if !s.running {
return
}
s.running = false
s.executor.stop()
close(s.doneCh)
}
func (s *Service) SetHandler(handler Handler) {
s.handler = handler
}
func (s *Service) SendRequest(ctx context.Context, inv Invocation) error {
if atomic.LoadInt32(&s.paused) == 1 {
err := fmt.Errorf("non-urgent invocations are paused: %w", hzerrors.ErrRetryableIO)
if time.Now().After(inv.Deadline()) {
return cb.WrapNonRetryableError(err)
}
return err
}
select {
case <-ctx.Done():
return cb.WrapNonRetryableError(fmt.Errorf("sending invocation: %w", ctx.Err()))
case <-s.doneCh:
return cb.WrapNonRetryableError(fmt.Errorf("sending invocation: %w", hzerrors.ErrClientNotActive))
case s.requestCh <- inv:
return nil
}
}
func (s *Service) SendUrgentRequest(ctx context.Context, inv Invocation) error {
select {
case <-ctx.Done():
return fmt.Errorf("sending urgent invocation: %w", ctx.Err())
case <-s.doneCh:
return cb.WrapNonRetryableError(fmt.Errorf("sending urgent invocation: %w", hzerrors.ErrClientNotActive))
case s.urgentRequestCh <- inv:
return nil
}
}
func (s *Service) WriteResponse(msg *proto.ClientMessage) error {
select {
case <-s.doneCh:
return cb.WrapNonRetryableError(fmt.Errorf("writing response: %w", hzerrors.ErrClientNotActive))
case s.responseCh <- msg:
return nil
}
}
func (s *Service) Remove(correlationID int64) error {
select {
case <-s.doneCh:
return cb.WrapNonRetryableError(fmt.Errorf("removing correlation: %w", hzerrors.ErrClientNotActive))
case s.removeCh <- correlationID:
return nil
}
}
// Pause stops invoking non-urgent invocations.
func (s *Service) Pause(paused bool) {
var p int32
if paused {
p = 1
}
s.stateMu.Lock()
if !s.running {
return
}
atomic.StoreInt32(&s.paused, p)
if p == 1 {
s.logger.Debug(func() string {
return "invocation.Service: disabled non-urgent invocations"
})
} else {
s.logger.Debug(func() string {
return "invocation.Service: enabled non-urgent invocations"
})
}
s.stateMu.Unlock()
}
func (s *Service) processIncoming() {
loop:
for {
select {
case inv := <-s.requestCh:
s.sendInvocation(inv)
case inv := <-s.urgentRequestCh:
s.sendInvocation(inv)
case msg := <-s.responseCh:
s.handleClientMessage(msg)
case id := <-s.removeCh:
s.removeCorrelationID(id)
case e := <-s.groupLostCh:
s.handleGroupLost(e)
case <-s.doneCh:
break loop
}
}
// remove invocations
for _, invocation := range s.invocations {
invocation.Close()
}
s.invocations = nil
}
func (s *Service) sendInvocation(invocation Invocation) {
s.logger.Trace(func() string {
return fmt.Sprintf("invocation.Service.sendInvocation correlationID: %d", invocation.Request().CorrelationID())
})
s.registerInvocation(invocation)
corrID := invocation.Request().CorrelationID()
gid, err := s.handler.Invoke(invocation)
if err != nil {
s.handleError(corrID, err)
return
}
invocation.SetGroup(gid)
}
func (s *Service) handleClientMessage(msg *proto.ClientMessage) {
correlationID := msg.CorrelationID()
if msg.Err != nil {
s.handleError(correlationID, msg.Err)
return
}
if msg.HasEventFlag() || msg.HasBackupEventFlag() {
if inv, found := s.invocations[correlationID]; !found {
s.logger.Trace(func() string {
return fmt.Sprintf("invocation with unknown correlation ID: %d", correlationID)
})
} else if inv.EventHandler() != nil {
handler := func() {
inv.EventHandler()(msg)
}
partitionID := msg.PartitionID()
// no specific partition (-1) are dispatched randomly in dispatch func.
ok := s.executor.dispatch(int(partitionID), handler)
if !ok {
s.logger.Warnf("event could not be processed, corresponding queue is full. PartitionID: %d, CorrelationID: %d", partitionID, correlationID)
}
}
return
}
if inv := s.unregisterInvocation(correlationID); inv != nil {
inv.Complete(msg)
} else {
s.logger.Trace(func() string {
return fmt.Sprintf("no invocation found with the correlation ID: %d", correlationID)
})
}
}
func (s *Service) removeCorrelationID(id int64) {
delete(s.invocations, id)
}
func (s *Service) handleError(correlationID int64, invocationErr error) {
if inv := s.unregisterInvocation(correlationID); inv != nil {
s.logger.Trace(func() string {
return fmt.Sprintf("error invoking %d: %s", correlationID, invocationErr)
})
if time.Now().After(inv.Deadline()) {
invocationErr = cb.WrapNonRetryableError(invocationErr)
}
inv.Complete(&proto.ClientMessage{Err: invocationErr})
} else {
s.logger.Trace(func() string {
return fmt.Sprintf("cannot handle error: no invocation found with correlation id: %d (%s)", correlationID, invocationErr.Error())
})
}
}
func (s *Service) registerInvocation(invocation Invocation) {
message := invocation.Request()
if message == nil {
panic("message loaded from invocation request is nil")
}
message.SetPartitionId(invocation.PartitionID())
s.invocations[message.CorrelationID()] = invocation
}
func (s *Service) unregisterInvocation(correlationID int64) Invocation {
if invocation, ok := s.invocations[correlationID]; ok {
if invocation.EventHandler() == nil {
// invocations with event handlers are removed with RemoveListener functions
s.removeCorrelationID(correlationID)
}
return invocation
}
return nil
}
func (s *Service) handleGroupLost(e *GroupLostEvent) {
s.stateMu.RLock()
defer s.stateMu.RUnlock()
if !s.running {
return
}
for corrID, inv := range s.invocations {
if inv.Group() == e.GroupID && !inv.Request().HasEventFlag() {
s.handleError(corrID, e.Err)
}
}
}