network/frame/meta_frame.go

114 lines
2.5 KiB
Go
Raw Normal View History

2022-10-11 17:36:09 +08:00
package frame
import (
"strconv"
"time"
coder "git.hpds.cc/Component/mq_coder"
gonanoid "github.com/matoous/go-nanoid/v2"
)
// MetaFrame is a coder 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().UnixMicro(), 10)
}
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 {
2023-03-10 23:49:52 +08:00
meta := coder.NewNodePacketEncoder(TagOfMetaFrame)
2022-10-11 17:36:09 +08:00
// transaction ID
2023-03-10 23:49:52 +08:00
transactionId := coder.NewPrimitivePacketEncoder(TagOfTransactionId)
2022-10-11 17:36:09 +08:00
transactionId.SetStringValue(m.tid)
meta.AddPrimitivePacket(transactionId)
// source ID
2023-03-10 23:49:52 +08:00
sourceId := coder.NewPrimitivePacketEncoder(TagOfSourceId)
2022-10-11 17:36:09 +08:00
sourceId.SetStringValue(m.sourceId)
meta.AddPrimitivePacket(sourceId)
// metadata
if m.metadata != nil {
2023-03-10 23:49:52 +08:00
metadata := coder.NewPrimitivePacketEncoder(TagOfMetadata)
2022-10-11 17:36:09 +08:00
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 := coder.NodePacket{}
_, err := coder.DecodeToNodePacket(buf, &nodeBlock)
if err != nil {
return nil, err
}
meta := &MetaFrame{}
for k, v := range nodeBlock.PrimitivePackets {
switch k {
2023-03-10 23:49:52 +08:00
case TagOfTransactionId:
2022-10-11 17:36:09 +08:00
val, err := v.ToUTF8String()
if err != nil {
return nil, err
}
meta.tid = val
break
2023-03-10 23:49:52 +08:00
case TagOfMetadata:
2022-10-11 17:36:09 +08:00
meta.metadata = v.ToBytes()
break
2023-03-10 23:49:52 +08:00
case TagOfSourceId:
2022-10-11 17:36:09 +08:00
sourceId, err := v.ToUTF8String()
if err != nil {
return nil, err
}
meta.sourceId = sourceId
break
}
}
return meta, nil
}