fix(client-python): keepalive options, typed error mapping with status code, open-enum names, malformed-reply checks (CPY-001..004, #257)

This commit is contained in:
Joseph Doherty
2026-12-03 09:46:02 -05:00
parent fafd79fa12
commit 3173ad7083
9 changed files with 365 additions and 14 deletions
@@ -18,7 +18,9 @@ from .errors import (
MxGatewayCommandError,
MxGatewayError,
MxGatewaySessionError,
MxGatewayTimeoutError,
MxGatewayTransportError,
MxGatewayUnavailableError,
MxGatewayWorkerError,
)
from .options import BrowseChildrenOptions, ClientOptions
@@ -43,7 +45,9 @@ __all__ = [
"MxGatewayCommandError",
"MxGatewayError",
"MxGatewaySessionError",
"MxGatewayTimeoutError",
"MxGatewayTransportError",
"MxGatewayUnavailableError",
"MxGatewayWorkerError",
"MxValueView",
"ReplayGap",
@@ -1,5 +1,6 @@
"""Authentication metadata helpers for MXAccess Gateway clients."""
import re
from collections.abc import Sequence
from dataclasses import dataclass
@@ -51,6 +52,21 @@ def merge_metadata(
return tuple(merged)
_CREDENTIAL_PATTERN = re.compile(r"mxgw_[A-Za-z0-9_-]+|\bbearer\b", re.IGNORECASE)
def redact_credentials(text: str | None) -> str:
"""Scrub credential-shaped text (``mxgw_<id>_<secret>`` keys, ``Bearer``) from `text`.
Library users get this on every mapped gRPC error without having to supply
the secret; a proxy or gateway error path can echo the authorization value.
"""
if not text:
return text or ""
return _CREDENTIAL_PATTERN.sub(REDACTED, text)
def redact_secret(text: str, secrets: Sequence[str | None]) -> str:
"""Replace known secret values with a stable redaction marker."""
@@ -6,9 +6,23 @@ from typing import Any
import grpc
from .auth import redact_credentials
from .generated import mxaccess_gateway_pb2 as pb
def _enum_name(enum_type: Any, value: int) -> str:
"""Return the enum member name, or the number when the value is unknown.
proto3 enums are open: a gateway newer than this client's generated code can
send a value the client has no name for, and ``Name()`` would raise
``ValueError`` in place of the typed gateway error being built.
"""
try:
return str(enum_type.Name(value))
except ValueError:
return str(value)
class MxGatewayError(Exception):
"""Base class for client wrapper errors."""
@@ -26,7 +40,24 @@ class MxGatewayError(Exception):
class MxGatewayTransportError(MxGatewayError):
"""Transport-level gRPC failure."""
"""Transport-level gRPC failure.
`code` is the gRPC status code that produced it (``None`` when the error did
not come from a status), so reconnect/backoff logic does not have to reach
into ``__cause__``.
"""
def __init__(
self,
message: str,
*,
protocol_status: pb.ProtocolStatus | None = None,
raw_reply: Any | None = None,
code: grpc.StatusCode | None = None,
) -> None:
"""Initialize with a message and the optional gRPC status code."""
super().__init__(message, protocol_status=protocol_status, raw_reply=raw_reply)
self.code = code
class MxGatewayAuthenticationError(MxGatewayTransportError):
@@ -37,6 +68,14 @@ class MxGatewayAuthorizationError(MxGatewayTransportError):
"""Authorization failure reported by gRPC."""
class MxGatewayTimeoutError(MxGatewayTransportError):
"""The call's deadline expired (``DEADLINE_EXCEEDED``); a write may or may not have applied."""
class MxGatewayUnavailableError(MxGatewayTransportError):
"""The gateway is unreachable or shedding load (``UNAVAILABLE`` / ``RESOURCE_EXHAUSTED``)."""
class MxGatewaySessionError(MxGatewayError):
"""Gateway session failure."""
@@ -58,18 +97,27 @@ class MalformedReplyError(MxGatewayError):
def map_rpc_error(operation: str, error: grpc.RpcError) -> MxGatewayTransportError:
"""Map a generated gRPC exception to the client exception hierarchy."""
"""Map a generated gRPC exception to the client exception hierarchy.
The status code is preserved on the result (``.code``), distinct types cover
the cases a retry loop must tell apart, and credential-shaped text is scrubbed
from the server-supplied details.
"""
code = error.code() if hasattr(error, "code") else None
details = error.details() if hasattr(error, "details") else str(error)
message = f"{operation} failed: {details}"
message = f"{operation} failed: {redact_credentials(details)}"
if code == grpc.StatusCode.UNAUTHENTICATED:
return MxGatewayAuthenticationError(message)
return MxGatewayAuthenticationError(message, code=code)
if code == grpc.StatusCode.PERMISSION_DENIED:
return MxGatewayAuthorizationError(message)
return MxGatewayAuthorizationError(message, code=code)
if code == grpc.StatusCode.DEADLINE_EXCEEDED:
return MxGatewayTimeoutError(message, code=code)
if code in (grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.RESOURCE_EXHAUSTED):
return MxGatewayUnavailableError(message, code=code)
return MxGatewayTransportError(message)
return MxGatewayTransportError(message, code=code)
def ensure_protocol_success(
@@ -92,7 +140,7 @@ def ensure_protocol_success(
return raw_reply
message_text = protocol_status.message if protocol_status else ""
message = f"{operation} failed: {message_text or pb.ProtocolStatusCode.Name(code)}"
message = f"{operation} failed: {message_text or _enum_name(pb.ProtocolStatusCode, code)}"
if code in (
pb.PROTOCOL_STATUS_CODE_SESSION_NOT_FOUND,
@@ -166,7 +214,7 @@ def _mxaccess_message(operation: str, reply: pb.MxCommandReply) -> str:
# verbatim for diagnostic parity with the other clients. `category` remains
# the authoritative verdict; `success` is diagnostics only.
for status in reply.statuses:
category = pb.MxStatusCategory.Name(status.category)
category = _enum_name(pb.MxStatusCategory, status.category)
message += (
f" [success={status.success}, category={category}, "
f"detail={status.detail}, {status.diagnostic_text}]"
@@ -30,6 +30,16 @@ class ClientOptions:
call_timeout: float | None = 30.0
stream_timeout: float | None = None
max_grpc_message_bytes: int = 16 * 1024 * 1024
#: HTTP/2 keepalive ping interval in seconds (``None`` disables keepalive).
#: Keep it at or above the gateway's permitted client ping interval (30 s by
#: default) or the gateway answers with GOAWAY (``too_many_pings``).
keepalive_time: float | None = 30.0
#: Seconds to wait for a keepalive ping acknowledgement before the
#: connection is treated as dead.
keepalive_timeout: float = 10.0
#: Send keepalive pings while no call is active. Required so an idle channel
#: between calls is still probed.
keepalive_permit_without_calls: bool = True
def __post_init__(self) -> None:
"""Validate options; raise `ValueError` for invalid combinations."""
@@ -44,6 +54,10 @@ class ClientOptions:
raise ValueError("stream_timeout must be greater than zero")
if self.max_grpc_message_bytes <= 0:
raise ValueError("max_grpc_message_bytes must be greater than zero")
if self.keepalive_time is not None and self.keepalive_time <= 0:
raise ValueError("keepalive_time must be greater than zero")
if self.keepalive_timeout <= 0:
raise ValueError("keepalive_timeout must be greater than zero")
def __repr__(self) -> str:
"""Return a repr that redacts the API key value."""
@@ -56,7 +70,10 @@ class ClientOptions:
f"server_name_override={self.server_name_override!r}, "
f"call_timeout={self.call_timeout!r}, "
f"stream_timeout={self.stream_timeout!r}, "
f"max_grpc_message_bytes={self.max_grpc_message_bytes!r})"
f"max_grpc_message_bytes={self.max_grpc_message_bytes!r}, "
f"keepalive_time={self.keepalive_time!r}, "
f"keepalive_timeout={self.keepalive_timeout!r}, "
f"keepalive_permit_without_calls={self.keepalive_permit_without_calls!r})"
)
@@ -191,6 +208,22 @@ def create_channel(
("grpc.max_receive_message_length", options.max_grpc_message_bytes),
("grpc.max_send_message_length", options.max_grpc_message_bytes),
]
if options.keepalive_time is not None:
# Without keepalive a half-open connection (firewall idle-out, host power
# loss) leaves a deadline-less stream waiting forever.
# `max_pings_without_data=0` lets the client keep pinging with no data in
# flight; the gateway's matching ping policy permits the 30 s interval.
channel_options.extend(
[
("grpc.keepalive_time_ms", int(options.keepalive_time * 1000)),
("grpc.keepalive_timeout_ms", int(options.keepalive_timeout * 1000)),
(
"grpc.keepalive_permit_without_calls",
1 if options.keepalive_permit_without_calls else 0,
),
("grpc.http2.max_pings_without_data", 0),
]
)
if options.server_name_override:
channel_options.append(("grpc.ssl_target_name_override", options.server_name_override))
elif security.target_name_override:
@@ -94,7 +94,9 @@ class Session:
),
correlation_id=correlation_id,
)
return reply.register.server_handle
if reply.HasField("register"):
return reply.register.server_handle
return _int32_return_value_or_raise("register", reply)
async def unregister(self, server_handle: int, *, correlation_id: str = "") -> None:
"""Invoke MXAccess `Unregister` for a previously registered `ServerHandle`."""
@@ -143,7 +145,9 @@ class Session:
),
correlation_id=correlation_id,
)
return reply.add_item.item_handle
if reply.HasField("add_item"):
return reply.add_item.item_handle
return _int32_return_value_or_raise("add_item", reply)
async def add_item2(
self,
@@ -165,7 +169,9 @@ class Session:
),
correlation_id=correlation_id,
)
return reply.add_item2.item_handle
if reply.HasField("add_item2"):
return reply.add_item2.item_handle
return _int32_return_value_or_raise("add_item2", reply)
async def advise(
self,
@@ -226,6 +232,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("add_item_bulk", reply)
return list(reply.add_item_bulk.results)
async def advise_item_bulk(
@@ -249,6 +256,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("advise_item_bulk", reply)
return list(reply.advise_item_bulk.results)
async def remove_item_bulk(
@@ -272,6 +280,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("remove_item_bulk", reply)
return list(reply.remove_item_bulk.results)
async def unadvise_item_bulk(
@@ -295,6 +304,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("un_advise_item_bulk", reply)
return list(reply.un_advise_item_bulk.results)
async def subscribe_bulk(
@@ -318,6 +328,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("subscribe_bulk", reply)
return list(reply.subscribe_bulk.results)
async def unsubscribe_bulk(
@@ -341,6 +352,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("unsubscribe_bulk", reply)
return list(reply.unsubscribe_bulk.results)
async def write_bulk(
@@ -369,6 +381,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("write_bulk", reply)
return list(reply.write_bulk.results)
async def write2_bulk(
@@ -392,6 +405,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("write2_bulk", reply)
return list(reply.write2_bulk.results)
async def write_secured_bulk(
@@ -415,6 +429,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("write_secured_bulk", reply)
return list(reply.write_secured_bulk.results)
async def write_secured2_bulk(
@@ -438,6 +453,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("write_secured2_bulk", reply)
return list(reply.write_secured2_bulk.results)
async def read_bulk(
@@ -477,6 +493,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("read_bulk", reply)
return list(reply.read_bulk.results)
async def write(
@@ -895,6 +912,7 @@ class Session:
),
correlation_id=correlation_id,
)
_require_payload("drain_events", reply)
return list(reply.drain_events.events)
def stream_events(
@@ -978,6 +996,34 @@ def _value_secrets(value: MxValueInput) -> list[str]:
return []
def _int32_return_value_or_raise(operation: str, reply: Any) -> int:
"""Return the int32 ``return_value`` of an OK reply lacking the typed payload, or raise.
Returning the protobuf default ``0`` would hand the caller a bogus handle that
fails later with an unrelated invalid-handle error.
"""
if reply.HasField("return_value") and reply.return_value.WhichOneof("kind") == "int32_value":
return int(reply.return_value.int32_value)
raise MalformedReplyError(
f"{operation} returned a malformed reply: OK reply carried "
"neither the typed payload nor an int32 return_value",
raw_reply=reply,
)
def _require_payload(field: str, reply: Any) -> None:
"""Raise `MalformedReplyError` when an OK reply lacks the typed payload ``field``.
An empty list read as "nothing subscribed, no failures" would be a silent
wrong answer for the bulk and drain commands.
"""
if not reply.HasField(field):
raise MalformedReplyError(
f"{field} returned a malformed reply: OK reply did not carry the {field} payload",
raw_reply=reply,
)
def _redact_error(error: MxGatewayError, secrets: Sequence[str | None]) -> None:
"""Scrub secret substrings from a raised error's message and reply in place.