github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/persistence/protocb/envelope.go (about) 1 package protocb 2 3 import ( 4 "encoding/json" 5 "log" 6 7 "google.golang.org/protobuf/proto" 8 "google.golang.org/protobuf/reflect/protoreflect" 9 "google.golang.org/protobuf/reflect/protoregistry" 10 ) 11 12 type envelope struct { 13 Type string `json:"type"` // reflected message type so we can deserialize back 14 Message json.RawMessage `json:"event"` // this is still protobuf but the json form 15 EventIndex int `json:"eventIndex"` // event index in the event stream 16 DocType string `json:"doctype"` // type snapshot or event 17 } 18 19 func newEnvelope(message proto.Message, doctype string, eventIndex int) *envelope { 20 typeName := proto.MessageName(message) 21 bytes, err := json.Marshal(message) 22 if err != nil { 23 log.Fatal(err) 24 } 25 envelope := &envelope{ 26 Type: string(typeName), 27 Message: bytes, 28 EventIndex: eventIndex, 29 DocType: doctype, 30 } 31 return envelope 32 } 33 34 func (envelope *envelope) message() proto.Message { 35 mt, err := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(envelope.Type)) 36 if err != nil { 37 log.Fatal(err) 38 } 39 40 pm := mt.New().Interface() 41 err = json.Unmarshal(envelope.Message, pm) 42 if err != nil { 43 log.Fatal(err) 44 } 45 return pm 46 }