-
Notifications
You must be signed in to change notification settings - Fork 12
/
message_endpoint.go
294 lines (244 loc) · 7.44 KB
/
message_endpoint.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
/*
* Copyright 2018 De-labtory
*
* 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
*
* https://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 swim
import (
"errors"
"sync"
"time"
"github.com/DE-labtory/iLogger"
"github.com/DE-labtory/swim/pb"
"github.com/gogo/protobuf/proto"
)
var ErrSendTimeout = errors.New("Error send timeout")
var ErrUnreachable = errors.New("Error this shouldn't reach")
var ErrInvalidMessage = errors.New("Error invalid message")
var ErrCallbackCollectIntervalNotSpecified = errors.New("Error callback collect interval should be specified")
// callback is called when target member sent back to local member a message
// created field is for clean up the old callback
type callback struct {
fn func(msg pb.Message)
created time.Time
}
// responseHandler manages callback functions
type responseHandler struct {
callbacks map[string]callback
collectInterval time.Duration
lock sync.RWMutex
}
func newResponseHandler(collectInterval time.Duration) *responseHandler {
h := &responseHandler{
callbacks: make(map[string]callback),
collectInterval: collectInterval,
lock: sync.RWMutex{},
}
go h.collectGarbageCallback()
return h
}
func (r *responseHandler) addCallback(seq string, cb callback) {
r.lock.Lock()
defer r.lock.Unlock()
r.callbacks[seq] = cb
}
// Handle, each time other member sent back
// a message, callback matching message's seq is called
func (r *responseHandler) handle(msg pb.Message) {
r.lock.Lock()
defer r.lock.Unlock()
seq := msg.Id
cb, exist := r.callbacks[seq]
if exist == false {
iLogger.Error(nil, "Panic, no matching callback function")
}
cb.fn(msg)
delete(r.callbacks, seq)
}
func (r *responseHandler) hasCallback(seq string) bool {
r.lock.RLock()
defer r.lock.RUnlock()
for s := range r.callbacks {
if seq == s {
return true
}
}
return false
}
// collectCallback every time callbackCollectInterval expired clean up
// the old (time.now - callback.created > time interval) callback delete from map
// callbackCollectInterval specified in config
func (r *responseHandler) collectGarbageCallback() {
timeout := r.collectInterval
T := time.NewTicker(timeout)
for {
select {
case <-T.C:
for seq, cb := range r.callbacks {
if time.Now().Sub(cb.created) > timeout {
delete(r.callbacks, seq)
}
}
}
}
}
type MessageEndpoint interface {
Listen()
SyncSend(addr string, msg pb.Message) (pb.Message, error)
Send(addr string, msg pb.Message) error
Shutdown()
}
type MessageEndpointConfig struct {
EncryptionEnabled bool
SendTimeout time.Duration
// callbackCollect Interval indicate time interval to clean up old
// callback function
CallbackCollectInterval time.Duration
}
// MessageEndpoint basically do receiving packet and determine
// which logic executed based on the packet.
type DefaultMessageEndpoint struct {
config MessageEndpointConfig
transport UDPTransport
messageHandler MessageHandler
resHandler *responseHandler
quit chan struct{}
}
func NewMessageEndpoint(config MessageEndpointConfig, transport UDPTransport, messageHandler MessageHandler) (MessageEndpoint, error) {
if config.CallbackCollectInterval == time.Duration(0) {
return nil, ErrCallbackCollectIntervalNotSpecified
}
return &DefaultMessageEndpoint{
config: config,
transport: transport,
messageHandler: messageHandler,
resHandler: newResponseHandler(config.CallbackCollectInterval),
quit: make(chan struct{}),
}, nil
}
// Listen is a log running goroutine that pulls packet from the
// transport and pass it for processing
func (m *DefaultMessageEndpoint) Listen() {
for {
select {
case packet := <-m.transport.PacketCh():
// validate packet then convert it to message
msg, err := m.processPacket(*packet)
if err != nil {
iLogger.Error(nil, err.Error())
}
// before message that come from other handle by MessageHandler
// check whether this message is sent-back message from other member
// this is determined by message's Seq property which work as message id
if m.resHandler.hasCallback(msg.Id) {
go m.resHandler.handle(msg)
} else {
go m.handleMessage(msg)
}
case <-m.quit:
return
}
}
}
// ProcessPacket process given packet, this procedure may include
// decrypting data and converting it to message
func (m *DefaultMessageEndpoint) processPacket(packet Packet) (pb.Message, error) {
msg := &pb.Message{}
if m.config.EncryptionEnabled {
// TODO: decrypt packet
}
if err := proto.Unmarshal(packet.Buf, msg); err != nil {
return pb.Message{}, err
}
return *msg, nil
}
func validateMessage(msg pb.Message) bool {
if msg.Id == "" {
iLogger.Info(nil, "message seq value empty")
return false
}
if msg.Payload == nil {
iLogger.Info(nil, "message payload value empty")
return false
}
return true
}
// with given message handleMessage determine which logic should be executed
// based on the message type. Additionally handleMessage can call MemberDelegater
// to update member status and encrypt messages
func (m *DefaultMessageEndpoint) handleMessage(msg pb.Message) error {
// validate message
if !validateMessage(msg) {
return ErrInvalidMessage
}
// call delegate func to update members states
m.messageHandler.handle(msg)
return nil
}
// SyncSend synchronously send message to member of addr, waits until response come back,
// whether it is timeout or send failed, SyncSend can be used in the case of pinging to other members.
// if @timeout is provided then set send timeout to given parameters, if not then calculate
// timeout based on the its awareness
func (m *DefaultMessageEndpoint) SyncSend(addr string, msg pb.Message) (pb.Message, error) {
onSucc := make(chan pb.Message)
defer close(onSucc)
d, err := proto.Marshal(&msg)
if err != nil {
return pb.Message{}, err
}
// register callback function, this callback function is called when
// member with @addr sent back us packet
m.resHandler.addCallback(msg.Id, callback{
fn: func(msg pb.Message) {
onSucc <- msg
},
created: time.Now(),
})
// send the message
_, err = m.transport.WriteTo(d, addr)
if err != nil {
iLogger.Error(nil, err.Error())
return pb.Message{}, err
}
// start timer
T := time.NewTimer(m.config.SendTimeout)
select {
case msg := <-onSucc:
return msg, nil
case <-T.C:
return pb.Message{}, ErrSendTimeout
}
return pb.Message{}, ErrUnreachable
}
// Send asynchronously send message to member of addr, don't wait until response come back,
// after response came back, callback function executed, Send can be used in the case of
// gossip message to other members
func (m *DefaultMessageEndpoint) Send(addr string, msg pb.Message) error {
d, err := proto.Marshal(&msg)
if err != nil {
return err
}
// send the message
_, err = m.transport.WriteTo(d, addr)
if err != nil {
iLogger.Info(nil, err.Error())
return err
}
return nil
}
func (m *DefaultMessageEndpoint) Shutdown() {
// close transport first
m.transport.Shutdown()
// then close message endpoint
m.quit <- struct{}{}
}