_compression.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 __future__ import annotations
  15. from typing import Optional
  16. import grpc
  17. from grpc._cython import cygrpc
  18. from grpc._typing import MetadataType
  19. NoCompression = cygrpc.CompressionAlgorithm.none
  20. Deflate = cygrpc.CompressionAlgorithm.deflate
  21. Gzip = cygrpc.CompressionAlgorithm.gzip
  22. _METADATA_STRING_MAPPING = {
  23. NoCompression: 'identity',
  24. Deflate: 'deflate',
  25. Gzip: 'gzip',
  26. }
  27. def _compression_algorithm_to_metadata_value(
  28. compression: grpc.Compression) -> str:
  29. return _METADATA_STRING_MAPPING[compression]
  30. def compression_algorithm_to_metadata(compression: grpc.Compression):
  31. return (cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
  32. _compression_algorithm_to_metadata_value(compression))
  33. def create_channel_option(compression: Optional[grpc.Compression]):
  34. return ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
  35. int(compression)),) if compression else ()
  36. def augment_metadata(metadata: Optional[MetadataType],
  37. compression: Optional[grpc.Compression]):
  38. if not metadata and not compression:
  39. return None
  40. base_metadata = tuple(metadata) if metadata else ()
  41. compression_metadata = (
  42. compression_algorithm_to_metadata(compression),) if compression else ()
  43. return base_metadata + compression_metadata
  44. __all__ = (
  45. "NoCompression",
  46. "Deflate",
  47. "Gzip",
  48. )