-
Notifications
You must be signed in to change notification settings - Fork 128
/
meta_frame.go
113 lines (96 loc) 路 2.55 KB
/
meta_frame.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
package frame
import (
"strconv"
"time"
gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/yomorun/y3"
)
// MetaFrame is a Y3 encoded bytes, SeqID is a fixed value of TYPE_ID_TRANSACTION.
// used for describes metadata for a DataFrame.
type MetaFrame struct {
tid string
metadata []byte
sourceID string
}
// NewMetaFrame creates a new MetaFrame instance.
func NewMetaFrame() *MetaFrame {
tid, err := gonanoid.New()
if err != nil {
tid = strconv.FormatInt(time.Now().Unix(), 10) // todo: UnixMicro since go 1.17
}
return &MetaFrame{tid: tid}
}
// SetTransactionID set the transaction ID.
func (m *MetaFrame) SetTransactionID(transactionID string) {
m.tid = transactionID
}
// TransactionID returns transactionID
func (m *MetaFrame) TransactionID() string {
return m.tid
}
// SetMetadata set the extra info of the application
func (m *MetaFrame) SetMetadata(metadata []byte) {
m.metadata = metadata
}
// Metadata returns the extra info of the application
func (m *MetaFrame) Metadata() []byte {
return m.metadata
}
// SetSourceID set the source ID.
func (m *MetaFrame) SetSourceID(sourceID string) {
m.sourceID = sourceID
}
// SourceID returns source ID
func (m *MetaFrame) SourceID() string {
return m.sourceID
}
// Encode implements Frame.Encode method.
func (m *MetaFrame) Encode() []byte {
meta := y3.NewNodePacketEncoder(byte(TagOfMetaFrame))
// transaction ID
transactionID := y3.NewPrimitivePacketEncoder(byte(TagOfTransactionID))
transactionID.SetStringValue(m.tid)
meta.AddPrimitivePacket(transactionID)
// source ID
sourceID := y3.NewPrimitivePacketEncoder(byte(TagOfSourceID))
sourceID.SetStringValue(m.sourceID)
meta.AddPrimitivePacket(sourceID)
// metadata
if m.metadata != nil {
metadata := y3.NewPrimitivePacketEncoder(byte(TagOfMetadata))
metadata.SetBytesValue(m.metadata)
meta.AddPrimitivePacket(metadata)
}
return meta.Encode()
}
// DecodeToMetaFrame decode a MetaFrame instance from given buffer.
func DecodeToMetaFrame(buf []byte) (*MetaFrame, error) {
nodeBlock := y3.NodePacket{}
_, err := y3.DecodeToNodePacket(buf, &nodeBlock)
if err != nil {
return nil, err
}
meta := &MetaFrame{}
for k, v := range nodeBlock.PrimitivePackets {
switch k {
case byte(TagOfTransactionID):
val, err := v.ToUTF8String()
if err != nil {
return nil, err
}
meta.tid = val
break
case byte(TagOfMetadata):
meta.metadata = v.ToBytes()
break
case byte(TagOfSourceID):
sourceID, err := v.ToUTF8String()
if err != nil {
return nil, err
}
meta.sourceID = sourceID
break
}
}
return meta, nil
}