go.uber.org/yarpc@v1.72.1/compressor/grpc/grpc.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 yarpcgrpccompressor provides an adapter for YARPC compressors to 22 // gRPC compressors. 23 // 24 // The only distinction is that YARPC's Decompressor returns an io.ReadCloser 25 // instead of a mere io.Reader. 26 // gRPC does not call Close, so must infer the end of stream by returning the 27 // reader to the reader pool when Read returns io.EOF. 28 // This wrapper uses the io.EOF to trigger and automatic Close. 29 package yarpcgrpccompressor 30 31 import ( 32 "io" 33 34 "go.uber.org/yarpc/api/transport" 35 "google.golang.org/grpc/encoding" 36 ) 37 38 // New adapts a YARPC compressor to a gRPC compressor. 39 func New(compressor transport.Compressor) encoding.Compressor { 40 return &Compressor{compressor: compressor} 41 } 42 43 // Compressor is a gRPC compressor that wraps a YARPC compressor. 44 type Compressor struct { 45 compressor transport.Compressor 46 } 47 48 var _ encoding.Compressor = (*Compressor)(nil) 49 50 // Name returns the name of the underlying compressor. 51 func (c *Compressor) Name() string { 52 return c.compressor.Name() 53 } 54 55 // Compress wraps a writer with a compressing writer. 56 func (c *Compressor) Compress(w io.Writer) (io.WriteCloser, error) { 57 return c.compressor.Compress(w) 58 } 59 60 // Decompress wraps a reader with a decompressing reader. 61 func (c *Compressor) Decompress(r io.Reader) (io.Reader, error) { 62 dr, err := c.compressor.Decompress(r) 63 if err != nil { 64 return nil, err 65 } 66 return &reader{reader: dr}, nil 67 } 68 69 type reader struct { 70 reader io.ReadCloser 71 } 72 73 var _ io.Reader = (*reader)(nil) 74 75 func (r *reader) Read(buf []byte) (n int, err error) { 76 n, err = r.reader.Read(buf) 77 if err == io.EOF { 78 r.reader.Close() 79 } 80 return n, err 81 }