_compression.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright 2019 The gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from grpc._cython import cygrpc
  15. NoCompression = cygrpc.CompressionAlgorithm.none
  16. Deflate = cygrpc.CompressionAlgorithm.deflate
  17. Gzip = cygrpc.CompressionAlgorithm.gzip
  18. _METADATA_STRING_MAPPING = {
  19. NoCompression: 'identity',
  20. Deflate: 'deflate',
  21. Gzip: 'gzip',
  22. }
  23. def _compression_algorithm_to_metadata_value(compression):
  24. return _METADATA_STRING_MAPPING[compression]
  25. def compression_algorithm_to_metadata(compression):
  26. return (cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
  27. _compression_algorithm_to_metadata_value(compression))
  28. def create_channel_option(compression):
  29. return ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
  30. int(compression)),) if compression else ()
  31. def augment_metadata(metadata, compression):
  32. if not metadata and not compression:
  33. return None
  34. base_metadata = tuple(metadata) if metadata else ()
  35. compression_metadata = (
  36. compression_algorithm_to_metadata(compression),) if compression else ()
  37. return base_metadata + compression_metadata
  38. __all__ = (
  39. "NoCompression",
  40. "Deflate",
  41. "Gzip",
  42. )