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"""Base class for interceptors that operate on all RPC types.""" 15 16import grpc 17 18 19class _GenericClientInterceptor( 20 grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor, 21 grpc.StreamUnaryClientInterceptor, grpc.StreamStreamClientInterceptor): 22 23 def __init__(self, interceptor_function): 24 self._fn = interceptor_function 25 26 def intercept_unary_unary(self, continuation, client_call_details, request): 27 new_details, new_request_iterator, postprocess = self._fn( 28 client_call_details, iter((request,)), False, False) 29 response = continuation(new_details, next(new_request_iterator)) 30 return postprocess(response) if postprocess else response 31 32 def intercept_unary_stream(self, continuation, client_call_details, 33 request): 34 new_details, new_request_iterator, postprocess = self._fn( 35 client_call_details, iter((request,)), False, True) 36 response_it = continuation(new_details, next(new_request_iterator)) 37 return postprocess(response_it) if postprocess else response_it 38 39 def intercept_stream_unary(self, continuation, client_call_details, 40 request_iterator): 41 new_details, new_request_iterator, postprocess = self._fn( 42 client_call_details, request_iterator, True, False) 43 response = continuation(new_details, new_request_iterator) 44 return postprocess(response) if postprocess else response 45 46 def intercept_stream_stream(self, continuation, client_call_details, 47 request_iterator): 48 new_details, new_request_iterator, postprocess = self._fn( 49 client_call_details, request_iterator, True, True) 50 response_it = continuation(new_details, new_request_iterator) 51 return postprocess(response_it) if postprocess else response_it 52 53 54def create(intercept_call): 55 return _GenericClientInterceptor(intercept_call) 56