1# Copyright 2023 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"""This contains common helpers for working with grpc data structures.""" 15import functools 16from typing import Optional 17 18import grpc 19 20 21@functools.cache # pylint: disable=no-member 22def status_from_int(grpc_status_int: int) -> Optional[grpc.StatusCode]: 23 """Converts the integer gRPC status code to the grpc.StatusCode enum.""" 24 for grpc_status in grpc.StatusCode: 25 if grpc_status.value[0] == grpc_status_int: 26 return grpc_status 27 return None 28 29 30def status_eq(grpc_status_int: int, grpc_status: grpc.StatusCode) -> bool: 31 """Compares the integer gRPC status code with the grpc.StatusCode enum.""" 32 return status_from_int(grpc_status_int) is grpc_status 33 34 35def status_pretty(grpc_status: grpc.StatusCode) -> str: 36 """Formats the status code as (int, NAME), f.e. (4, DEADLINE_EXCEEDED)""" 37 return f"({grpc_status.value[0]}, {grpc_status.name})" 38