vitess.io/vitess@v0.16.2/go/vt/servenv/grpc_codec.go (about) 1 /* 2 Copyright 2021 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package servenv 18 19 import ( 20 "fmt" 21 22 // use the original golang/protobuf package we can continue serializing 23 // messages from our dependencies, particularly from etcd 24 "github.com/golang/protobuf/proto" //nolint 25 26 "google.golang.org/grpc/encoding" 27 _ "google.golang.org/grpc/encoding/proto" // nolint:revive 28 ) 29 30 // Name is the name registered for the proto compressor. 31 const Name = "proto" 32 33 type vtprotoCodec struct{} 34 35 type vtprotoMessage interface { 36 MarshalVT() ([]byte, error) 37 UnmarshalVT([]byte) error 38 } 39 40 func (vtprotoCodec) Marshal(v any) ([]byte, error) { 41 vt, ok := v.(vtprotoMessage) 42 if ok { 43 return vt.MarshalVT() 44 } 45 46 vv, ok := v.(proto.Message) 47 if !ok { 48 return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) 49 } 50 return proto.Marshal(vv) 51 } 52 53 func (vtprotoCodec) Unmarshal(data []byte, v any) error { 54 vt, ok := v.(vtprotoMessage) 55 if ok { 56 return vt.UnmarshalVT(data) 57 } 58 59 vv, ok := v.(proto.Message) 60 if !ok { 61 return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) 62 } 63 return proto.Unmarshal(data, vv) 64 } 65 66 func (vtprotoCodec) Name() string { 67 return Name 68 } 69 70 func init() { 71 encoding.RegisterCodec(vtprotoCodec{}) 72 }