-
Notifications
You must be signed in to change notification settings - Fork 297
/
types.helper.go
67 lines (60 loc) · 1.77 KB
/
types.helper.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
package proto
import (
"crypto/md5"
"encoding/hex"
"fmt"
"sort"
"strings"
"google.golang.org/protobuf/proto"
)
func (esk *EventSchemaKey) MustMarshal() []byte {
m, err := proto.MarshalOptions{}.Marshal(esk)
if err != nil {
panic(fmt.Errorf("marshalling event schema key failed: %w", err))
}
return m
}
func (esm *EventSchemaMessage) MustMarshal() []byte {
m, err := proto.MarshalOptions{}.Marshal(esm)
if err != nil {
panic(fmt.Errorf("marshalling event schema message failed: %w", err))
}
return m
}
// UnmarshalEventSchemaMessage creates a new event schema message from the provided protobuf bytes.
func UnmarshalEventSchemaMessage(raw []byte) (*EventSchemaMessage, error) {
p := &EventSchemaMessage{}
if err := proto.Unmarshal(raw, p); err != nil {
return nil, fmt.Errorf("failed to unmarshal event schema message: %w", err)
}
return p, nil
}
// SchemaHash returns a hash of the schema. Keys are sorted lexicographically during hashing.
func SchemaHash(schema map[string]string) string {
keys := make([]string, 0, len(schema))
for k := range schema {
keys = append(keys, k)
}
sort.Strings(keys)
var sb strings.Builder
for _, k := range keys {
sb.WriteString(k)
sb.WriteString(":")
sb.WriteString(schema[k])
sb.WriteString(",")
}
md5Sum := md5.Sum([]byte(sb.String()))
schemaHash := hex.EncodeToString(md5Sum[:])
return schemaHash
}
// Merge merges the other event schema message into this one.
func (sm *EventSchemaMessage) Merge(other *EventSchemaMessage) {
sm.BatchCount += other.BatchCount + 1
if len(other.Sample) < len(sm.Sample) { // keep the smallest sample
sm.Sample = other.Sample
}
sm.Sample = other.Sample
if other.ObservedAt.AsTime().After(sm.ObservedAt.AsTime()) { // keep the laters observed time
sm.ObservedAt = other.ObservedAt
}
}