Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/grpc/_common.py
7765 views
# Copyright 2016 gRPC authors.1#2# Licensed under the Apache License, Version 2.0 (the "License");3# you may not use this file except in compliance with the License.4# You may obtain a copy of the License at5#6# http://www.apache.org/licenses/LICENSE-2.07#8# Unless required by applicable law or agreed to in writing, software9# distributed under the License is distributed on an "AS IS" BASIS,10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11# See the License for the specific language governing permissions and12# limitations under the License.13"""Shared implementation."""1415import logging16import time1718import grpc19from grpc._cython import cygrpc20import six2122_LOGGER = logging.getLogger(__name__)2324CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = {25cygrpc.ConnectivityState.idle:26grpc.ChannelConnectivity.IDLE,27cygrpc.ConnectivityState.connecting:28grpc.ChannelConnectivity.CONNECTING,29cygrpc.ConnectivityState.ready:30grpc.ChannelConnectivity.READY,31cygrpc.ConnectivityState.transient_failure:32grpc.ChannelConnectivity.TRANSIENT_FAILURE,33cygrpc.ConnectivityState.shutdown:34grpc.ChannelConnectivity.SHUTDOWN,35}3637CYGRPC_STATUS_CODE_TO_STATUS_CODE = {38cygrpc.StatusCode.ok: grpc.StatusCode.OK,39cygrpc.StatusCode.cancelled: grpc.StatusCode.CANCELLED,40cygrpc.StatusCode.unknown: grpc.StatusCode.UNKNOWN,41cygrpc.StatusCode.invalid_argument: grpc.StatusCode.INVALID_ARGUMENT,42cygrpc.StatusCode.deadline_exceeded: grpc.StatusCode.DEADLINE_EXCEEDED,43cygrpc.StatusCode.not_found: grpc.StatusCode.NOT_FOUND,44cygrpc.StatusCode.already_exists: grpc.StatusCode.ALREADY_EXISTS,45cygrpc.StatusCode.permission_denied: grpc.StatusCode.PERMISSION_DENIED,46cygrpc.StatusCode.unauthenticated: grpc.StatusCode.UNAUTHENTICATED,47cygrpc.StatusCode.resource_exhausted: grpc.StatusCode.RESOURCE_EXHAUSTED,48cygrpc.StatusCode.failed_precondition: grpc.StatusCode.FAILED_PRECONDITION,49cygrpc.StatusCode.aborted: grpc.StatusCode.ABORTED,50cygrpc.StatusCode.out_of_range: grpc.StatusCode.OUT_OF_RANGE,51cygrpc.StatusCode.unimplemented: grpc.StatusCode.UNIMPLEMENTED,52cygrpc.StatusCode.internal: grpc.StatusCode.INTERNAL,53cygrpc.StatusCode.unavailable: grpc.StatusCode.UNAVAILABLE,54cygrpc.StatusCode.data_loss: grpc.StatusCode.DATA_LOSS,55}56STATUS_CODE_TO_CYGRPC_STATUS_CODE = {57grpc_code: cygrpc_code for cygrpc_code, grpc_code in six.iteritems(58CYGRPC_STATUS_CODE_TO_STATUS_CODE)59}6061MAXIMUM_WAIT_TIMEOUT = 0.16263_ERROR_MESSAGE_PORT_BINDING_FAILED = 'Failed to bind to address %s; set ' \64'GRPC_VERBOSITY=debug environment variable to see detailed error message.'656667def encode(s):68if isinstance(s, bytes):69return s70else:71return s.encode('utf8')727374def decode(b):75if isinstance(b, bytes):76return b.decode('utf-8', 'replace')77return b787980def _transform(message, transformer, exception_message):81if transformer is None:82return message83else:84try:85return transformer(message)86except Exception: # pylint: disable=broad-except87_LOGGER.exception(exception_message)88return None899091def serialize(message, serializer):92return _transform(message, serializer, 'Exception serializing message!')939495def deserialize(serialized_message, deserializer):96return _transform(serialized_message, deserializer,97'Exception deserializing message!')9899100def fully_qualified_method(group, method):101return '/{}/{}'.format(group, method)102103104def _wait_once(wait_fn, timeout, spin_cb):105wait_fn(timeout=timeout)106if spin_cb is not None:107spin_cb()108109110def wait(wait_fn, wait_complete_fn, timeout=None, spin_cb=None):111"""Blocks waiting for an event without blocking the thread indefinitely.112113See https://github.com/grpc/grpc/issues/19464 for full context. CPython's114`threading.Event.wait` and `threading.Condition.wait` methods, if invoked115without a timeout kwarg, may block the calling thread indefinitely. If the116call is made from the main thread, this means that signal handlers may not117run for an arbitrarily long period of time.118119This wrapper calls the supplied wait function with an arbitrary short120timeout to ensure that no signal handler has to wait longer than121MAXIMUM_WAIT_TIMEOUT before executing.122123Args:124wait_fn: A callable acceptable a single float-valued kwarg named125`timeout`. This function is expected to be one of `threading.Event.wait`126or `threading.Condition.wait`.127wait_complete_fn: A callable taking no arguments and returning a bool.128When this function returns true, it indicates that waiting should cease.129timeout: An optional float-valued number of seconds after which the wait130should cease.131spin_cb: An optional Callable taking no arguments and returning nothing.132This callback will be called on each iteration of the spin. This may be133used for, e.g. work related to forking.134135Returns:136True if a timeout was supplied and it was reached. False otherwise.137"""138if timeout is None:139while not wait_complete_fn():140_wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)141else:142end = time.time() + timeout143while not wait_complete_fn():144remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)145if remaining < 0:146return True147_wait_once(wait_fn, remaining, spin_cb)148return False149150151def validate_port_binding_result(address, port):152"""Validates if the port binding succeed.153154If the port returned by Core is 0, the binding is failed. However, in that155case, the Core API doesn't return a detailed failing reason. The best we156can do is raising an exception to prevent further confusion.157158Args:159address: The address string to be bound.160port: An int returned by core161"""162if port == 0:163# The Core API doesn't return a failure message. The best we can do164# is raising an exception to prevent further confusion.165raise RuntimeError(_ERROR_MESSAGE_PORT_BINDING_FAILED % address)166else:167return port168169170