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
+55
View File
@@ -9,6 +9,14 @@ from zb_mom_ww_mxgateway import options as options_module
from zb_mom_ww_mxgateway.errors import MxGatewayTransportError
from zb_mom_ww_mxgateway.options import ClientOptions, create_channel
#: Default HTTP/2 keepalive channel options (30 s ping, 10 s timeout, idle pings).
KEEPALIVE_OPTIONS = [
("grpc.keepalive_time_ms", 30_000),
("grpc.keepalive_timeout_ms", 10_000),
("grpc.keepalive_permit_without_calls", 1),
("grpc.http2.max_pings_without_data", 0),
]
def test_auth_metadata_adds_bearer_api_key() -> None:
assert auth_metadata("mxgw_test_secret") == (
@@ -70,6 +78,7 @@ def test_create_channel_uses_plaintext_channel(monkeypatch: pytest.MonkeyPatch)
[
("grpc.max_receive_message_length", 16 * 1024 * 1024),
("grpc.max_send_message_length", 16 * 1024 * 1024),
*KEEPALIVE_OPTIONS,
],
),
]
@@ -122,6 +131,7 @@ def test_create_channel_uses_tls_channel_tofu_default(monkeypatch: pytest.Monkey
[
("grpc.max_receive_message_length", 16 * 1024 * 1024),
("grpc.max_send_message_length", 16 * 1024 * 1024),
*KEEPALIVE_OPTIONS,
("grpc.ssl_target_name_override", "localhost"),
],
),
@@ -171,6 +181,7 @@ def test_create_channel_uses_tls_channel_tofu_respects_server_name_override(
[
("grpc.max_receive_message_length", 16 * 1024 * 1024),
("grpc.max_send_message_length", 16 * 1024 * 1024),
*KEEPALIVE_OPTIONS,
# Explicit override from ClientOptions — not the auto-localhost one
("grpc.ssl_target_name_override", "gateway.test"),
],
@@ -224,6 +235,7 @@ def test_create_channel_uses_tls_channel_require_cert_validation(
[
("grpc.max_receive_message_length", 16 * 1024 * 1024),
("grpc.max_send_message_length", 16 * 1024 * 1024),
*KEEPALIVE_OPTIONS,
],
),
]
@@ -278,6 +290,7 @@ def test_create_channel_uses_tls_channel_ca_file(
[
("grpc.max_receive_message_length", 16 * 1024 * 1024),
("grpc.max_send_message_length", 16 * 1024 * 1024),
*KEEPALIVE_OPTIONS,
],
),
]
@@ -324,3 +337,45 @@ def test_tofu_probe_timeout_raises_transport_error(
with pytest.raises(MxGatewayTransportError) as excinfo:
create_channel(options)
assert options.endpoint in str(excinfo.value)
def test_keepalive_defaults_are_configurable_and_can_be_disabled() -> None:
from zb_mom_ww_mxgateway.options import ClientOptions
defaults = ClientOptions(endpoint="localhost:5000")
assert defaults.keepalive_time == 30.0
assert defaults.keepalive_timeout == 10.0
assert defaults.keepalive_permit_without_calls is True
tuned = ClientOptions(
endpoint="localhost:5000",
keepalive_time=45.0,
keepalive_timeout=5.0,
keepalive_permit_without_calls=False,
)
assert (tuned.keepalive_time, tuned.keepalive_timeout) == (45.0, 5.0)
assert tuned.keepalive_permit_without_calls is False
with pytest.raises(ValueError):
ClientOptions(endpoint="localhost:5000", keepalive_time=0)
with pytest.raises(ValueError):
ClientOptions(endpoint="localhost:5000", keepalive_timeout=0)
def test_keepalive_disabled_adds_no_keepalive_channel_options(monkeypatch) -> None:
from zb_mom_ww_mxgateway import options as options_module
calls: list[list[tuple[str, object]]] = []
monkeypatch.setattr(
options_module.grpc.aio,
"insecure_channel",
lambda endpoint, options: calls.append(options) or "plain-channel",
)
options_module.create_channel(
options_module.ClientOptions(
endpoint="localhost:5000", plaintext=True, keepalive_time=None
)
)
assert not any(name.startswith("grpc.keepalive") for name, _ in calls[0])
+72 -2
View File
@@ -3,11 +3,25 @@
import json
from pathlib import Path
import grpc
import pytest
from google.protobuf.json_format import ParseDict
from zb_mom_ww_mxgateway.errors import ensure_mxaccess_success, ensure_protocol_success
from zb_mom_ww_mxgateway import MxAccessError, MxGatewaySessionError
from zb_mom_ww_mxgateway.errors import (
ensure_mxaccess_success,
ensure_protocol_success,
map_rpc_error,
)
from zb_mom_ww_mxgateway import (
MxAccessError,
MxGatewayAuthenticationError,
MxGatewayAuthorizationError,
MxGatewayCommandError,
MxGatewaySessionError,
MxGatewayTimeoutError,
MxGatewayTransportError,
MxGatewayUnavailableError,
)
from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb
FIXTURE_ROOT = Path(__file__).resolve().parents[2] / "proto" / "fixtures" / "behavior"
@@ -96,3 +110,59 @@ def test_session_status_maps_to_session_error() -> None:
def _load_reply(name: str) -> pb.MxCommandReply:
payload = json.loads((FIXTURE_ROOT / name).read_text(encoding="utf-8"))
return ParseDict(payload, pb.MxCommandReply())
def test_unknown_enum_values_do_not_replace_typed_errors() -> None:
"""CPY-001: proto3 enums are open; an unnamed value must not raise ValueError."""
reply = pb.MxCommandReply(
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_MXACCESS_FAILURE),
statuses=[pb.MxStatusProxy(category=99)],
)
with pytest.raises(MxAccessError) as captured:
ensure_mxaccess_success("write", reply)
assert "category=99" in str(captured.value)
status = pb.ProtocolStatus(code=999)
with pytest.raises(MxGatewayCommandError) as command_error:
ensure_protocol_success("invoke", status)
assert "999" in str(command_error.value)
@pytest.mark.parametrize(
("code", "expected"),
[
(grpc.StatusCode.UNAUTHENTICATED, MxGatewayAuthenticationError),
(grpc.StatusCode.PERMISSION_DENIED, MxGatewayAuthorizationError),
(grpc.StatusCode.DEADLINE_EXCEEDED, MxGatewayTimeoutError),
(grpc.StatusCode.UNAVAILABLE, MxGatewayUnavailableError),
(grpc.StatusCode.RESOURCE_EXHAUSTED, MxGatewayUnavailableError),
(grpc.StatusCode.INTERNAL, MxGatewayTransportError),
],
)
def test_map_rpc_error_preserves_status_code_and_type(code, expected) -> None:
"""CPY-003: callers can tell unavailable from deadline-exceeded without __cause__."""
class _Error(grpc.RpcError):
def code(self):
return code
def details(self):
return "boom"
mapped = map_rpc_error("invoke", _Error())
assert type(mapped) is expected
assert mapped.code is code
def test_map_rpc_error_redacts_credentials_in_details() -> None:
class _Error(grpc.RpcError):
def code(self):
return grpc.StatusCode.INTERNAL
def details(self):
return 'bad header "Bearer mxgw_id_secret" key=mxgw_id_secret'
message = str(map_rpc_error("invoke", _Error()))
assert "secret" not in message
@@ -110,3 +110,56 @@ async def test_authenticate_user_echoed_credential_is_scrubbed(fixture: str) ->
assert credential not in exc.raw_reply.diagnostic_message
for status in exc.raw_reply.statuses:
assert credential not in status.diagnostic_text
@pytest.mark.parametrize(
("kind", "call"),
[
(pb.MX_COMMAND_KIND_REGISTER, lambda s: s.register("client")),
(pb.MX_COMMAND_KIND_ADD_ITEM, lambda s: s.add_item(1, "Tag")),
(pb.MX_COMMAND_KIND_ADD_ITEM2, lambda s: s.add_item2(1, "Tag", "ctx")),
(pb.MX_COMMAND_KIND_SUBSCRIBE_BULK, lambda s: s.subscribe_bulk(1, ["Tag"])),
(pb.MX_COMMAND_KIND_READ_BULK, lambda s: s.read_bulk(1, ["Tag"])),
(pb.MX_COMMAND_KIND_DRAIN_EVENTS, lambda s: s.drain_events(10)),
],
)
@pytest.mark.asyncio
async def test_handle_and_bulk_helpers_raise_on_reply_without_payload(kind, call) -> None:
"""CPY-004: an OK reply with no payload must not read as handle 0 / an empty list."""
reply = pb.MxCommandReply(
session_id="session-1",
kind=kind,
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
)
session, _ = await _session_with([reply])
with pytest.raises(MalformedReplyError) as captured:
await call(session)
assert captured.value.raw_reply is reply
@pytest.mark.asyncio
async def test_register_falls_back_to_return_value_int32() -> None:
reply = pb.MxCommandReply(
session_id="session-1",
kind=pb.MX_COMMAND_KIND_REGISTER,
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
return_value=pb.MxValue(int32_value=5),
)
session, _ = await _session_with([reply])
assert await session.register("client") == 5
@pytest.mark.asyncio
async def test_empty_bulk_payload_is_a_valid_empty_result() -> None:
reply = pb.MxCommandReply(
session_id="session-1",
kind=pb.MX_COMMAND_KIND_DRAIN_EVENTS,
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
drain_events=pb.DrainEventsReply(),
)
session, _ = await _session_with([reply])
assert await session.drain_events(10) == []