consul/agent/agentpb/encoder.go

36 lines
886 B
Go
Raw Normal View History

Add support for implementing new requests with protobufs instea… (#6502) * Add build system support for protobuf generation This is done generically so that we don’t have to keep updating the makefile to add another proto generation. Note: anything not in the vendor directory and with a .proto extension will be run through protoc if the corresponding namespace.pb.go file is not up to date. If you want to rebuild just a single proto file you can do so with: make proto-rebuild PROTOFILES=<list of proto files to rebuild> Providing the PROTOFILES var will override the default behavior of finding all the .proto files. * Start adding types to the agent/proto package These will be needed for some other work and are by no means comprehensive. * Add ability to resolve/fixup the agentpb.ACLLinks structure in the state store. * Use protobuf marshalling of raft requests instead of msgpack for protoc generated types. This does not change any encoding of existing types. * Removed structs package automatically encoding with protobuf marshalling Instead the caller of raftApply that wants to opt-in to protobuf encoding will have to call `raftApplyProtobuf` * Run update-vendor to fixup modules.txt Nothing changed as far as dependencies go but the ordering of modules in that file depends on the time they are first seen and its not alphabetical. * Rename some things and implement the structs.RPCInfo interface bits agentpb.QueryOptions and agentpb.WriteRequest implement 3 of the 4 RPCInfo funcs and the new TargetDatacenter message type implements the fourth. * Use the right encoding function. * Renamed agent/proto package to agent/agentpb to prevent package name conflicts * Update modules.txt to fix ordering * Change blockingQuery to take in interfaces for the query options and meta * Add %T to error output. * Add/Update some comments
2019-09-20 18:37:22 +00:00
package agentpb
import (
"fmt"
"github.com/hashicorp/consul/agent/structs"
)
type ProtoMarshaller interface {
Size() int
MarshalTo([]byte) (int, error)
Unmarshal([]byte) error
ProtoMessage()
}
func EncodeInterface(t structs.MessageType, message interface{}) ([]byte, error) {
if marshaller, ok := message.(ProtoMarshaller); ok {
return Encode(t, marshaller)
}
return nil, fmt.Errorf("message does not implement the ProtoMarshaller interface: %T", message)
}
func Encode(t structs.MessageType, message ProtoMarshaller) ([]byte, error) {
data := make([]byte, message.Size()+1)
data[0] = uint8(t)
if _, err := message.MarshalTo(data[1:]); err != nil {
return nil, err
}
return data, nil
}
func Decode(buf []byte, out ProtoMarshaller) error {
// Note that this assumes the leading byte indicating the type has already been stripped off
return out.Unmarshal(buf)
}