Skip to content

Commit 2b456d3

Browse files
committed
fix(grpc): mask a failed outbound RPC instead of re-raising it (#86)
UnhandledErrorInterceptor re-raised grpc.RpcError alongside grpc.aio.AbortError. A client-side AioRpcError is a grpc.RpcError, so a failed outbound call reached the caller as UNKNOWN with the downstream details. Only AbortError carries a status the handler chose; everything else is logged and masked as INTERNAL / internal_error. Closes #86
1 parent e11de17 commit 2b456d3

4 files changed

Lines changed: 104 additions & 18 deletions

File tree

‎docs/adapters/grpc.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,14 @@ indistinguishable to a caller. Without it `grpc.aio` answers `UNKNOWN` with `rep
106106
exception, so the one error class whose wording nobody reviewed is the one that reaches the wire
107107
verbatim.
108108

109-
Three things are left alone, because each already carries a decision:
110-
`grpc.aio.AbortError` and `grpc.RpcError` (a status a handler chose itself) are re-raised, and
109+
Two things are left alone, because each already carries a decision: `grpc.aio.AbortError`, which
110+
`context.abort()` raises with a status the handler chose itself, is re-raised, and
111111
`asyncio.CancelledError` never reaches it — a caller that walked away is not a failure to report.
112112

113+
A failed outbound call is not one of them. `grpc.aio.AioRpcError` is the status a downstream service
114+
returned to this server; re-raised, it would reach your caller as `UNKNOWN` with the downstream
115+
details in it. It is logged and masked like any other unhandled exception.
116+
113117
`map_service_errors=False` does not remove it. That flag turns off the mapping of the errors you
114118
declared; with it off a `ServiceError` reaches the client as a masked `INTERNAL` like any other
115119
unhandled exception, never as its own message.

‎servicewright/adapters/grpc/errors.py‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,17 +105,19 @@ class UnhandledErrorInterceptor(AsyncServerInterceptor):
105105
:class:`GrpcEntrypoint` adds it inside :class:`UnitScopeInterceptor` — so
106106
the log record still carries the correlation ids — and outside your own
107107
interceptors, so an exception type you map yourself reaches your
108-
interceptor first and never gets here. A deliberate status passes through:
109-
``grpc.aio.AbortError`` and ``grpc.RpcError`` are re-raised, and
110-
``asyncio.CancelledError`` is a ``BaseException``, so a caller that walks
111-
away is not an error to report.
108+
interceptor first and never gets here. Only ``grpc.aio.AbortError`` passes
109+
through: ``context.abort()`` raises it, so its status is one the handler
110+
chose. A ``grpc.aio.AioRpcError`` from an outbound call is the status a
111+
downstream service gave this server, and it is masked like any other
112+
exception. ``asyncio.CancelledError`` is a ``BaseException``, so a caller
113+
that walks away is not an error to report.
112114
"""
113115

114116
async def around_call(self, call: RpcCall) -> AsyncIterator[None]:
115117
"""Run the RPC; mask anything that comes out of it without a status."""
116118
try:
117119
yield
118-
except (grpc.aio.AbortError, grpc.RpcError):
120+
except grpc.aio.AbortError:
119121
raise
120122
except Exception:
121123
logger.exception("Unhandled exception while serving RPC", extra={"grpc_method": call.method_name})

‎tests/integration/test_grpc_integration.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,59 @@ async def call_then_stop() -> None:
107107
assert error.details() == "internal_error"
108108
assert dict(error.trailing_metadata() or ())["x-error-code"] == "internal_error"
109109
assert _SECRET not in str(error.details())
110+
111+
112+
async def test__grpc_entrypoint__outbound_call_fails__client_gets_a_masked_internal() -> None:
113+
# Arrange — a downstream service that aborts with a message meant for nobody outside.
114+
async def get(request: bytes, context: grpc.aio.ServicerContext[bytes, bytes]) -> bytes:
115+
await context.abort(grpc.StatusCode.INTERNAL, _SECRET)
116+
117+
downstream = grpc.aio.server()
118+
downstream.add_generic_rpc_handlers(
119+
(grpc.method_handlers_generic_handler("lab.Ledger", {"Get": grpc.unary_unary_rpc_method_handler(get)}),)
120+
)
121+
downstream_port = downstream.add_insecure_port("127.0.0.1:0")
122+
await downstream.start()
123+
124+
def register_forwarding_servicer(server: Any, _ctx: Any) -> None:
125+
async def pay(request: bytes, context: Any) -> bytes:
126+
async with grpc.aio.insecure_channel(f"127.0.0.1:{downstream_port}") as channel:
127+
return await channel.unary_unary("/lab.Ledger/Get")(request, timeout=5)
128+
129+
server.add_generic_rpc_handlers(
130+
(grpc.method_handlers_generic_handler(_SERVICE, {"Pay": grpc.unary_unary_rpc_method_handler(pay)}),)
131+
)
132+
133+
spec: AppSpec[Any, Any] = AppSpec(service_name="grpc-outbound-it", create_container=lambda _s: FakeContainer())
134+
config = GrpcConfig(host="127.0.0.1", port=0, enable_reflection=False, enable_channelz=False)
135+
ep = GrpcEntrypoint(config=config, servicers=register_forwarding_servicer)
136+
service = Service(spec, entrypoints=[ep])
137+
138+
stop = asyncio.Event()
139+
failures: list[grpc.aio.AioRpcError] = []
140+
141+
async def call_then_stop() -> None:
142+
while not (spec.health.ready and ep.bound_port):
143+
await asyncio.sleep(0.01)
144+
await asyncio.sleep(0.05)
145+
146+
async with grpc.aio.insecure_channel(f"127.0.0.1:{ep.bound_port}") as channel:
147+
try:
148+
await channel.unary_unary(f"/{_SERVICE}/Pay")(b"42", timeout=5)
149+
except grpc.aio.AioRpcError as error:
150+
failures.append(error)
151+
152+
stop.set()
153+
154+
# Act
155+
try:
156+
await asyncio.gather(service.run(FakeSettings(), stop=stop), call_then_stop())
157+
finally:
158+
await downstream.stop(grace=None)
159+
160+
# Assert — re-raised, the downstream AioRpcError would reach the client as UNKNOWN with its details.
161+
error = failures[0]
162+
assert error.code() is grpc.StatusCode.INTERNAL
163+
assert error.details() == "internal_error"
164+
assert dict(error.trailing_metadata() or ())["x-error-code"] == "internal_error"
165+
assert _SECRET not in str(error.details())

‎tests/unit/test_grpc.py‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -930,28 +930,52 @@ async def test__unhandled_error_interceptor__service_error__masks_it_too() -> No
930930
assert "user_missing" not in details
931931

932932

933+
async def test__unhandled_error_interceptor__handler_aborted__passes_the_status_through() -> None:
934+
# Arrange
935+
from servicewright.adapters.grpc import UnhandledErrorInterceptor
936+
937+
context = _AbortRecordingContext()
938+
939+
# Act
940+
with pytest.raises(grpc.aio.AbortError):
941+
async with UnhandledErrorInterceptor().around(_make_call(context, "/pkg.Svc/Rpc")):
942+
raise grpc.aio.AbortError("already aborted")
943+
944+
# Assert
945+
assert context.aborts == []
946+
947+
933948
@pytest.mark.parametrize(
934-
"deliberate",
949+
"downstream",
935950
[
936-
pytest.param(grpc.aio.AbortError("already aborted"), id="abort-error"),
937-
pytest.param(grpc.RpcError("already failed"), id="rpc-error"),
951+
pytest.param(
952+
grpc.aio.AioRpcError(
953+
grpc.StatusCode.INTERNAL,
954+
grpc.aio.Metadata(),
955+
grpc.aio.Metadata(),
956+
details="ledger dsn=postgres://user:pw@db/ledger",
957+
),
958+
id="aio-rpc-error",
959+
),
960+
pytest.param(grpc.RpcError("ledger dsn=postgres://user:pw@db/ledger"), id="rpc-error"),
938961
],
939962
)
940-
async def test__unhandled_error_interceptor__status_already_chosen__passes_it_through(
941-
deliberate: Exception,
942-
) -> None:
963+
async def test__unhandled_error_interceptor__outbound_call_failed__masks_it(downstream: grpc.RpcError) -> None:
943964
# Arrange
944-
from servicewright.adapters.grpc import UnhandledErrorInterceptor
965+
from servicewright.adapters.grpc import ERROR_CODE_TRAILING_METADATA, UnhandledErrorInterceptor
945966

946967
context = _AbortRecordingContext()
947968

948969
# Act
949-
with pytest.raises(type(deliberate)):
970+
with pytest.raises(_AbortedSentinelError):
950971
async with UnhandledErrorInterceptor().around(_make_call(context, "/pkg.Svc/Rpc")):
951-
raise deliberate
972+
raise downstream
952973

953-
# Assert
954-
assert context.aborts == []
974+
# Assert — re-raised, grpc.aio would answer UNKNOWN with the downstream details.
975+
(code, details, trailing) = context.aborts[0]
976+
assert code == grpc.StatusCode.INTERNAL
977+
assert details == "internal_error"
978+
assert trailing == ((ERROR_CODE_TRAILING_METADATA, "internal_error"),)
955979

956980

957981
async def test__unhandled_error_interceptor__caller_cancelled__passes_it_through() -> None:

0 commit comments

Comments
 (0)