Imported Upstream version 1.28.1
[platform/upstream/grpc.git] / src / python / grpcio / grpc / _compression.py
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
15 from grpc._cython import cygrpc
16
17 NoCompression = cygrpc.CompressionAlgorithm.none
18 Deflate = cygrpc.CompressionAlgorithm.deflate
19 Gzip = cygrpc.CompressionAlgorithm.gzip
20
21 _METADATA_STRING_MAPPING = {
22     NoCompression: 'identity',
23     Deflate: 'deflate',
24     Gzip: 'gzip',
25 }
26
27
28 def _compression_algorithm_to_metadata_value(compression):
29     return _METADATA_STRING_MAPPING[compression]
30
31
32 def compression_algorithm_to_metadata(compression):
33     return (cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
34             _compression_algorithm_to_metadata_value(compression))
35
36
37 def create_channel_option(compression):
38     return ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
39              int(compression)),) if compression else ()
40
41
42 def augment_metadata(metadata, compression):
43     if not metadata and not compression:
44         return None
45     base_metadata = tuple(metadata) if metadata else ()
46     compression_metadata = (
47         compression_algorithm_to_metadata(compression),) if compression else ()
48     return base_metadata + compression_metadata
49
50
51 __all__ = (
52     "NoCompression",
53     "Deflate",
54     "Gzip",
55 )