From 855cd8a52656d6b5540b5c4af40b34ab32fa33db Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:47:40 -0500 Subject: [PATCH] fix(client-python): CLI batch reuses one loop/channel; smoke attaches stream before advise (CPY-005, CPY-006, #257) --- clients/python/README.md | 11 +- .../python/src/zb_mom_ww_mxgateway/session.py | 9 + .../src/zb_mom_ww_mxgateway_cli/commands.py | 167 +++++++++++++++++- clients/python/tests/test_cli.py | 158 +++++++++++++++++ 4 files changed, 334 insertions(+), 11 deletions(-) diff --git a/clients/python/README.md b/clients/python/README.md index 571fd4be..20b12951 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -498,8 +498,15 @@ mxgw-py write --session-id --server-handle 1 --item-handle 2 --type int32 - ``` Use `--api-key` or `--api-key-env MXGATEWAY_API_KEY` to attach API key -metadata. `smoke` opens a session, registers, adds an item, advises, streams a -bounded event count, and closes the session in a `finally` block. +metadata. `smoke` opens a session, registers, adds an item, attaches the event +stream, advises, collects a bounded event count, and closes the session in a +`finally` block. It attaches the stream before advising (and, when the gateway +lists `stream-events-attached-ack`, waits for the attach acknowledgement) so the +initial value cannot be published before the subscriber registers. + +`batch` reads one command per stdin line and runs them all on a single event loop, +reusing one client (one channel, one TLS certificate probe) per distinct +connection until stdin ends; it closes them once at the end. Use TLS options for a secured gateway: diff --git a/clients/python/src/zb_mom_ww_mxgateway/session.py b/clients/python/src/zb_mom_ww_mxgateway/session.py index 47a1d740..e0d2dbe1 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/session.py +++ b/clients/python/src/zb_mom_ww_mxgateway/session.py @@ -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) diff --git a/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py b/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py index fa05282e..2900beca 100644 --- a/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py +++ b/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py @@ -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: diff --git a/clients/python/tests/test_cli.py b/clients/python/tests/test_cli.py index ae306330..71da4afb 100644 --- a/clients/python/tests/test_cli.py +++ b/clients/python/tests/test_cli.py @@ -973,3 +973,161 @@ def test_stream_events_renders_replay_gap(monkeypatch: pytest.MonkeyPatch) -> No # The gap is rendered, never swallowed, and the normal event still follows it. assert "replayGap" not in rows[1] assert rows[1]["workerSequence"] == "43" + + +def test_batch_reuses_one_client_and_event_loop_across_lines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """CPY-005: each batch line used to run a new loop and dial a new channel.""" + import asyncio + + connects: list[object] = [] + loops: list[asyncio.AbstractEventLoop] = [] + closes: list[int] = [] + + class _CountingGalaxy(_FakeGalaxyClient): + async def test_connection(self) -> bool: + loops.append(asyncio.get_running_loop()) + return True + + async def close(self) -> None: + closes.append(1) + + fake = _CountingGalaxy(ok=True) + + async def fake_connect(options, **_kwargs): + connects.append(options) + return fake + + monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["batch"], + input=("galaxy-test-connection --plaintext --json\n" * 3), + ) + + assert result.exit_code == 0, result.output + assert result.output.count(_BATCH_EOR) == 3 + assert len(connects) == 1, "one channel for all three lines" + assert len(set(map(id, loops))) == 1, "one event loop for all three lines" + assert closes == [1], "the shared client is closed once, when the batch ends" + assert commands_module._batch_context is None + + +def test_batch_dials_separate_clients_for_distinct_connections( + monkeypatch: pytest.MonkeyPatch, +) -> None: + connects: list[str] = [] + + async def fake_connect(options, **_kwargs): + connects.append(options.endpoint) + return _FakeGalaxyClient(ok=True) + + monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["batch"], + input=( + "galaxy-test-connection --plaintext --endpoint a:1 --json\n" + "galaxy-test-connection --plaintext --endpoint b:1 --json\n" + "galaxy-test-connection --plaintext --endpoint a:1 --json\n" + ), + ) + + assert result.exit_code == 0, result.output + assert connects == ["a:1", "b:1"] + + +class _SmokeSession: + """Fake session that only delivers an initial event to a subscriber attached before advise.""" + + def __init__(self, *, attach_ack: bool) -> None: + from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb + + self._pb = pb + capabilities = ["stream-events-attached-ack"] if attach_ack else [] + self.open_reply = pb.OpenSessionReply(session_id="s1", capabilities=capabilities) + self.session_id = "s1" + self.calls: list[str] = [] + self.emit_requested: bool | None = None + self._subscribed = False + self._advised = asyncio_event() + + async def __aenter__(self) -> "_SmokeSession": + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def register(self, _name: str) -> int: + self.calls.append("register") + return 1 + + async def add_item(self, _server: int, _item: str) -> int: + self.calls.append("add_item") + return 2 + + async def advise(self, _server: int, _item: int) -> None: + self.calls.append("advise") + self._advised.set() + + def stream_events(self, *, emit_stream_attached: bool = False): + self.calls.append("stream_events") + self.emit_requested = emit_stream_attached + self._subscribed = True + pb = self._pb + + async def _gen(): + if emit_stream_attached: + yield pb.MxEvent(stream_attached=pb.StreamAttached()) + await self._advised.wait() + # The initial value is only delivered to an already-registered subscriber. + yield pb.MxEvent(worker_sequence=7) + + return _gen() + + +def asyncio_event(): + import asyncio + + return asyncio.Event() + + +class _SmokeClient: + def __init__(self, session: _SmokeSession) -> None: + self._session = session + + async def __aenter__(self) -> "_SmokeClient": + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def open_session(self, **_kwargs): + return self._session + + +@pytest.mark.parametrize("attach_ack", [True, False]) +def test_smoke_attaches_event_stream_before_advise( + monkeypatch: pytest.MonkeyPatch, attach_ack: bool +) -> None: + """CPY-006: advising before the stream attaches can lose the initial value.""" + session = _SmokeSession(attach_ack=attach_ack) + + async def fake_connect(options, **_kwargs): + return _SmokeClient(session) + + monkeypatch.setattr(commands_module.GatewayClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["smoke", "--plaintext", "--item", "Tag", "--max-events", "1", "--timeout", "2", "--json"], + ) + + assert result.exit_code == 0, result.output + assert session.calls.index("stream_events") < session.calls.index("advise") + assert session.emit_requested is attach_ack + payload = json.loads(result.output) + assert [event["workerSequence"] for event in payload["events"]] == ["7"]