github.com/cloudwego/kitex@v0.9.0/pkg/remote/codec/protobuf/encoding/encoding.go (about)

     1  /*
     2   *
     3   * Copyright 2017 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   * This file may have been modified by CloudWeGo authors. All CloudWeGo
    18   * Modifications are Copyright 2023 CloudWeGo Authors.
    19   */
    20  
    21  // Package encoding defines the interface for the compressor and codec, and
    22  // functions to register and retrieve compressors and codecs.
    23  //
    24  // # Experimental
    25  //
    26  // Notice: This package is EXPERIMENTAL and may be changed or removed in a
    27  // later release.
    28  package encoding
    29  
    30  import (
    31  	"fmt"
    32  	"io"
    33  	"strings"
    34  )
    35  
    36  // Identity specifies the optional encoding for uncompressed streams.
    37  // It is intended for grpc internal use only.
    38  const Identity = "identity"
    39  
    40  // Compressor is used for compressing and decompressing when sending or
    41  // receiving messages.
    42  type Compressor interface {
    43  	// Compress writes the data written to wc to w after compressing it.  If an
    44  	// error occurs while initializing the compressor, that error is returned
    45  	// instead.
    46  	Compress(w io.Writer) (io.WriteCloser, error)
    47  	// Decompress reads data from r, decompresses it, and provides the
    48  	// uncompressed data via the returned io.Reader.  If an error occurs while
    49  	// initializing the decompressor, that error is returned instead.
    50  	Decompress(r io.Reader) (io.Reader, error)
    51  	// Name is the name of the compression codec and is used to set the content
    52  	// coding header.  The result must be static; the result cannot change
    53  	// between calls.
    54  	Name() string
    55  	// If a Compressor implements
    56  	// DecompressedSize(compressedBytes []byte) int, gRPC will call it
    57  	// to determine the size of the buffer allocated for the result of decompression.
    58  	// Return -1 to indicate unknown size.
    59  	//
    60  	// Experimental
    61  	//
    62  	// Notice: This API is EXPERIMENTAL and may be changed or removed in a
    63  	// later release.
    64  }
    65  
    66  var registeredCompressor = make(map[string]Compressor)
    67  
    68  // RegisterCompressor registers the compressor with gRPC by its name.  It can
    69  // be activated when sending an RPC via grpc.UseCompressor().  It will be
    70  // automatically accessed when receiving a message based on the content coding
    71  // header.  Servers also use it to send a response with the same encoding as
    72  // the request.
    73  //
    74  // NOTE: this function must only be called during initialization time (i.e. in
    75  // an init() function), and is not thread-safe.  If multiple Compressors are
    76  // registered with the same name, the one registered last will take effect.
    77  func RegisterCompressor(c Compressor) {
    78  	registeredCompressor[c.Name()] = c
    79  }
    80  
    81  // GetCompressor returns Compressor for the given compressor name.
    82  func GetCompressor(name string) Compressor {
    83  	return registeredCompressor[name]
    84  }
    85  
    86  // FindCompressorName returns the name of compressor that actually used.
    87  // when cname is like "identity,deflate,gzip", only one compressor name should be returned.
    88  func FindCompressorName(cname string) string {
    89  	compressor, _ := FindCompressor(cname)
    90  	if compressor != nil {
    91  		return compressor.Name()
    92  	}
    93  	return ""
    94  }
    95  
    96  // FindCompressor is used to search for compressors based on a given name, where the input name can be an array of compressor names.
    97  func FindCompressor(cname string) (compressor Compressor, err error) {
    98  	// if cname is empty, it means there's no compressor
    99  	if cname == "" {
   100  		return nil, nil
   101  	}
   102  	// cname can be an array, such as "identity,deflate,gzip", which means there should be at least one compressor registered.
   103  	// found available compressors
   104  	var hasIdentity bool
   105  	for _, name := range strings.Split(strings.TrimSuffix(cname, ";"), ",") {
   106  		name = strings.TrimSpace(name)
   107  		if name == Identity {
   108  			hasIdentity = true
   109  		}
   110  		compressor = GetCompressor(name)
   111  		if compressor != nil {
   112  			break
   113  		}
   114  	}
   115  	if compressor == nil {
   116  		if hasIdentity {
   117  			return nil, nil
   118  		}
   119  		return nil, fmt.Errorf("no kitex compressor registered found for:%v", cname)
   120  	}
   121  	return compressor, nil
   122  }
   123  
   124  // Codec defines the interface gRPC uses to encode and decode messages.  Note
   125  // that implementations of this interface must be thread safe; a Codec's
   126  // methods can be called from concurrent goroutines.
   127  type Codec interface {
   128  	// Marshal returns the wire format of v.
   129  	Marshal(v interface{}) ([]byte, error)
   130  	// Unmarshal parses the wire format into v.
   131  	Unmarshal(data []byte, v interface{}) error
   132  	// Name returns the name of the Codec implementation. The returned string
   133  	// will be used as part of content type in transmission.  The result must be
   134  	// static; the result cannot change between calls.
   135  	Name() string
   136  }
   137  
   138  var registeredCodecs = make(map[string]Codec)
   139  
   140  // RegisterCodec registers the provided Codec for use with all gRPC clients and
   141  // servers.
   142  //
   143  // The Codec will be stored and looked up by result of its Name() method, which
   144  // should match the content-subtype of the encoding handled by the Codec.  This
   145  // is case-insensitive, and is stored and looked up as lowercase.  If the
   146  // result of calling Name() is an empty string, RegisterCodec will panic. See
   147  // Content-Type on
   148  // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
   149  // more details.
   150  //
   151  // NOTE: this function must only be called during initialization time (i.e. in
   152  // an init() function), and is not thread-safe.  If multiple Compressors are
   153  // registered with the same name, the one registered last will take effect.
   154  func RegisterCodec(codec Codec) {
   155  	if codec == nil {
   156  		panic("cannot register a nil Codec")
   157  	}
   158  	if codec.Name() == "" {
   159  		panic("cannot register Codec with empty string result for Name()")
   160  	}
   161  	contentSubtype := strings.ToLower(codec.Name())
   162  	registeredCodecs[contentSubtype] = codec
   163  }
   164  
   165  // GetCodec gets a registered Codec by content-subtype, or nil if no Codec is
   166  // registered for the content-subtype.
   167  //
   168  // The content-subtype is expected to be lowercase.
   169  func GetCodec(contentSubtype string) Codec {
   170  	return registeredCodecs[contentSubtype]
   171  }