|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Typed gateway errors that retain the original gRPC status and metadata.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from dataclasses import dataclass |
| 9 | + |
| 10 | +import grpc |
| 11 | +from google.protobuf.message import DecodeError |
| 12 | +from google.rpc import error_details_pb2, status_pb2 |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class FieldViolation: |
| 17 | + """A request field rejected by the gateway.""" |
| 18 | + |
| 19 | + field: str |
| 20 | + description: str |
| 21 | + |
| 22 | + |
| 23 | +@dataclass(frozen=True) |
| 24 | +class ErrorInfo: |
| 25 | + """A machine-readable error reason scoped to its producing service.""" |
| 26 | + |
| 27 | + reason: str |
| 28 | + domain: str |
| 29 | + metadata: dict[str, str] |
| 30 | + |
| 31 | + |
| 32 | +class GatewayError(grpc.RpcError): |
| 33 | + """A gRPC failure with decoded standard details. |
| 34 | +
|
| 35 | + ``raw_error`` retains the complete original exception and metadata. |
| 36 | + ``raw_status`` retains all decoded Any messages, including unknown types. |
| 37 | + A retry delay is guidance only; it does not make a mutation safe to repeat. |
| 38 | + Existing ``except grpc.RpcError`` handlers continue to match this type. |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, error: grpc.RpcError) -> None: |
| 42 | + super().__init__(str(error)) |
| 43 | + self.raw_error = error |
| 44 | + self.raw_status: status_pb2.Status | None = None |
| 45 | + self.field_violations: tuple[FieldViolation, ...] = () |
| 46 | + self.error_info: ErrorInfo | None = None |
| 47 | + self.retry_delay: float | None = None |
| 48 | + trailing = getattr(error, "trailing_metadata", lambda: None)() or () |
| 49 | + for key, value in trailing: |
| 50 | + if key != "grpc-status-details-bin" or not isinstance(value, bytes): |
| 51 | + continue |
| 52 | + try: |
| 53 | + status = status_pb2.Status.FromString(value) |
| 54 | + except DecodeError: |
| 55 | + continue |
| 56 | + # The transport status is authoritative. Inconsistent rich status |
| 57 | + # must not provide misleading recovery guidance. |
| 58 | + code = self.code() |
| 59 | + if ( |
| 60 | + code is None |
| 61 | + or status.code != code.value[0] |
| 62 | + or status.message != self.details() |
| 63 | + ): |
| 64 | + continue |
| 65 | + self.raw_status = status |
| 66 | + break |
| 67 | + if self.raw_status is None: |
| 68 | + return |
| 69 | + violations = [] |
| 70 | + for detail in self.raw_status.details: |
| 71 | + try: |
| 72 | + if detail.Is(error_details_pb2.BadRequest.DESCRIPTOR): |
| 73 | + bad_request = error_details_pb2.BadRequest() |
| 74 | + detail.Unpack(bad_request) |
| 75 | + violations.extend( |
| 76 | + FieldViolation(v.field, v.description) |
| 77 | + for v in bad_request.field_violations |
| 78 | + ) |
| 79 | + elif detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR): |
| 80 | + info = error_details_pb2.ErrorInfo() |
| 81 | + detail.Unpack(info) |
| 82 | + self.error_info = ErrorInfo( |
| 83 | + info.reason, info.domain, dict(info.metadata) |
| 84 | + ) |
| 85 | + elif detail.Is(error_details_pb2.RetryInfo.DESCRIPTOR): |
| 86 | + retry = error_details_pb2.RetryInfo() |
| 87 | + detail.Unpack(retry) |
| 88 | + delay = retry.retry_delay |
| 89 | + if ( |
| 90 | + retry.HasField("retry_delay") |
| 91 | + and 0 <= delay.seconds <= 315_576_000_000 |
| 92 | + and 0 <= delay.nanos < 1_000_000_000 |
| 93 | + ): |
| 94 | + self.retry_delay = delay.seconds + delay.nanos / 1_000_000_000 |
| 95 | + except DecodeError: |
| 96 | + continue |
| 97 | + self.field_violations = tuple(violations) |
| 98 | + |
| 99 | + def code(self): |
| 100 | + """Return the original gRPC status code.""" |
| 101 | + return getattr(self.raw_error, "code", lambda: None)() |
| 102 | + |
| 103 | + def details(self): |
| 104 | + """Return the original human-readable gRPC message.""" |
| 105 | + return getattr(self.raw_error, "details", lambda: str(self.raw_error))() |
| 106 | + |
| 107 | + def __getattr__(self, name): |
| 108 | + return getattr(self.raw_error, name) |
| 109 | + |
| 110 | + |
| 111 | +def from_grpc_error(error: grpc.RpcError) -> GatewayError: |
| 112 | + """Decode a raw RPC failure without discarding unrecognized details.""" |
| 113 | + return error if isinstance(error, GatewayError) else GatewayError(error) |
| 114 | + |
| 115 | + |
| 116 | +class _ErrorMappingStream: |
| 117 | + def __init__(self, call): |
| 118 | + self._call = call |
| 119 | + self._iterator = iter(call) |
| 120 | + |
| 121 | + def __iter__(self): |
| 122 | + return self |
| 123 | + |
| 124 | + def __next__(self): |
| 125 | + try: |
| 126 | + return next(self._iterator) |
| 127 | + except grpc.RpcError as error: |
| 128 | + raise from_grpc_error(error) from error |
| 129 | + |
| 130 | + def __getattr__(self, name): |
| 131 | + return getattr(self._call, name) |
| 132 | + |
| 133 | + |
| 134 | +class _ErrorMappingInterceptor( |
| 135 | + grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor |
| 136 | +): |
| 137 | + def intercept_unary_unary(self, continuation, client_call_details, request): |
| 138 | + call = continuation(client_call_details, request) |
| 139 | + error = call.exception() |
| 140 | + if isinstance(error, grpc.RpcError): |
| 141 | + raise from_grpc_error(error) from error |
| 142 | + return call |
| 143 | + |
| 144 | + def intercept_unary_stream(self, continuation, client_call_details, request): |
| 145 | + return _ErrorMappingStream(continuation(client_call_details, request)) |
| 146 | + |
| 147 | + |
| 148 | +def _error_mapping_channel(channel): |
| 149 | + return grpc.intercept_channel(channel, _ErrorMappingInterceptor()) |
0 commit comments