_compression.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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,
  29. ) -> str:
  30. return _METADATA_STRING_MAPPING[compression]
  31. def compression_algorithm_to_metadata(compression: grpc.Compression):
  32. return (
  33. cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
  34. _compression_algorithm_to_metadata_value(compression),
  35. )
  36. def create_channel_option(compression: Optional[grpc.Compression]):
  37. return (
  38. ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, int(compression)),)
  39. if compression
  40. else ()
  41. )
  42. def augment_metadata(
  43. metadata: Optional[MetadataType], compression: Optional[grpc.Compression]
  44. ):
  45. if not metadata and not compression:
  46. return None
  47. base_metadata = tuple(metadata) if metadata else ()
  48. compression_metadata = (
  49. (compression_algorithm_to_metadata(compression),) if compression else ()
  50. )
  51. return base_metadata + compression_metadata
  52. __all__ = (
  53. "NoCompression",
  54. "Deflate",
  55. "Gzip",
  56. )