Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 17 additions & 20 deletions docs/tunnels/003-inventory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
10 changes: 10 additions & 0 deletions examples/api-list-inventory/README.md
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 19 additions & 0 deletions examples/api-list-inventory/main.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 10 additions & 0 deletions examples/api-watch-tunnels/README.md
Original file line number Diff line number Diff line change
@@ -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.
25 changes: 25 additions & 0 deletions examples/api-watch-tunnels/main.py
Original file line number Diff line number Diff line change
@@ -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())
19 changes: 19 additions & 0 deletions src/rstream/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from rstream.control import ControlChannel
from rstream.engine_api import (
ClientFilters,
ClientInventory,
Event,
EventStream,
TunnelFilters,
Expand All @@ -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
Expand All @@ -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}")
Expand All @@ -56,14 +67,19 @@ def __getattr__(name: str) -> ModuleType:
"HTTPCORS",
"BytestreamTunnel",
"Client",
"ClientChanged",
"ClientFilters",
"ClientInventory",
"ClientOptions",
"ConfigurationError",
"ControlChannel",
"CreateTunnelOptions",
"EngineError",
"Event",
"EventStream",
"InventoryInitial",
"InventorySnapshot",
"InventoryStream",
"ProtocolError",
"ResolvedClientOptions",
"RstreamError",
Expand All @@ -73,6 +89,7 @@ def __getattr__(name: str) -> ModuleType:
"ServerDetails",
"TLSOptions",
"TunnelAuth",
"TunnelChanged",
"TunnelFilters",
"TunnelInventory",
"TunnelProperties",
Expand All @@ -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",
]
44 changes: 41 additions & 3 deletions src/rstream/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -20,18 +21,21 @@
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,
watch_params_json,
)
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,
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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()
Expand All @@ -339,14 +344,37 @@ 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",
params_json=params or None,
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,
*,
Expand Down Expand Up @@ -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()
Expand All @@ -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):
Expand Down Expand Up @@ -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
)
Expand Down
Loading
Loading