vitess.io/vitess@v0.16.2/go/vt/grpcclient/snappy.go (about)

     1  /*
     2  Copyright 2019 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 grpcclient
    18  
    19  import (
    20  	"io"
    21  
    22  	"github.com/golang/snappy"
    23  
    24  	"google.golang.org/grpc"
    25  	"google.golang.org/grpc/encoding"
    26  )
    27  
    28  var compression string
    29  
    30  // SnappyCompressor is a gRPC compressor using the Snappy algorithm.
    31  type SnappyCompressor struct{}
    32  
    33  // Name is "snappy"
    34  func (s SnappyCompressor) Name() string {
    35  	return "snappy"
    36  }
    37  
    38  // Compress wraps with a SnappyReader
    39  func (s SnappyCompressor) Compress(w io.Writer) (io.WriteCloser, error) {
    40  	return snappy.NewBufferedWriter(w), nil
    41  }
    42  
    43  // Decompress wraps with a SnappyReader
    44  func (s SnappyCompressor) Decompress(r io.Reader) (io.Reader, error) {
    45  	return snappy.NewReader(r), nil
    46  }
    47  
    48  func appendCompression(opts []grpc.DialOption) ([]grpc.DialOption, error) {
    49  	if compression == "snappy" {
    50  		compression := grpc.WithDefaultCallOptions(grpc.UseCompressor("snappy"))
    51  		opts = append(opts, compression)
    52  	}
    53  
    54  	return opts, nil
    55  }
    56  
    57  func init() {
    58  	encoding.RegisterCompressor(SnappyCompressor{})
    59  	RegisterGRPCDialOptions(appendCompression)
    60  }