1# Copyright 2017 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"""Interceptor that adds headers to outgoing requests."""
15
16import collections
17
18import grpc
19
20
21class _ConcreteValue(grpc.Future):
22
23    def __init__(self, result):
24        self._result = result
25
26    def cancel(self):
27        return False
28
29    def cancelled(self):
30        return False
31
32    def running(self):
33        return False
34
35    def done(self):
36        return True
37
38    def result(self, timeout=None):
39        return self._result
40
41    def exception(self, timeout=None):
42        return None
43
44    def traceback(self, timeout=None):
45        return None
46
47    def add_done_callback(self, fn):
48        fn(self._result)
49
50
51class DefaultValueClientInterceptor(grpc.UnaryUnaryClientInterceptor,
52                                    grpc.StreamUnaryClientInterceptor):
53
54    def __init__(self, value):
55        self._default = _ConcreteValue(value)
56
57    def _intercept_call(self, continuation, client_call_details,
58                        request_or_iterator):
59        response = continuation(client_call_details, request_or_iterator)
60        return self._default if response.exception() else response
61
62    def intercept_unary_unary(self, continuation, client_call_details, request):
63        return self._intercept_call(continuation, client_call_details, request)
64
65    def intercept_stream_unary(self, continuation, client_call_details,
66                               request_iterator):
67        return self._intercept_call(continuation, client_call_details,
68                                    request_iterator)
69