go.uber.org/yarpc@v1.72.1/encoding/protobuf/stream.go (about) 1 // Copyright (c) 2022 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package protobuf 22 23 import ( 24 "bytes" 25 "context" 26 27 "github.com/gogo/protobuf/proto" 28 "go.uber.org/yarpc/api/transport" 29 ) 30 31 // readFromStream reads a proto.Message from a stream. 32 func readFromStream( 33 ctx context.Context, 34 stream transport.Stream, 35 newMessage func() proto.Message, 36 codec *codec, 37 ) (proto.Message, error) { 38 streamMsg, err := stream.ReceiveMessage(ctx) 39 if err != nil { 40 return nil, convertFromYARPCError(Encoding, err, codec) 41 } 42 message := newMessage() 43 if err := unmarshal(stream.Request().Meta.Encoding, streamMsg.Body, message, codec); err != nil { 44 streamMsg.Body.Close() 45 return nil, err 46 } 47 if streamMsg.Body != nil { 48 streamMsg.Body.Close() 49 } 50 return message, nil 51 } 52 53 // writeToStream writes a proto.Message to a stream. 54 func writeToStream(ctx context.Context, stream transport.Stream, message proto.Message, codec *codec) error { 55 messageData, cleanup, err := marshal(stream.Request().Meta.Encoding, message, codec) 56 if err != nil { 57 return err 58 } 59 return stream.SendMessage( 60 ctx, 61 &transport.StreamMessage{ 62 Body: readCloser{ 63 Reader: bytes.NewReader(messageData), 64 closer: cleanup, 65 }, 66 BodySize: len(messageData), 67 }, 68 ) 69 } 70 71 type readCloser struct { 72 *bytes.Reader 73 closer func() 74 } 75 76 func (r readCloser) Close() error { 77 r.closer() 78 return nil 79 }