-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathcoordinator.go
305 lines (267 loc) · 7.93 KB
/
coordinator.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
300
301
302
303
304
305
package stream
import (
"fmt"
"github.com/pkg/errors"
"github.com/rabbitmq/rabbitmq-stream-go-client/pkg/amqp"
"strconv"
"sync"
"time"
)
type Coordinator struct {
counter int
producers map[interface{}]interface{}
consumers map[interface{}]interface{}
responses map[interface{}]interface{}
nextItemProducer uint8
nextItemConsumer uint8
mutex *sync.Mutex
}
type Code struct {
id uint16
}
type offsetMessage struct {
message *amqp.Message
offset int64
}
type offsetMessages = []*offsetMessage
type chunkInfo struct {
offsetMessages offsetMessages
numEntries uint16
}
type Response struct {
code chan Code
data chan interface{}
chunkForConsumer chan chunkInfo
commandDescription string
correlationid int
}
func NewCoordinator() *Coordinator {
return &Coordinator{mutex: &sync.Mutex{},
producers: make(map[interface{}]interface{}),
consumers: make(map[interface{}]interface{}),
responses: make(map[interface{}]interface{})}
}
// producersEnvironment
func (coordinator *Coordinator) NewProducer(
parameters *ProducerOptions) (*Producer, error) {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
size := 10000
if parameters != nil {
size = parameters.QueueSize
}
var lastId, err = coordinator.getNextProducerItem()
if err != nil {
return nil, err
}
var producer = &Producer{id: lastId,
options: parameters,
mutex: &sync.Mutex{},
mutexPending: &sync.Mutex{},
unConfirmedMessages: map[int64]*ConfirmationStatus{},
status: open,
messageSequenceCh: make(chan messageSequence, size),
pendingMessages: pendingMessagesSequence{
messages: make([]messageSequence, 0),
size: initBufferPublishSize,
}}
coordinator.producers[lastId] = producer
return producer, err
}
func (coordinator *Coordinator) RemoveConsumerById(id interface{}, reason Event) error {
consumer, err := coordinator.GetConsumerById(id)
if err != nil {
return err
}
reason.StreamName = consumer.GetStreamName()
reason.Name = consumer.GetName()
if closeHandler := consumer.GetCloseHandler(); closeHandler != nil {
closeHandler <- reason
close(closeHandler)
}
return coordinator.removeById(id, coordinator.consumers)
}
func (coordinator *Coordinator) RemoveProducerById(id uint8, reason Event) error {
producer, err := coordinator.GetProducerById(id)
if err != nil {
return err
}
reason.StreamName = producer.GetStreamName()
reason.Name = producer.GetName()
tentatives := 0
for producer.lenUnConfirmed() > 0 && tentatives < 3 {
time.Sleep(200 * time.Millisecond)
tentatives++
}
if producer.closeHandler != nil {
producer.closeHandler <- reason
}
return coordinator.removeById(id, coordinator.producers)
}
func (coordinator *Coordinator) RemoveResponseById(id interface{}) error {
resp, err := coordinator.GetResponseByName(fmt.Sprintf("%d", id))
if err != nil {
return err
}
err = coordinator.removeById(fmt.Sprintf("%d", id), coordinator.responses)
close(resp.code)
close(resp.data)
close(resp.chunkForConsumer)
return err
}
func (coordinator *Coordinator) ProducersCount() int {
return coordinator.count(coordinator.producers)
}
// response
func newResponse(commandDescription string) *Response {
res := &Response{}
res.commandDescription = commandDescription
res.code = make(chan Code, 1)
res.data = make(chan interface{}, 1)
res.chunkForConsumer = make(chan chunkInfo, 100)
return res
}
func (coordinator *Coordinator) NewResponseWitName(id string) *Response {
coordinator.mutex.Lock()
coordinator.counter++
res := newResponse(id)
res.correlationid = coordinator.counter
coordinator.responses[id] = res
coordinator.mutex.Unlock()
return res
}
func (coordinator *Coordinator) NewResponse(commandId uint16, info ...string) *Response {
description := lookUpCommand(commandId)
if len(info) > 0 {
description = fmt.Sprintf("%s, - %s", description, info[0])
}
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
coordinator.counter++
res := newResponse(description)
res.correlationid = coordinator.counter
coordinator.responses[strconv.Itoa(coordinator.counter)] = res
return res
}
func (coordinator *Coordinator) GetResponseByName(id string) (*Response, error) {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
if coordinator.responses[id] == nil {
return nil, errors.New("Response #{id} not found ")
}
switch coordinator.responses[id].(type) {
case *Response:
return coordinator.responses[id].(*Response), nil
}
return nil, nil
}
func (coordinator *Coordinator) RemoveResponseByName(id string) error {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
if coordinator.responses[id] == nil {
return errors.New("Response #{id} not found ")
}
coordinator.responses[id] = nil
delete(coordinator.responses, id)
return nil
}
// Consumer functions
func (coordinator *Coordinator) NewConsumer(messagesHandler MessagesHandler,
parameters *ConsumerOptions) *Consumer {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
var lastId, _ = coordinator.getNextConsumerItem()
var item = &Consumer{ID: lastId, options: parameters,
response: newResponse(lookUpCommand(commandSubscribe)),
status: open,
mutex: &sync.Mutex{},
MessagesHandler: messagesHandler,
lastStoredOffset: -1, // because 0 is a valid value for the offset
isPromotedAsActive: true,
}
coordinator.consumers[lastId] = item
return item
}
func (coordinator *Coordinator) GetConsumerById(id interface{}) (*Consumer, error) {
v, err := coordinator.getById(id, coordinator.consumers)
if err != nil {
return nil, err
}
return v.(*Consumer), err
}
func (coordinator *Coordinator) GetResponseById(id uint32) (*Response, error) {
v, err := coordinator.getById(fmt.Sprintf("%d", id), coordinator.responses)
if err != nil {
return nil, err
}
return v.(*Response), err
}
func (coordinator *Coordinator) ConsumersCount() int {
return coordinator.count(coordinator.consumers)
}
func (coordinator *Coordinator) GetProducerById(id interface{}) (*Producer, error) {
v, err := coordinator.getById(id, coordinator.producers)
if err != nil {
return nil, err
}
return v.(*Producer), err
}
// general functions
func (coordinator *Coordinator) getById(id interface{}, refmap map[interface{}]interface{}) (interface{}, error) {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
if refmap[id] == nil {
return nil, errors.New("item #{id} not found ")
}
return refmap[id], nil
}
func (coordinator *Coordinator) removeById(id interface{}, refmap map[interface{}]interface{}) error {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
if refmap[id] == nil {
return fmt.Errorf("remove failed, id %d not found", id)
}
refmap[id] = nil
delete(refmap, id)
return nil
}
func (coordinator *Coordinator) count(refmap map[interface{}]interface{}) int {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
return len(refmap)
}
func (coordinator *Coordinator) getNextProducerItem() (uint8, error) {
if coordinator.nextItemProducer >= ^uint8(0) {
return coordinator.reuseFreeId(coordinator.producers)
}
res := coordinator.nextItemProducer
coordinator.nextItemProducer++
return res, nil
}
func (coordinator *Coordinator) getNextConsumerItem() (uint8, error) {
if coordinator.nextItemConsumer >= ^uint8(0) {
return coordinator.reuseFreeId(coordinator.consumers)
}
res := coordinator.nextItemConsumer
coordinator.nextItemConsumer++
return res, nil
}
func (coordinator *Coordinator) reuseFreeId(refMap map[interface{}]interface{}) (byte, error) {
maxValue := int(^uint8(0))
var result byte
for i := 0; i < maxValue; i++ {
if refMap[byte(i)] == nil {
return byte(i), nil
}
result++
}
if result >= ^uint8(0) {
return 0, errors.New("No more items available")
}
return result, nil
}
func (coordinator *Coordinator) Producers() map[interface{}]interface{} {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
return coordinator.producers
}