fix(clients/python): concurrency-safe Session.close() caching the real reply (mxaccessgw#202)
This commit is contained in:
@@ -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."""
|
||||
|
||||
Reference in New Issue
Block a user