preloader.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. package grpc
  19. import (
  20. "google.golang.org/grpc/codes"
  21. "google.golang.org/grpc/status"
  22. )
  23. // PreparedMsg is responsible for creating a Marshalled and Compressed object.
  24. //
  25. // This API is EXPERIMENTAL.
  26. type PreparedMsg struct {
  27. // Struct for preparing msg before sending them
  28. encodedData []byte
  29. hdr []byte
  30. payload []byte
  31. }
  32. // Encode marshalls and compresses the message using the codec and compressor for the stream.
  33. func (p *PreparedMsg) Encode(s Stream, msg interface{}) error {
  34. ctx := s.Context()
  35. rpcInfo, ok := rpcInfoFromContext(ctx)
  36. if !ok {
  37. return status.Errorf(codes.Internal, "grpc: unable to get rpcInfo")
  38. }
  39. // check if the context has the relevant information to prepareMsg
  40. if rpcInfo.preloaderInfo == nil {
  41. return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo is nil")
  42. }
  43. if rpcInfo.preloaderInfo.codec == nil {
  44. return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo.codec is nil")
  45. }
  46. // prepare the msg
  47. data, err := encode(rpcInfo.preloaderInfo.codec, msg)
  48. if err != nil {
  49. return err
  50. }
  51. p.encodedData = data
  52. compData, err := compress(data, rpcInfo.preloaderInfo.cp, rpcInfo.preloaderInfo.comp)
  53. if err != nil {
  54. return err
  55. }
  56. p.hdr, p.payload = msgHeader(data, compData)
  57. return nil
  58. }