diff --git a/clients/python/README.md b/clients/python/README.md index f5790ea2..571fd4be 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -455,6 +455,32 @@ building it inside `asyncio.to_thread` raises `RuntimeError: There is no current event loop in thread 'asyncio_N'`. Callers that build their own channel should keep `create_channel` on the loop thread. +## Keepalive And Error Mapping + +The channel sends an HTTP/2 PING every 30 s, waits 10 s for the acknowledgement, +and pings even while no call is active (`grpc.keepalive_time_ms`, +`grpc.keepalive_timeout_ms`, `grpc.keepalive_permit_without_calls`, and +`grpc.http2.max_pings_without_data=0` so pings continue with no data in flight). +A half-open connection (firewall idle-out, host power loss) therefore makes a +deadline-less `stream_events()` iterator raise `MxGatewayTransportError` within +about 40 s instead of hanging forever. Tune with `ClientOptions(keepalive_time=..., +keepalive_timeout=..., keepalive_permit_without_calls=...)`; `keepalive_time=None` +disables it. Keep `keepalive_time` at or above the gateway's permitted client ping +interval (`MxGateway:*` keepalive policy, 30 s by default); pinging faster makes +the gateway send GOAWAY (`too_many_pings`). + +gRPC failures map to `MxGatewayAuthenticationError`, `MxGatewayAuthorizationError`, +`MxGatewayTimeoutError` (`DEADLINE_EXCEEDED`), `MxGatewayUnavailableError` +(`UNAVAILABLE` / `RESOURCE_EXHAUSTED`) or the base `MxGatewayTransportError`. Every +transport error carries the gRPC status in `.code`, and credential-shaped text +(`mxgw_...` keys, `Bearer`) is scrubbed from the server-supplied details. Enum +values newer than the generated code (a new status category or protocol status +code) are reported by number instead of raising `ValueError`. + +`register`, `add_item`, `add_item2`, the bulk helpers, `read_bulk` and +`drain_events` raise `MalformedReplyError` when an `OK` reply lacks the expected +payload, instead of returning handle `0` or an empty list. + ## CLI The CLI emits deterministic JSON for automation: diff --git a/clients/python/src/zb_mom_ww_mxgateway/__init__.py b/clients/python/src/zb_mom_ww_mxgateway/__init__.py index 1f8f31ba..2cf0e0c9 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/__init__.py +++ b/clients/python/src/zb_mom_ww_mxgateway/__init__.py @@ -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", diff --git a/clients/python/src/zb_mom_ww_mxgateway/auth.py b/clients/python/src/zb_mom_ww_mxgateway/auth.py index 8d21f08b..831528f9 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/auth.py +++ b/clients/python/src/zb_mom_ww_mxgateway/auth.py @@ -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__`` 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.""" diff --git a/clients/python/src/zb_mom_ww_mxgateway/errors.py b/clients/python/src/zb_mom_ww_mxgateway/errors.py index ca2770c0..4f06c704 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/errors.py +++ b/clients/python/src/zb_mom_ww_mxgateway/errors.py @@ -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}]" diff --git a/clients/python/src/zb_mom_ww_mxgateway/options.py b/clients/python/src/zb_mom_ww_mxgateway/options.py index ea3e38bf..867b9eac 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/options.py +++ b/clients/python/src/zb_mom_ww_mxgateway/options.py @@ -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: diff --git a/clients/python/src/zb_mom_ww_mxgateway/session.py b/clients/python/src/zb_mom_ww_mxgateway/session.py index 90c8b066..47a1d740 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/session.py +++ b/clients/python/src/zb_mom_ww_mxgateway/session.py @@ -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. diff --git a/clients/python/tests/test_auth_options.py b/clients/python/tests/test_auth_options.py index 53305357..00395be1 100644 --- a/clients/python/tests/test_auth_options.py +++ b/clients/python/tests/test_auth_options.py @@ -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]) diff --git a/clients/python/tests/test_errors.py b/clients/python/tests/test_errors.py index 36493a2d..e1c2860c 100644 --- a/clients/python/tests/test_errors.py +++ b/clients/python/tests/test_errors.py @@ -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 diff --git a/clients/python/tests/test_malformed_reply.py b/clients/python/tests/test_malformed_reply.py index fe8b8a3e..9cee9d7c 100644 --- a/clients/python/tests/test_malformed_reply.py +++ b/clients/python/tests/test_malformed_reply.py @@ -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) == []