From 5fa2812c65f8217df0c78f515523280aed8ae8a4 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:09:05 +0100 Subject: [PATCH] feat: watch typed Engine inventory through reconnects --- docs/tunnels/003-inventory.md | 37 ++--- examples/README.md | 2 + examples/api-list-inventory/README.md | 10 ++ examples/api-list-inventory/main.py | 19 +++ examples/api-watch-tunnels/README.md | 10 ++ examples/api-watch-tunnels/main.py | 25 +++ src/rstream/__init__.py | 19 +++ src/rstream/client.py | 44 +++++- src/rstream/engine_api.py | 214 ++++++++++++++++++++------ src/rstream/inventory.py | 204 ++++++++++++++++++++++++ src/rstream/sync.py | 151 ++++++++++++++++++ tests/e2e/test_real_engine.py | 29 ++++ tests/unit/test_inventory.py | 161 +++++++++++++++++++ 13 files changed, 857 insertions(+), 68 deletions(-) create mode 100644 examples/api-list-inventory/README.md create mode 100644 examples/api-list-inventory/main.py create mode 100644 examples/api-watch-tunnels/README.md create mode 100644 examples/api-watch-tunnels/main.py create mode 100644 src/rstream/inventory.py create mode 100644 src/rstream/sync.py create mode 100644 tests/unit/test_inventory.py diff --git a/docs/tunnels/003-inventory.md b/docs/tunnels/003-inventory.md index 657c773..5ae98c2 100644 --- a/docs/tunnels/003-inventory.md +++ b/docs/tunnels/003-inventory.md @@ -30,12 +30,13 @@ async def main() -> None: async with rstream.Client.from_env() as client: for entry in await client.list_tunnels(): print(entry.properties.id, entry.status, flush=True) - async with client.watch() as events: - async for event in events: - if event.type == "state.initial" and event.object is not None: - print("snapshot", event.object.get("tunnels", []), flush=True) - else: - print(event.type, flush=True) + async with client.watch_inventory( + tunnels=rstream.TunnelFilters(status="online") + ) as snapshots: + async for snapshot in snapshots: + print("last known" if snapshot.stale else "current", flush=True) + for entry in snapshot.tunnels: + print(entry.properties.id, entry.properties.name, flush=True) with suppress(KeyboardInterrupt): @@ -44,22 +45,18 @@ with suppress(KeyboardInterrupt): Run `python watch_tunnels.py`. While it is running, start and stop a [sample tunnel](000-http-applications.md) in a second terminal -using the same project. Look for `tunnel.created` and `tunnel.deleted` -with the `id` field selected, or replacement snapshots otherwise. -The script closes the watch on Ctrl+C. +using the same project. Each update contains the complete visible list. +On disconnection the previous list is marked stale until the next Engine +snapshot. The script closes the subscription on Ctrl+C. -If the application needs a narrower set, use -`filters=rstream.TunnelFilters(labels={"role": "worker"})` for -`list_tunnels` and the same filter as `tunnels=filters` for `watch`. -Set that label on tunnel creation. To maintain a live view, replace it -at every `state.initial` and apply the subsequent create, update and -delete events. The watch can send a new snapshot on an existing -connection as well as after reconnecting. +Use `clients=rstream.ClientFilters(status="online")` to follow clients, or +pass both filters to follow both categories. The list methods accept +`filters` and an optional `limit`. For individual events, use `client.watch()` +and `rstream.inventory_event(event)` to decode inventory changes. -Call `await client.list_clients(filters=...)` with a `rstream.ClientFilters` -instance to list runtime clients. Pass the same filter to `client.watch(clients=...)` -to watch client changes. A context needs permission and scope to see those -resources. Both list methods accept a `limit` for a bounded result. +A blocking program can use [the synchronous list example](../../examples/api-list-inventory) +and `rstream.sync.InventoryClient.watch_inventory()`. In asyncio services, use +[the async watch example](../../examples/api-watch-tunnels). The default transport is server-sent events. Install the `realtime` extra and use `transport="websocket"` if the application requires WebSockets. diff --git a/examples/README.md b/examples/README.md index 50668f3..12ebba4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,6 +8,8 @@ with signed deliveries and need no Engine. | Example | Purpose | | --- | --- | +| [api-list-inventory](api-list-inventory) | List online clients and tunnels from a blocking program. | +| [api-watch-tunnels](api-watch-tunnels) | Maintain an online tunnel registry with asyncio. | | [private-dial](private-dial) | Make an HTTP request through a private byte stream. | | [fastapi-tunnel](fastapi-tunnel) | Publish a FastAPI app through the direct ASGI helper. | | [flask-tunnel](flask-tunnel) | Publish a Flask app through the direct WSGI helper. | diff --git a/examples/api-list-inventory/README.md b/examples/api-list-inventory/README.md new file mode 100644 index 0000000..e2147da --- /dev/null +++ b/examples/api-list-inventory/README.md @@ -0,0 +1,10 @@ +# List online clients and tunnels + +Install the `api` extra and select an [Engine context](../../docs/001-configuration.md) +with inventory access. From the repository root, run the example. + +```sh +python examples/api-list-inventory/main.py +``` + +Pass `clients` or `tunnels` to query only one category. diff --git a/examples/api-list-inventory/main.py b/examples/api-list-inventory/main.py new file mode 100644 index 0000000..ed3be98 --- /dev/null +++ b/examples/api-list-inventory/main.py @@ -0,0 +1,19 @@ +import argparse + +import rstream +from rstream.sync import InventoryClient + +parser = argparse.ArgumentParser() +parser.add_argument( + "kind", nargs="?", choices=("clients", "tunnels", "both"), default="both" +) +kind = parser.parse_args().kind +with InventoryClient() as client: + if kind in ("both", "clients"): + for row in client.list_clients(filters=rstream.ClientFilters(status="online")): + print("client", row.get("id"), row.get("agent")) + if kind in ("both", "tunnels"): + for entry in client.list_tunnels( + filters=rstream.TunnelFilters(status="online") + ): + print("tunnel", entry.properties.id, entry.properties.name) diff --git a/examples/api-watch-tunnels/README.md b/examples/api-watch-tunnels/README.md new file mode 100644 index 0000000..0ce6049 --- /dev/null +++ b/examples/api-watch-tunnels/README.md @@ -0,0 +1,10 @@ +# Watch online tunnels + +Install the `api` extra and select an [Engine context](../../docs/001-configuration.md) +with inventory access. From the repository root, run the example. + +```sh +python examples/api-watch-tunnels/main.py +``` + +Start or stop a tunnel in another terminal. Each update prints the full visible list; a disconnect marks the list as last known until reconnection. Stop with Ctrl+C. diff --git a/examples/api-watch-tunnels/main.py b/examples/api-watch-tunnels/main.py new file mode 100644 index 0000000..1987c2d --- /dev/null +++ b/examples/api-watch-tunnels/main.py @@ -0,0 +1,25 @@ +import asyncio +from contextlib import suppress + +import rstream + + +async def main() -> None: + async with ( + rstream.Client.from_env() as client, + client.watch_inventory( + tunnels=rstream.TunnelFilters(status="online") + ) as stream, + ): + async for snapshot in stream: + print( + "last known" if snapshot.stale else "current", + len(snapshot.tunnels), + flush=True, + ) + for tunnel in snapshot.tunnels: + print(" ", tunnel.properties.id, tunnel.properties.name, flush=True) + + +with suppress(KeyboardInterrupt): + asyncio.run(main()) diff --git a/src/rstream/__init__.py b/src/rstream/__init__.py index 37a8760..008dcc7 100644 --- a/src/rstream/__init__.py +++ b/src/rstream/__init__.py @@ -8,6 +8,7 @@ from rstream.control import ControlChannel from rstream.engine_api import ( ClientFilters, + ClientInventory, Event, EventStream, TunnelFilters, @@ -23,6 +24,14 @@ RuntimeError, UnsupportedFeatureError, ) +from rstream.inventory import ( + ClientChanged, + InventoryInitial, + InventorySnapshot, + InventoryStream, + TunnelChanged, + inventory_event, +) from rstream.stable_domains import engine_hostname, generate_stable_domain from rstream.stream import RstreamStream from rstream.tunnel import BytestreamTunnel, format_forwarding_address @@ -47,6 +56,8 @@ def __getattr__(name: str) -> ModuleType: if name == "asgi": return import_module("rstream.asgi") + if name == "sync": + return import_module("rstream.sync") if name == "wsgi": return import_module("rstream.wsgi") raise AttributeError(f"module 'rstream' has no attribute {name!r}") @@ -56,7 +67,9 @@ def __getattr__(name: str) -> ModuleType: "HTTPCORS", "BytestreamTunnel", "Client", + "ClientChanged", "ClientFilters", + "ClientInventory", "ClientOptions", "ConfigurationError", "ControlChannel", @@ -64,6 +77,9 @@ def __getattr__(name: str) -> ModuleType: "EngineError", "Event", "EventStream", + "InventoryInitial", + "InventorySnapshot", + "InventoryStream", "ProtocolError", "ResolvedClientOptions", "RstreamError", @@ -73,6 +89,7 @@ def __getattr__(name: str) -> ModuleType: "ServerDetails", "TLSOptions", "TunnelAuth", + "TunnelChanged", "TunnelFilters", "TunnelInventory", "TunnelProperties", @@ -87,7 +104,9 @@ def __getattr__(name: str) -> ModuleType: "format_forwarding_address", "generate_signing_secret", "generate_stable_domain", + "inventory_event", "sign_payload", + "sync", "verify_event", "wsgi", ] diff --git a/src/rstream/client.py b/src/rstream/client.py index cb7f4c6..c52b62f 100644 --- a/src/rstream/client.py +++ b/src/rstream/client.py @@ -6,6 +6,7 @@ from collections.abc import AsyncIterator, Awaitable, Mapping from contextlib import suppress from typing import TypeVar +from weakref import WeakSet from rstream._proto import rstream_pb2 as pb from rstream.api import RstreamAPIClient, TokenCredentials, engine_from_project @@ -20,11 +21,13 @@ from rstream.control import ControlChannel from rstream.engine_api import ( ClientFilters, + ClientInventory, Event, EventStream, TunnelFilters, TunnelInventory, WatchTransport, + client_inventory_from_json, list_inventory, tunnel_inventory_from_json, watch_events, @@ -32,6 +35,7 @@ ) from rstream.engine_discovery import EngineAPIDiscovery, has_client_certificate from rstream.errors import ConfigurationError, ProtocolError, RuntimeError +from rstream.inventory import InventoryStream, snapshots from rstream.protocol import ( engine_error_from_pb, message_with_open_control_channel_req, @@ -119,6 +123,7 @@ def __init__( self._resolved: ResolvedClientOptions | None = None self._controls: set[ControlChannel] = set() self._control_watchers: set[asyncio.Task[None]] = set() + self._streams: WeakSet[EventStream | InventoryStream] = WeakSet() self._closed = False self._engine_discovery = EngineAPIDiscovery() @@ -330,7 +335,7 @@ async def list_clients( *, filters: ClientFilters | None = None, limit: int | None = None, - ) -> list[Mapping[str, object]]: + ) -> list[ClientInventory]: """List live runtime clients from the engine inventory.""" self._ensure_open() engine, token, tls = await self._engine_api_target() @@ -339,7 +344,7 @@ async def list_clients( params["limit"] = limit if filters is not None: params["filters"] = filters.to_json() - return await list_inventory( + rows = await list_inventory( engine=engine, token=token, path="/clients", @@ -347,6 +352,29 @@ async def list_clients( tls=tls, ) + return [client_inventory_from_json(row) for row in rows] + + def watch_inventory( + self, + *, + tunnels: TunnelFilters | None = None, + clients: ClientFilters | None = None, + transport: WatchTransport = "sse", + ) -> InventoryStream: + """Follow both inventories, or only the categories with an explicit filter.""" + self._ensure_open() + stream = InventoryStream( + snapshots( + lambda: self.watch( + tunnels=tunnels, clients=clients, transport=transport + ), + clients=clients is not None or tunnels is None, + tunnels=tunnels is not None or clients is None, + ) + ) + self._streams.add(stream) + return stream + def watch( self, *, @@ -379,7 +407,9 @@ async def generate() -> AsyncIterator[Event]: finally: await source.aclose() - return EventStream(generate()) + stream = EventStream(generate()) + self._streams.add(stream) + return stream async def _engine_api_target(self) -> tuple[str, str | None, TLSOptions | None]: self._ensure_open() @@ -394,6 +424,9 @@ async def close(self) -> None: if self._closed: return self._closed = True + for stream in tuple(self._streams): + await stream.aclose() + self._streams.clear() await self._engine_discovery.close() failure: BaseException | None = None for control in tuple(self._controls): @@ -507,6 +540,11 @@ async def _resolve_engine( "Engine is required but not configured.", code="ERR_RSTREAM_ENGINE_REQUIRED", ) + if has_client_certificate(resolved.tls) and not resolved.token: + raise ConfigurationError( + "Configure the Engine address directly for this mTLS identity.", + code="ERR_RSTREAM_ENGINE_REQUIRED", + ) credentials = ( TokenCredentials(resolved.token) if resolved.token is not None else None ) diff --git a/src/rstream/engine_api.py b/src/rstream/engine_api.py index e858da4..871910e 100644 --- a/src/rstream/engine_api.py +++ b/src/rstream/engine_api.py @@ -7,12 +7,14 @@ from __future__ import annotations +import asyncio import json import ssl from collections.abc import AsyncGenerator, AsyncIterator, Mapping +from contextlib import aclosing from dataclasses import dataclass, field from datetime import datetime -from typing import Any, Literal +from typing import Any, Generic, Literal, TypedDict, TypeVar, cast from rstream.config import TLSOptions, create_ssl_context from rstream.errors import RuntimeError @@ -98,6 +100,47 @@ def to_json(self) -> dict[str, object]: return out +class ClientInventory(TypedDict, total=False): + """Visible Engine client fields. A projected field is absent from the dict.""" + + id: str + status: str + user_id: str + workspace_id: str + project_id: str + cluster_id: str + endpoint: str + plan: str + provider: str + region: str + agent: str + channel: str + version: str + os: str + arch: str + protocol_version: str + labels: dict[str, str] + + +def client_inventory_from_json(row: Mapping[str, object]) -> ClientInventory: + for key in ClientInventory.__annotations__: + if key not in row: + continue + value = row[key] + if key == "labels": + if isinstance(value, dict) and all( + isinstance(k, str) and isinstance(v, str) for k, v in value.items() + ): + continue + elif isinstance(value, str): + continue + raise RuntimeError( + f"Invalid Engine client field {key!r}.", + code="ERR_RSTREAM_ENGINE_API_PAYLOAD", + ) + return cast(ClientInventory, dict(row)) + + @dataclass(frozen=True) class TunnelInventory: """One live tunnel as reported by the engine inventory.""" @@ -181,29 +224,43 @@ def tunnel_properties_from_json(data: Mapping[str, object]) -> TunnelProperties: ) -class EventStream: - """Async iterator over engine events, also usable as an async context manager. +_T = TypeVar("_T") - Iterating with ``async for`` works directly. Wrapping the stream in - ``async with`` guarantees the underlying connection is closed when the - block exits, including on cancellation. - """ - def __init__(self, source: AsyncIterator[Event]) -> None: +class _OwnedStream(Generic[_T]): + def __init__(self, source: AsyncIterator[_T]) -> None: self._source = source + self._closed = False + self._read: asyncio.Future[_T] | None = None - def __aiter__(self) -> EventStream: + def __aiter__(self) -> _OwnedStream[_T]: return self - async def __anext__(self) -> Event: - return await self._source.__anext__() + async def __anext__(self) -> _T: + if self._closed: + raise StopAsyncIteration + if self._read is not None: + raise RuntimeError( + "Only one read may be pending on a watch.", + code="ERR_RSTREAM_CONCURRENT_READ", + ) + self._read = asyncio.ensure_future(anext(self._source)) + try: + return await self._read + finally: + self._read = None async def aclose(self) -> None: + self._closed = True + read = self._read + if read is not None: + read.cancel() + await asyncio.gather(read, return_exceptions=True) aclose = getattr(self._source, "aclose", None) if aclose is not None: await aclose() - async def __aenter__(self) -> EventStream: + async def __aenter__(self) -> _OwnedStream[_T]: return self async def __aexit__( @@ -215,6 +272,16 @@ async def __aexit__( await self.aclose() +class EventStream(_OwnedStream[Event]): + """Single-connection event iterator. Use async with to close it on exit.""" + + def __aiter__(self) -> EventStream: + return self + + async def __aenter__(self) -> EventStream: + return self + + def watch_params_json( tunnels: TunnelFilters | None, clients: ClientFilters | None, @@ -268,6 +335,7 @@ async def list_inventory( raise RuntimeError( f"Engine API error {response.status_code}: {response.text}", code="ERR_RSTREAM_ENGINE_API_HTTP", + details={"status": response.status_code}, ) value = response.json() if not isinstance(value, list): @@ -275,7 +343,12 @@ async def list_inventory( "Engine API returned an unexpected payload.", code="ERR_RSTREAM_ENGINE_API_PAYLOAD", ) - return [item for item in value if isinstance(item, Mapping)] + if not all(isinstance(item, dict) for item in value): + raise RuntimeError( + "Engine inventory contains a non-object row.", + code="ERR_RSTREAM_ENGINE_API_PAYLOAD", + ) + return value async def watch_events( @@ -287,20 +360,19 @@ async def watch_events( transport: WatchTransport, ) -> AsyncGenerator[Event, None]: if transport == "websocket": - async for event in _watch_websocket( - engine=engine, token=token, params_json=params_json, tls=tls - ): - yield event - return - if transport != "sse": + connect = _watch_websocket + elif transport == "sse": + connect = _watch_sse + else: raise RuntimeError( f"Unsupported watch transport {transport!r}.", code="ERR_RSTREAM_WATCH_TRANSPORT", ) - async for event in _watch_sse( - engine=engine, token=token, params_json=params_json, tls=tls - ): - yield event + async with aclosing( + connect(engine=engine, token=token, params_json=params_json, tls=tls) + ) as source: + async for event in source: + yield event async def _watch_sse( @@ -309,7 +381,7 @@ async def _watch_sse( token: str | None, params_json: Mapping[str, object] | None, tls: TLSOptions | None, -) -> AsyncIterator[Event]: +) -> AsyncGenerator[Event, None]: httpx = _require_httpx() url = f"https://{engine}/api/sse" query: dict[str, str] = {} @@ -319,7 +391,9 @@ async def _watch_sse( if token: headers["Authorization"] = f"Bearer {token}" async with ( - httpx.AsyncClient(verify=_httpx_verify(tls), timeout=None) as client, + httpx.AsyncClient( + verify=_httpx_verify(tls), timeout=httpx.Timeout(15, read=75) + ) as client, client.stream("GET", url, params=query, headers=headers) as response, ): if response.status_code < 200 or response.status_code >= 300: @@ -327,21 +401,58 @@ async def _watch_sse( raise RuntimeError( f"Engine SSE error {response.status_code}: {body}", code="ERR_RSTREAM_ENGINE_API_HTTP", + details={"status": response.status_code}, ) - data_lines: list[str] = [] - async for line in response.aiter_lines(): - if line == "": - if data_lines: - payload = "\n".join(data_lines) - data_lines = [] - event = _decode_event(payload) - if event is not None: - yield event - continue - if line.startswith(":"): - continue - if line.startswith("data:"): - data_lines.append(line[5:].lstrip()) + if ( + response.headers.get("content-type", "").split(";", 1)[0].strip().lower() + != "text/event-stream" + ): + raise RuntimeError( + "Expected an Engine event stream.", code="ERR_RSTREAM_EVENT_JSON" + ) + async for payload in _sse_payloads(response.aiter_bytes()): + event = _decode_event(payload) + if event is not None: + yield event + + +_MAX_EVENT_BYTES = 16 * 1024 * 1024 + + +async def _sse_payloads(chunks: AsyncIterator[bytes]) -> AsyncIterator[str]: + line = bytearray() + data = bytearray() + first = True + previous_cr = False + async for chunk in chunks: + if not chunk: + continue + if previous_cr and chunk.startswith(b"\n"): + chunk = chunk[1:] + if not chunk: + previous_cr = False + continue + previous_cr = chunk.endswith(b"\r") + parts = chunk.replace(b"\r\n", b"\n").replace(b"\r", b"\n").split(b"\n") + for index, part in enumerate(parts): + if len(line) + len(part) + len(data) > _MAX_EVENT_BYTES: + raise RuntimeError( + "Engine event exceeds its size limit.", + code="ERR_RSTREAM_EVENT_JSON", + ) + line.extend(part) + if index == len(parts) - 1: + break + if first: + line = line.removeprefix(b"\xef\xbb\xbf") + first = False + if not line and data: + yield data.decode("utf-8") + data.clear() + elif line == b"data" or line.startswith(b"data:"): + data.extend(line[5:].removeprefix(b" ")) + data.extend(b"\n") + line.clear() async def _watch_websocket( @@ -350,9 +461,9 @@ async def _watch_websocket( token: str | None, params_json: Mapping[str, object] | None, tls: TLSOptions | None, -) -> AsyncIterator[Event]: +) -> AsyncGenerator[Event, None]: try: - import websockets + from websockets.asyncio.client import connect as websocket_connect except ImportError as error: raise RuntimeError( "Install rstreamlabs-rstream[realtime] to watch events over WebSocket.", @@ -374,10 +485,21 @@ async def _watch_websocket( ssl_context.verify_mode = ssl.CERT_NONE elif isinstance(verify, ssl.SSLContext): ssl_context = verify + + # The Engine authority was selected for this identity. A redirect must not + # carry the bearer token or re-use its client certificate on another host. + class DirectConnection(websocket_connect): + def process_redirect(self, exc: Exception) -> Exception | str: + return exc + if ssl_context is not None: - connect = websockets.connect(url, additional_headers=headers, ssl=ssl_context) + connect = DirectConnection( + url, additional_headers=headers, ssl=ssl_context, max_size=_MAX_EVENT_BYTES + ) else: - connect = websockets.connect(url, additional_headers=headers) + connect = DirectConnection( + url, additional_headers=headers, max_size=_MAX_EVENT_BYTES + ) async with connect as connection: async for message in connection: if isinstance(message, bytes): @@ -398,8 +520,10 @@ def _decode_event(payload: str) -> Event | None: f"Invalid event JSON: {error}", code="ERR_RSTREAM_EVENT_JSON", ) from error - if not isinstance(data, Mapping): - return None + if not isinstance(data, Mapping) or not isinstance(data.get("type"), str): + raise RuntimeError( + "Engine event is missing its type.", code="ERR_RSTREAM_EVENT_JSON" + ) return event_from_json(data) diff --git a/src/rstream/inventory.py b/src/rstream/inventory.py new file mode 100644 index 0000000..cd88aab --- /dev/null +++ b/src/rstream/inventory.py @@ -0,0 +1,204 @@ +"""Typed Engine inventory events and reconnecting snapshots.""" + +from __future__ import annotations + +import asyncio +import random +import socket +import ssl +import time +from collections.abc import AsyncIterator, Callable, Mapping +from copy import deepcopy +from dataclasses import dataclass +from typing import Literal, TypeVar, cast + +from rstream.engine_api import ( + ClientInventory, + Event, + EventStream, + TunnelInventory, + _OwnedStream, + client_inventory_from_json, + tunnel_inventory_from_json, +) +from rstream.errors import RuntimeError + +Change = Literal["created", "updated", "deleted"] + + +@dataclass(frozen=True) +class InventorySnapshot: + """Visible rows, marked stale during reconnection.""" + + clients: tuple[ClientInventory, ...] + tunnels: tuple[TunnelInventory, ...] + stale: bool = False + + +@dataclass(frozen=True) +class InventoryInitial: + snapshot: InventorySnapshot + + +@dataclass(frozen=True) +class ClientChanged: + change: Change + client: ClientInventory + + +@dataclass(frozen=True) +class TunnelChanged: + change: Change + tunnel: TunnelInventory + + +def _invalid(message: str) -> RuntimeError: + return RuntimeError(message, code="ERR_RSTREAM_ENGINE_API_PAYLOAD") + + +def _rows(body: Mapping[str, object], key: str) -> list[Mapping[str, object]]: + rows = body.get(key) + if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows): + raise _invalid(f"Expected an inventory array for {key}.") + return rows + + +def inventory_event( + event: Event, *, clients: bool = True, tunnels: bool = True +) -> InventoryInitial | ClientChanged | TunnelChanged | None: + """Decode inventory changes. Other event categories return None.""" + body = event.object + if event.type == "state.initial": + if body is None: + raise _invalid("Expected an inventory snapshot.") + return InventoryInitial( + InventorySnapshot( + tuple(client_inventory_from_json(row) for row in _rows(body, "clients")) + if clients + else (), + tuple(tunnel_inventory_from_json(row) for row in _rows(body, "tunnels")) + if tunnels + else (), + ) + ) + kind, _, action = event.type.partition(".") + if action not in ("created", "updated", "deleted") or not ( + (kind == "client" and clients) or (kind == "tunnel" and tunnels) + ): + return None + if body is None or not isinstance(body.get("id"), str) or not body["id"]: + raise _invalid("Expected an identifier in an inventory change.") + change = cast(Change, action) + if kind == "client": + return ClientChanged(change, client_inventory_from_json(body)) + return TunnelChanged(change, tunnel_inventory_from_json(body)) + + +_T = TypeVar("_T") + + +def _apply( + rows: list[_T], row: _T, change: Change, key: Callable[[_T], str | None] +) -> None: + identity = key(row) + for index, previous in enumerate(rows): + if key(previous) == identity: + if change == "deleted": + del rows[index] + else: + rows[index] = row + return + if change != "deleted": + rows.append(row) + + +def _retryable(error: Exception) -> bool: + cause: BaseException | None = error + seen: set[int] = set() + while cause is not None and id(cause) not in seen: + if isinstance(cause, ssl.SSLError): + return False + seen.add(id(cause)) + cause = cause.__cause__ or cause.__context__ + if isinstance(error, RuntimeError): + return error.code == "ERR_RSTREAM_ENGINE_API_HTTP" and ( + error.details or {} + ).get("status") in (408, 429, 500, 502, 503, 504) + if isinstance(error, (ConnectionError, TimeoutError, socket.gaierror)): + return True + try: + import httpx + except ImportError: + pass + else: + if isinstance( + error, + (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError), + ): + return True + try: + from websockets.exceptions import ConnectionClosed, InvalidStatus + except ImportError: + return False + if isinstance(error, InvalidStatus): + return error.response.status_code in (408, 429, 500, 502, 503, 504) + return isinstance(error, ConnectionClosed) and ( + error.rcvd is None or error.rcvd.code in (1000, 1001, 1006, 1011, 1012, 1013) + ) + + +class InventoryStream(_OwnedStream[InventorySnapshot]): + """Async snapshot iterator owned by its client.""" + + +async def snapshots( + connect: Callable[[], EventStream], *, clients: bool, tunnels: bool +) -> AsyncIterator[InventorySnapshot]: + delay = 0.25 + client_rows: list[ClientInventory] = [] + tunnel_rows: list[TunnelInventory] = [] + while True: + current = False + started = time.monotonic() + try: + async with connect() as stream: + async for event in stream: + change = inventory_event(event, clients=clients, tunnels=tunnels) + if change is None: + continue + if isinstance(change, InventoryInitial): + client_rows = list(change.snapshot.clients) + tunnel_rows = list(change.snapshot.tunnels) + current = True + elif not current: + raise _invalid( + "Inventory changes arrived before the initial snapshot." + ) + elif isinstance(change, ClientChanged): + _apply( + client_rows, + change.client, + change.change, + lambda row: row.get("id"), + ) + else: + _apply( + tunnel_rows, + change.tunnel, + change.change, + lambda row: row.properties.id, + ) + yield deepcopy( + InventorySnapshot(tuple(client_rows), tuple(tunnel_rows)) + ) + except Exception as error: + if not _retryable(error): + raise + if current: + yield deepcopy( + InventorySnapshot(tuple(client_rows), tuple(tunnel_rows), stale=True) + ) + if time.monotonic() - started >= 30: + delay = 0.25 + await asyncio.sleep(random.uniform(delay / 2, delay)) + delay = min(10, delay * 2) diff --git a/src/rstream/sync.py b/src/rstream/sync.py new file mode 100644 index 0000000..6de95cd --- /dev/null +++ b/src/rstream/sync.py @@ -0,0 +1,151 @@ +"""Blocking Engine inventory for applications that do not run an asyncio event loop.""" + +from __future__ import annotations + +import asyncio +import threading +from collections.abc import Iterator, Mapping + +from rstream.client import Client +from rstream.config import TLSOptions +from rstream.engine_api import ( + ClientFilters, + ClientInventory, + TunnelFilters, + TunnelInventory, + WatchTransport, +) +from rstream.inventory import InventorySnapshot, InventoryStream + + +class InventoryClient: + """Owns an Engine client and event loop on the thread entering the context.""" + + def __init__( + self, + *, + engine: str | None = None, + token: str | None = None, + tls: TLSOptions | None = None, + context: str | None = None, + config_path: str | None = None, + api_url: str | None = None, + project_endpoint: str | None = None, + region: str | None = None, + control_plane_headers: Mapping[str, str] | None = None, + read_config_file: bool = True, + ) -> None: + self._client = Client( + engine=engine, + token=token, + tls=tls, + context=context, + config_path=config_path, + api_url=api_url, + project_endpoint=project_endpoint, + region=region, + control_plane_headers=control_plane_headers, + read_config_file=read_config_file, + ) + self._loop: asyncio.AbstractEventLoop | None = None + self._thread: int | None = None + self._closed = False + + def __enter__(self) -> InventoryClient: + if self._closed or self._loop is not None: + raise RuntimeError("The inventory client context has already been entered.") + try: + asyncio.get_running_loop() + except RuntimeError: + pass + else: + raise RuntimeError("Use rstream.Client from an asyncio event loop.") + self._thread = threading.get_ident() + self._loop = asyncio.new_event_loop() + return self + + def _active_loop(self) -> asyncio.AbstractEventLoop: + if self._loop is None or threading.get_ident() != self._thread: + raise RuntimeError( + "Use the inventory client inside its context on the owning thread." + ) + return self._loop + + def list_clients( + self, *, filters: ClientFilters | None = None, limit: int | None = None + ) -> list[ClientInventory]: + return self._active_loop().run_until_complete( + self._client.list_clients(filters=filters, limit=limit) + ) + + def list_tunnels( + self, *, filters: TunnelFilters | None = None, limit: int | None = None + ) -> list[TunnelInventory]: + return self._active_loop().run_until_complete( + self._client.list_tunnels(filters=filters, limit=limit) + ) + + def watch_inventory( + self, + *, + tunnels: TunnelFilters | None = None, + clients: ClientFilters | None = None, + transport: WatchTransport = "sse", + ) -> InventoryWatch: + self._active_loop() + return InventoryWatch( + self, + self._client.watch_inventory( + tunnels=tunnels, clients=clients, transport=transport + ), + ) + + def close(self) -> None: + if self._closed: + return + loop = self._active_loop() + try: + loop.run_until_complete(self._client.close()) + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.run_until_complete(loop.shutdown_default_executor()) + finally: + loop.close() + self._loop = None + self._closed = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: object, + ) -> None: + self.close() + + +class InventoryWatch(Iterator[InventorySnapshot]): + """Blocking inventory iterator on the owning client's thread.""" + + def __init__(self, owner: InventoryClient, stream: InventoryStream) -> None: + self._owner = owner + self._stream = stream + + def __next__(self) -> InventorySnapshot: + try: + return self._owner._active_loop().run_until_complete(anext(self._stream)) + except StopAsyncIteration: + raise StopIteration from None + + def close(self) -> None: + if not self._owner._closed: + self._owner._active_loop().run_until_complete(self._stream.aclose()) + + def __enter__(self) -> InventoryWatch: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: object, + ) -> None: + self.close() diff --git a/tests/e2e/test_real_engine.py b/tests/e2e/test_real_engine.py index 07388b9..9c05e5f 100644 --- a/tests/e2e/test_real_engine.py +++ b/tests/e2e/test_real_engine.py @@ -26,6 +26,35 @@ async def test_real_engine_certificate_http_inventory() -> None: @pytest.mark.asyncio +@pytest.mark.parametrize("transport", ["sse", "websocket"]) +async def test_real_engine_inventory_lifecycle( + transport: rstream.WatchTransport, +) -> None: + if not real_engine_enabled(): + pytest.skip("Set RSTREAM_PYTHON_E2E_ENGINE to run the inventory lifecycle.") + name = f"python-inventory-{uuid.uuid4().hex[:12]}" + filters = rstream.TunnelFilters(name=name, status="online") + async with ( + real_engine_client(zero_rtt=False) as client, + await client.connect() as control, + client.watch_inventory(tunnels=filters, transport=transport) as snapshots, + ): + assert not (await asyncio.wait_for(anext(snapshots), 5)).tunnels + tunnel = await control.create_tunnel(name=name, publish=False) + try: + created = await asyncio.wait_for(anext(snapshots), 5) + assert [row.properties.id for row in created.tunnels] == [tunnel.id] + assert [ + row.properties.id for row in await client.list_tunnels(filters=filters) + ] == [tunnel.id] + assert await client.list_clients( + filters=rstream.ClientFilters(status="online") + ) + finally: + await control.close_tunnel(tunnel.id) + assert not (await asyncio.wait_for(anext(snapshots), 5)).tunnels + + async def test_real_engine_private_bytestream_matrix() -> None: if not real_engine_enabled(): pytest.skip( diff --git a/tests/unit/test_inventory.py b/tests/unit/test_inventory.py new file mode 100644 index 0000000..d76882f --- /dev/null +++ b/tests/unit/test_inventory.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import asyncio +import json +import ssl +from collections.abc import AsyncIterator +from typing import cast + +import httpx +import pytest + +import rstream +from rstream.engine_api import EventStream, _sse_payloads, event_from_json +from rstream.inventory import _retryable +from rstream.sync import InventoryClient + + +def initial( + clients: list[dict[str, object]], tunnels: list[dict[str, object]] +) -> rstream.Event: + return event_from_json( + { + "type": "state.initial", + "object": { + "clients": clients, + "tunnels": tunnels, + "snapshot_at": "2026-01-01T00:00:00Z", + }, + } + ) + + +async def test_watch_resynchronizes_without_aliasing_and_honors_selection( + monkeypatch: pytest.MonkeyPatch, +) -> None: + connections = 0 + released = asyncio.Event() + filters = rstream.TunnelFilters(status="online") + + async def events() -> AsyncIterator[rstream.Event]: + nonlocal connections + connections += 1 + if connections == 1: + yield initial( + [{"id": "other"}], [{"id": "a", "labels": {"key": "original"}}] + ) + for kind, body in ( + ("client.deleted", {"id": "other"}), + ("tunnel.updated", {"id": "a", "name": "new"}), + ("tunnel.created", {"id": "b"}), + ("tunnel.deleted", {"id": "a"}), + ): + yield event_from_json({"type": kind, "object": body}) + return + try: + yield initial([], [{"name": "same"}, {"name": "same"}]) + await asyncio.Event().wait() + finally: + released.set() + + async with rstream.Client() as client: + + def connect(**kwargs: object) -> EventStream: + assert kwargs["tunnels"] is filters + return EventStream(events()) + + monkeypatch.setattr(client, "watch", connect) + async with client.watch_inventory(tunnels=filters) as stream: + first = await anext(stream) + assert not first.stale and not first.clients + cast(dict[str, str], first.tunnels[0].properties.labels)["key"] = ( + "user edit" + ) + assert (await anext(stream)).tunnels[0].properties.name == "new" + assert len((await anext(stream)).tunnels) == 2 + fresh = await anext(stream) + assert [row.properties.id for row in fresh.tunnels] == ["b"] + stale = await anext(stream) + assert stale.stale and stale.tunnels == fresh.tunnels + after = await asyncio.wait_for(anext(stream), 2) + assert not after.stale and [ + row.properties.name for row in after.tunnels + ] == ["same", "same"] + blocked = asyncio.create_task(stream.__anext__()) + await asyncio.sleep(0) + await asyncio.wait_for(client.close(), 2) + with pytest.raises(asyncio.CancelledError): + await blocked + assert released.is_set() and connections == 2 + + +async def test_client_rows_survive_mutation_and_silent_gaps_fail( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def events() -> AsyncIterator[rstream.Event]: + yield initial([{"id": "a", "labels": {"site": "one"}}], []) + yield event_from_json({"type": "client.created", "object": {"id": "b"}}) + yield event_from_json({"type": "client.updated", "object": {}}) + + async with rstream.Client() as client: + monkeypatch.setattr(client, "watch", lambda **kw: EventStream(events())) + async with client.watch_inventory(clients=rstream.ClientFilters()) as stream: + row = (await anext(stream)).clients[0] + row["labels"]["site"] = "edited" + assert (await anext(stream)).clients[0]["labels"] == {"site": "one"} + with pytest.raises(rstream.RstreamRuntimeError, match="identifier"): + await anext(stream) + + +async def test_sse_framing_across_chunks() -> None: + async def chunks() -> AsyncIterator[bytes]: + for byte in b"\xef\xbb\xbf:keepalive\r\n\r\ndata: {\r\ndata: }\r\n\r\n": + yield bytes([byte]) + + assert [json.loads(payload) async for payload in _sse_payloads(chunks())] == [{}] + + +def test_retry_policy_preserves_tls_and_policy_denials() -> None: + for status in (401, 403, 404): + assert not _retryable( + rstream.RstreamRuntimeError( + "denied", code="ERR_RSTREAM_ENGINE_API_HTTP", details={"status": status} + ) + ) + network = httpx.ConnectError("handshake") + network.__cause__ = ssl.SSLCertVerificationError("untrusted") + assert not _retryable(network) + assert _retryable(ConnectionRefusedError()) + assert _retryable( + rstream.RstreamRuntimeError( + "unavailable", code="ERR_RSTREAM_ENGINE_API_HTTP", details={"status": 503} + ) + ) + + +def test_blocking_inventory_uses_one_owned_loop_and_closes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + loops = [] + closed = [] + + async def fake_list( + self: rstream.Client, **kwargs: object + ) -> list[rstream.ClientInventory]: + loops.append(asyncio.get_running_loop()) + return [{"id": "client"}] + + async def events() -> AsyncIterator[rstream.Event]: + try: + loops.append(asyncio.get_running_loop()) + yield initial([{"id": "client"}], []) + finally: + closed.append(True) + + monkeypatch.setattr(rstream.Client, "list_clients", fake_list) + monkeypatch.setattr(rstream.Client, "watch", lambda *a, **kw: EventStream(events())) + with InventoryClient() as client: + assert client.list_clients()[0]["id"] == "client" + with client.watch_inventory() as stream: + assert next(stream).clients == ({"id": "client"},) + assert loops[0] is loops[1] and loops[0].is_closed() and closed == [True]