-
Notifications
You must be signed in to change notification settings - Fork 69
/
event.go
305 lines (261 loc) · 7.5 KB
/
event.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 eventhub
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/Azure/azure-amqp-common-go/persist"
"github.com/mitchellh/mapstructure"
"pack.ag/amqp"
)
const (
batchMessageFormat uint32 = 0x80013700
partitionKeyAnnotationName string = "x-opt-partition-key"
sequenceNumberName string = "x-opt-sequence-number"
enqueueTimeName string = "x-opt-enqueued-time"
)
type (
// Event is an Event Hubs message to be sent or received
Event struct {
Data []byte
PartitionKey *string
Properties map[string]interface{}
ID string
message *amqp.Message
SystemProperties *SystemProperties
}
// EventBatch is a batch of Event Hubs messages to be sent
EventBatch struct {
Events []*Event
PartitionKey *string
Properties map[string]interface{}
ID string
}
// SystemProperties are used to store properties that are set by the system.
SystemProperties struct {
SequenceNumber *int64 `mapstructure:"x-opt-sequence-number"` // unique sequence number of the message
EnqueuedTime *time.Time `mapstructure:"x-opt-enqueued-time"` // time the message landed in the message queue
Offset *int64 `mapstructure:"x-opt-offset"`
PartitionID *int16 `mapstructure:"x-opt-partition-id"`
PartitionKey *string `mapstructure:"x-opt-partition-key"`
}
mapStructureTag struct {
Name string
PersistEmpty bool
}
)
// NewEventFromString builds an Event from a string message
func NewEventFromString(message string) *Event {
return NewEvent([]byte(message))
}
// NewEvent builds an Event from a slice of data
func NewEvent(data []byte) *Event {
return &Event{
Data: data,
}
}
// NewEventBatch builds an EventBatch from an array of Events
func NewEventBatch(events []*Event) *EventBatch {
return &EventBatch{
Events: events,
}
}
// GetCheckpoint returns the checkpoint information on the Event
func (e *Event) GetCheckpoint() persist.Checkpoint {
var offset string
var enqueueTime time.Time
var sequenceNumber int64
if val, ok := e.message.Annotations[offsetAnnotationName]; ok {
offset = val.(string)
}
if val, ok := e.message.Annotations[enqueueTimeName]; ok {
enqueueTime = val.(time.Time)
}
if val, ok := e.message.Annotations[sequenceNumberName]; ok {
sequenceNumber = val.(int64)
}
return persist.NewCheckpoint(offset, sequenceNumber, enqueueTime)
}
// Set will set a key in the event properties
func (e *Event) Set(key string, value interface{}) {
if e.Properties == nil {
e.Properties = make(map[string]interface{})
}
e.Properties[key] = value
}
// Get will fetch a property from the event
func (e *Event) Get(key string) (interface{}, bool) {
if e.Properties == nil {
return nil, false
}
if val, ok := e.Properties[key]; ok {
return val, true
}
return nil, false
}
func (e *Event) toMsg() (*amqp.Message, error) {
msg := e.message
if msg == nil {
msg = amqp.NewMessage(e.Data)
}
msg.Properties = &amqp.MessageProperties{
MessageID: e.ID,
}
if len(e.Properties) > 0 {
msg.ApplicationProperties = make(map[string]interface{})
for key, value := range e.Properties {
msg.ApplicationProperties[key] = value
}
}
if e.SystemProperties != nil {
sysPropMap, err := encodeStructureToMap(e.SystemProperties)
if err != nil {
return nil, err
}
msg.Annotations = annotationsFromMap(sysPropMap)
}
if e.PartitionKey != nil {
msg.Annotations = make(amqp.Annotations)
msg.Annotations[partitionKeyAnnotationName] = e.PartitionKey
}
return msg, nil
}
func (b *EventBatch) toEvent() (*Event, error) {
msg := &amqp.Message{
Data: make([][]byte, len(b.Events)),
Properties: &amqp.MessageProperties{
MessageID: b.ID,
},
Format: batchMessageFormat,
}
if b.PartitionKey != nil {
msg.Annotations = make(amqp.Annotations)
msg.Annotations[partitionKeyAnnotationName] = b.PartitionKey
}
for idx, event := range b.Events {
innerMsg, err := event.toMsg()
if err != nil {
return nil, err
}
bin, err := innerMsg.MarshalBinary()
if err != nil {
return nil, err
}
msg.Data[idx] = bin
}
return eventFromMsg(msg)
}
func eventFromMsg(msg *amqp.Message) (*Event, error) {
return newEvent(msg.Data[0], msg)
}
func newEvent(data []byte, msg *amqp.Message) (*Event, error) {
event := &Event{
Data: data,
message: msg,
}
if msg.Properties != nil {
if id, ok := msg.Properties.MessageID.(string); ok {
event.ID = id
}
}
if msg.Annotations != nil {
if val, ok := msg.Annotations[partitionKeyAnnotationName]; ok {
if valStr, ok := val.(string); ok {
event.PartitionKey = &valStr
}
}
}
if msg.Annotations != nil {
if err := mapstructure.WeakDecode(msg.Annotations, &event.SystemProperties); err != nil {
fmt.Println("error decoding...", err)
return event, err
}
}
if msg != nil {
event.Properties = msg.ApplicationProperties
}
return event, nil
}
func encodeStructureToMap(structPointer interface{}) (map[string]interface{}, error) {
valueOfStruct := reflect.ValueOf(structPointer)
s := valueOfStruct.Elem()
if s.Kind() != reflect.Struct {
return nil, fmt.Errorf("must provide a struct")
}
encoded := make(map[string]interface{})
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
if f.IsValid() && f.CanSet() {
tf := s.Type().Field(i)
tag, err := parseMapStructureTag(tf.Tag)
if err != nil {
return nil, err
}
if tag != nil {
switch f.Kind() {
case reflect.Ptr:
if !f.IsNil() || tag.PersistEmpty {
if f.IsNil() {
encoded[tag.Name] = nil
} else {
encoded[tag.Name] = f.Elem().Interface()
}
}
default:
if f.Interface() != reflect.Zero(f.Type()).Interface() || tag.PersistEmpty {
encoded[tag.Name] = f.Interface()
}
}
}
}
}
return encoded, nil
}
func parseMapStructureTag(tag reflect.StructTag) (*mapStructureTag, error) {
str, ok := tag.Lookup("mapstructure")
if !ok {
return nil, nil
}
mapTag := new(mapStructureTag)
split := strings.Split(str, ",")
mapTag.Name = strings.TrimSpace(split[0])
if len(split) > 1 {
for _, tagKey := range split[1:] {
switch tagKey {
case "persistempty":
mapTag.PersistEmpty = true
default:
return nil, fmt.Errorf("key %q is not understood", tagKey)
}
}
}
return mapTag, nil
}
func annotationsFromMap(m map[string]interface{}) amqp.Annotations {
a := make(amqp.Annotations)
for key, val := range m {
a[key] = val
}
return a
}