fix(client-python): CLI batch reuses one loop/channel; smoke attaches stream before advise (CPY-005, CPY-006, #257)
This commit is contained in:
@@ -919,9 +919,17 @@ class Session:
|
||||
self,
|
||||
*,
|
||||
after_worker_sequence: int = 0,
|
||||
emit_stream_attached: bool = False,
|
||||
) -> AsyncIterator[pb.MxEvent | ReplayGap]:
|
||||
"""Return an async iterator over this session's `MxEvent` stream.
|
||||
|
||||
With *emit_stream_attached* the gateway sends one ``stream_attached``
|
||||
sentinel event first, after this stream's subscriber is registered; wait
|
||||
for it before ``advise`` / ``subscribe_bulk`` so the initial value cannot
|
||||
be lost to the attach race. Only request it when the session's
|
||||
``open_reply.capabilities`` lists ``stream-events-attached-ack``; the
|
||||
sentinel is yielded as an ``MxEvent`` with ``HasField("stream_attached")``.
|
||||
|
||||
Each yielded item is either a normal :class:`~...MxEvent` or a
|
||||
:class:`ReplayGap`. Branch on ``isinstance(item, ReplayGap)`` — a gap is
|
||||
never delivered as an ``MxEvent`` so it cannot be mistaken for a real
|
||||
@@ -941,6 +949,7 @@ class Session:
|
||||
pb.StreamEventsRequest(
|
||||
session_id=self.session_id,
|
||||
after_worker_sequence=after_worker_sequence,
|
||||
emit_stream_attached=emit_stream_attached,
|
||||
),
|
||||
)
|
||||
return _surface_replay_gaps(raw)
|
||||
|
||||
@@ -40,6 +40,71 @@ DEFAULT_OPERATOR_PASSWORD_ENV = "MXGATEWAY_OPERATOR_PASSWORD"
|
||||
|
||||
_BATCH_EOR = "__MXGW_BATCH_EOR__"
|
||||
|
||||
#: `OpenSessionReply.capabilities` entry advertising `StreamEventsRequest.emit_stream_attached`.
|
||||
_STREAM_ATTACHED_CAPABILITY = "stream-events-attached-ack"
|
||||
|
||||
|
||||
class _BatchContext:
|
||||
"""Process-wide state that lets batch mode reuse one loop and one client per connection.
|
||||
|
||||
Batch mode exists to avoid per-command start-up cost. Re-entering Click per line
|
||||
used to run ``asyncio.run`` (a new loop), dial a new channel and, on the lenient
|
||||
TLS path, run a separate blocking TOFU certificate probe every time. While a
|
||||
batch is active ``_run`` drives every command on ``loop`` and ``_connect`` /
|
||||
``_connect_galaxy`` hand out a cached client per distinct connection whose
|
||||
``async with`` exit does not close it; the batch closes them all once at the end.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.loop = asyncio.new_event_loop()
|
||||
self.gateway_clients: dict[tuple[Any, ...], GatewayClient] = {}
|
||||
self.galaxy_clients: dict[tuple[Any, ...], GalaxyRepositoryClient] = {}
|
||||
|
||||
def close(self) -> None:
|
||||
async def _close_all() -> None:
|
||||
for client in [*self.gateway_clients.values(), *self.galaxy_clients.values()]:
|
||||
with contextlib.suppress(Exception):
|
||||
await client.close()
|
||||
|
||||
try:
|
||||
self.loop.run_until_complete(_close_all())
|
||||
finally:
|
||||
self.loop.close()
|
||||
|
||||
|
||||
_batch_context: _BatchContext | None = None
|
||||
|
||||
|
||||
class _SharedClient:
|
||||
"""Wrap a batch-cached client so ``async with`` yields it without closing it."""
|
||||
|
||||
def __init__(self, client: Any) -> None:
|
||||
self._client = client
|
||||
|
||||
async def __aenter__(self) -> Any:
|
||||
return self._client
|
||||
|
||||
async def __aexit__(self, *_exc_info: object) -> None:
|
||||
return None
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._client, name)
|
||||
|
||||
|
||||
def _connection_key(kwargs: dict[str, Any]) -> tuple[Any, ...]:
|
||||
"""Identity of a connection: every option that changes how the channel is dialed."""
|
||||
|
||||
return (
|
||||
kwargs["endpoint"],
|
||||
kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env")),
|
||||
_use_plaintext(kwargs),
|
||||
kwargs.get("ca_file"),
|
||||
bool(kwargs.get("require_certificate_validation")),
|
||||
kwargs.get("server_name_override"),
|
||||
kwargs.get("call_timeout"),
|
||||
kwargs.get("stream_timeout"),
|
||||
)
|
||||
|
||||
|
||||
@click.group()
|
||||
def main() -> None:
|
||||
@@ -75,6 +140,16 @@ def batch() -> None:
|
||||
dispatcher would silently spawn a nested loop reading from the same exhausted stdin.
|
||||
"""
|
||||
|
||||
global _batch_context
|
||||
_batch_context = _BatchContext()
|
||||
try:
|
||||
_run_batch_loop()
|
||||
finally:
|
||||
context, _batch_context = _batch_context, None
|
||||
context.close()
|
||||
|
||||
|
||||
def _run_batch_loop() -> None:
|
||||
for raw_line in sys.stdin:
|
||||
line = raw_line.rstrip("\n").rstrip("\r")
|
||||
if not line:
|
||||
@@ -1234,12 +1309,29 @@ async def _smoke(**kwargs: Any) -> dict[str, Any]:
|
||||
async with session:
|
||||
server_handle = await session.register(kwargs["client_name"])
|
||||
item_handle = await session.add_item(server_handle, kwargs["item"])
|
||||
await session.advise(server_handle, item_handle)
|
||||
events = await _collect_events(
|
||||
session.stream_events(),
|
||||
max_events=kwargs["max_events"],
|
||||
timeout=kwargs["timeout"],
|
||||
)
|
||||
# Attach the event stream BEFORE advising: a fresh stream does not
|
||||
# replay the ring, so an initial OnDataChange published before the
|
||||
# subscriber registers would be lost (CPY-006). When the gateway
|
||||
# advertises the attach acknowledgement, wait for the sentinel so the
|
||||
# subscriber is known to be registered before the advise is issued.
|
||||
capabilities = session.open_reply.capabilities if session.open_reply else ()
|
||||
attach_ack = _STREAM_ATTACHED_CAPABILITY in capabilities
|
||||
iterator = session.stream_events(emit_stream_attached=attach_ack).__aiter__()
|
||||
try:
|
||||
leading: list[pb.MxEvent | ReplayGap] = []
|
||||
if attach_ack:
|
||||
leading = await _await_stream_attached(iterator, timeout=kwargs["timeout"])
|
||||
await session.advise(server_handle, item_handle)
|
||||
events = await _collect_events(
|
||||
iterator,
|
||||
max_events=kwargs["max_events"],
|
||||
timeout=kwargs["timeout"],
|
||||
leading=leading,
|
||||
)
|
||||
finally:
|
||||
close = getattr(iterator, "aclose", None)
|
||||
if close is not None:
|
||||
await close()
|
||||
return {
|
||||
"sessionId": session.session_id,
|
||||
"serverHandle": server_handle,
|
||||
@@ -1458,6 +1550,18 @@ async def _galaxy_watch(**kwargs: Any) -> dict[str, Any]:
|
||||
|
||||
|
||||
async def _connect(kwargs: dict[str, Any]) -> GatewayClient:
|
||||
context = _batch_context
|
||||
if context is None:
|
||||
return await _connect_new(kwargs)
|
||||
key = _connection_key(kwargs)
|
||||
client = context.gateway_clients.get(key)
|
||||
if client is None:
|
||||
client = await _connect_new(kwargs)
|
||||
context.gateway_clients[key] = client
|
||||
return _SharedClient(client) # type: ignore[return-value]
|
||||
|
||||
|
||||
async def _connect_new(kwargs: dict[str, Any]) -> GatewayClient:
|
||||
api_key = kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env"))
|
||||
return await GatewayClient.connect(
|
||||
ClientOptions(
|
||||
@@ -1474,6 +1578,18 @@ async def _connect(kwargs: dict[str, Any]) -> GatewayClient:
|
||||
|
||||
|
||||
async def _connect_galaxy(kwargs: dict[str, Any]) -> GalaxyRepositoryClient:
|
||||
context = _batch_context
|
||||
if context is None:
|
||||
return await _connect_galaxy_new(kwargs)
|
||||
key = _connection_key(kwargs)
|
||||
client = context.galaxy_clients.get(key)
|
||||
if client is None:
|
||||
client = await _connect_galaxy_new(kwargs)
|
||||
context.galaxy_clients[key] = client
|
||||
return _SharedClient(client) # type: ignore[return-value]
|
||||
|
||||
|
||||
async def _connect_galaxy_new(kwargs: dict[str, Any]) -> GalaxyRepositoryClient:
|
||||
api_key = kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env"))
|
||||
return await GalaxyRepositoryClient.connect(
|
||||
ClientOptions(
|
||||
@@ -1526,6 +1642,15 @@ def _secrets(kwargs: dict[str, Any]) -> list[str | None]:
|
||||
]
|
||||
|
||||
|
||||
def _run_awaitable(awaitable: Awaitable[Any]) -> Any:
|
||||
"""Run `awaitable` on the batch loop when a batch is active, else on a fresh loop."""
|
||||
|
||||
context = _batch_context
|
||||
if context is None:
|
||||
return asyncio.run(awaitable) # type: ignore[arg-type]
|
||||
return context.loop.run_until_complete(awaitable)
|
||||
|
||||
|
||||
def _run(
|
||||
awaitable: Awaitable[dict[str, Any]],
|
||||
*,
|
||||
@@ -1533,7 +1658,7 @@ def _run(
|
||||
secrets: list[str | None],
|
||||
) -> None:
|
||||
try:
|
||||
payload = asyncio.run(awaitable)
|
||||
payload = _run_awaitable(awaitable)
|
||||
except MxGatewayError as error:
|
||||
raise click.ClickException(redact_secret(str(error), secrets)) from error
|
||||
|
||||
@@ -1546,7 +1671,7 @@ def _run_streaming(
|
||||
secrets: list[str | None],
|
||||
) -> None:
|
||||
try:
|
||||
asyncio.run(awaitable)
|
||||
_run_awaitable(awaitable)
|
||||
except MxGatewayError as error:
|
||||
raise click.ClickException(redact_secret(str(error), secrets)) from error
|
||||
|
||||
@@ -1570,11 +1695,35 @@ def _emit(
|
||||
click.echo(text or rendered_text or json.dumps(payload, sort_keys=True))
|
||||
|
||||
|
||||
async def _await_stream_attached(
|
||||
iterator: Any,
|
||||
*,
|
||||
timeout: float,
|
||||
) -> list[pb.MxEvent | ReplayGap]:
|
||||
"""Wait for the ``stream_attached`` sentinel; return any real items read meanwhile.
|
||||
|
||||
The sentinel is consumed, not returned: it is an attach acknowledgement, not an
|
||||
MXAccess event. A timeout or an early end of stream is tolerated (the caller then
|
||||
proceeds best-effort, as against a gateway that never sends the sentinel).
|
||||
"""
|
||||
|
||||
leading: list[pb.MxEvent | ReplayGap] = []
|
||||
try:
|
||||
while True:
|
||||
item = await asyncio.wait_for(iterator.__anext__(), timeout=timeout)
|
||||
if not isinstance(item, ReplayGap) and item.HasField("stream_attached"):
|
||||
return leading
|
||||
leading.append(item)
|
||||
except (StopAsyncIteration, asyncio.TimeoutError):
|
||||
return leading
|
||||
|
||||
|
||||
async def _collect_events(
|
||||
events: Any,
|
||||
*,
|
||||
max_events: int,
|
||||
timeout: float,
|
||||
leading: list[pb.MxEvent | ReplayGap] | None = None,
|
||||
) -> list[pb.MxEvent | ReplayGap]:
|
||||
if max_events > MAX_AGGREGATE_EVENTS:
|
||||
raise click.BadParameter(
|
||||
@@ -1582,7 +1731,7 @@ async def _collect_events(
|
||||
param_hint="--max-events",
|
||||
)
|
||||
|
||||
collected: list[pb.MxEvent | ReplayGap] = []
|
||||
collected: list[pb.MxEvent | ReplayGap] = list(leading or [])
|
||||
iterator = events.__aiter__()
|
||||
try:
|
||||
while len(collected) < max_events:
|
||||
|
||||
Reference in New Issue
Block a user