diff --git a/clients/python/README.md b/clients/python/README.md index 58ed764c..f5790ea2 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -103,6 +103,10 @@ async with await GatewayClient.connect( await session.close() ``` +`Session.close()` is concurrency-safe and idempotent: concurrent or repeated +calls issue a single `CloseSession` RPC and return the gateway's real reply (a +failed RPC is not cached, so a later call may retry). + `GatewayClient.open_session_raw`, `GatewayClient.invoke_raw`, and `GatewayClient.stream_events_raw` keep the generated protobuf replies and events available for parity tests. `Session` helpers call the method-specific diff --git a/clients/python/src/zb_mom_ww_mxgateway/session.py b/clients/python/src/zb_mom_ww_mxgateway/session.py index 24ba73f4..f2a40f32 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/session.py +++ b/clients/python/src/zb_mom_ww_mxgateway/session.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from collections.abc import AsyncIterator, Sequence from typing import Any @@ -29,6 +30,8 @@ class Session: self.session_id = session_id self.open_reply = open_reply self._closed = False + self._close_lock = asyncio.Lock() + self._close_reply: pb.CloseSessionReply | None = None async def __aenter__(self) -> "Session": """Return self to support ``async with`` usage.""" @@ -39,23 +42,26 @@ class Session: await self.close() async def close(self, *, client_correlation_id: str = "") -> pb.CloseSessionReply: - """Close the gateway session. Repeated calls return a local closed reply.""" + """Close the gateway session. - if self._closed: - return pb.CloseSessionReply( - session_id=self.session_id, - final_state=pb.SESSION_STATE_CLOSED, - protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK), + Concurrency-safe: concurrent and repeated calls issue a single + CloseSession RPC and all return the gateway's real reply. If the RPC + raises, nothing is cached and a later call may retry. + """ + + async with self._close_lock: + if self._close_reply is not None: + return self._close_reply + + reply = await self.client.close_session_raw( + pb.CloseSessionRequest( + session_id=self.session_id, + client_correlation_id=client_correlation_id, + ), ) - - reply = await self.client.close_session_raw( - pb.CloseSessionRequest( - session_id=self.session_id, - client_correlation_id=client_correlation_id, - ), - ) - self._closed = True - return reply + self._closed = True + self._close_reply = reply + return reply async def invoke(self, command: pb.MxCommand, *, correlation_id: str = "") -> pb.MxCommandReply: """Invoke a raw command and enforce gateway and MXAccess success.""" diff --git a/clients/python/tests/test_client_session.py b/clients/python/tests/test_client_session.py index c46d6ba9..f74d5aac 100644 --- a/clients/python/tests/test_client_session.py +++ b/clients/python/tests/test_client_session.py @@ -374,3 +374,34 @@ class FakeStream: def cancel(self) -> None: self.cancelled = True + + +@pytest.mark.asyncio +async def test_session_close_is_concurrency_safe_and_caches_real_reply() -> None: + stub = FakeGatewayStub() + real = stub.close_session.replies[0] + real.final_state = pb.SESSION_STATE_CLOSED + original_call = stub.close_session.__call__ + + async def slow_close(request: Any, *, metadata: Any) -> Any: + await asyncio.sleep(0.01) + return await original_call(request, metadata=metadata) + + class SlowUnary: + requests = stub.close_session.requests + + async def __call__(self, request: Any, *, metadata: Any) -> Any: + return await slow_close(request, metadata=metadata) + + stub.CloseSession = SlowUnary() + client = await GatewayClient.connect( + ClientOptions(endpoint="fake", api_key="k", plaintext=True), + stub=stub, + ) + session = await client.open_session(client_session_name="pytest") + + replies = await asyncio.gather(*(session.close() for _ in range(5))) + + assert len(stub.close_session.requests) == 1 + assert all(r is real for r in replies) + assert (await session.close()) is real