gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/preloader.go (about)

     1  /*
     2   *
     3   * Copyright 2019 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   */
    18  
    19  package grpc
    20  
    21  import (
    22  	"gitee.com/ks-custle/core-gm/grpc/codes"
    23  	"gitee.com/ks-custle/core-gm/grpc/status"
    24  )
    25  
    26  // PreparedMsg is responsible for creating a Marshalled and Compressed object.
    27  //
    28  // # Experimental
    29  //
    30  // Notice: This type is EXPERIMENTAL and may be changed or removed in a
    31  // later release.
    32  type PreparedMsg struct {
    33  	// Struct for preparing msg before sending them
    34  	encodedData []byte
    35  	hdr         []byte
    36  	payload     []byte
    37  }
    38  
    39  // Encode marshalls and compresses the message using the codec and compressor for the stream.
    40  func (p *PreparedMsg) Encode(s Stream, msg interface{}) error {
    41  	ctx := s.Context()
    42  	rpcInfo, ok := rpcInfoFromContext(ctx)
    43  	if !ok {
    44  		return status.Errorf(codes.Internal, "grpc: unable to get rpcInfo")
    45  	}
    46  
    47  	// check if the context has the relevant information to prepareMsg
    48  	if rpcInfo.preloaderInfo == nil {
    49  		return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo is nil")
    50  	}
    51  	if rpcInfo.preloaderInfo.codec == nil {
    52  		return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo.codec is nil")
    53  	}
    54  
    55  	// prepare the msg
    56  	data, err := encode(rpcInfo.preloaderInfo.codec, msg)
    57  	if err != nil {
    58  		return err
    59  	}
    60  	p.encodedData = data
    61  	compData, err := compress(data, rpcInfo.preloaderInfo.cp, rpcInfo.preloaderInfo.comp)
    62  	if err != nil {
    63  		return err
    64  	}
    65  	p.hdr, p.payload = msgHeader(data, compData)
    66  	return nil
    67  }