From 3813148f74364902ee65aeba76ea5f335c715da2 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:54:47 +0100 Subject: [PATCH 01/11] build: refresh Hatchling and qualify Python 3.14 and 3.15 --- .github/workflows/ci.yml | 6 +++--- .github/workflows/publish.yml | 4 ++-- .github/workflows/release-candidate.yml | 4 ++-- pyproject.toml | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ffb169d..d260401 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,12 +14,12 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ["3.10", "3.11", "3.12", "3.13"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} - name: Run checks @@ -37,7 +37,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.13" - name: Build distribution diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 43505cf..093cef4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -77,7 +77,7 @@ jobs: # retained candidate archives are uploaded; this source is not rebuilt. path: candidate-source persist-credentials: false - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-candidate-${{ steps.release.outputs.version }} path: candidate @@ -94,7 +94,7 @@ jobs: run: >- python .github/scripts/verify-pypi-release.py "$VERSION" candidate/packages --github-output "$GITHUB_OUTPUT" - - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 if: ${{ steps.pypi.outputs.publish == 'true' }} with: packages-dir: candidate/packages diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index 88556cc..574de98 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.13" - name: Build and verify distributions @@ -49,7 +49,7 @@ jobs: mkdir -p candidate/packages mv dist/* candidate/packages/ (cd candidate && sha256sum -- packages/* > SHA256SUMS) - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-candidate-${{ env.VERSION }} path: candidate diff --git a/pyproject.toml b/pyproject.toml index e497eb0..67a52fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["hatchling==1.32.0"] +requires = ["hatchling==1.33.0"] build-backend = "hatchling.build" [project] From a0167feb3a3e96134b1635ad60f3d7633838d2f9 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:05:54 +0100 Subject: [PATCH 02/11] docs: align async SDK onboarding and framework prerequisites --- README.md | 294 ++++---------------------------------- SECURITY.md | 11 +- docs/001-configuration.md | 18 +++ docs/002-tunnels.md | 26 +++- docs/README.md | 27 ++-- 5 files changed, 89 insertions(+), 287 deletions(-) diff --git a/README.md b/README.md index 9f07009..389bd68 100644 --- a/README.md +++ b/README.md @@ -1,105 +1,32 @@ # rstream Python SDK -`rstreamlabs-rstream` is the Python SDK for rstream tunnels and webhook -receivers. Python code imports it as `rstream`. +Connect Python applications to rstream without running a separate agent process. The SDK creates tunnels, dials private services and verifies webhook deliveries. Its async API fits `asyncio` applications, with adapters that serve ASGI and WSGI applications directly over accepted tunnel streams. -The SDK is async-first, framework-neutral, and uses the same runtime protocol -and CLI-compatible configuration model as the Go, JavaScript, Java, and C++ -SDKs. It is designed for Python services that need to publish local HTTP -applications, dial private tunnels, accept bytestream tunnel connections -directly, or verify rstream webhook deliveries in a backend framework. +The package is named `rstreamlabs-rstream`; import it as `rstream`. Python 3.10 or newer is required. -## SDK Surface +## Where this SDK fits -This repository targets Python 3.10 and newer. +An rstream agent connects outbound to the edge, which routes traffic to the application and applies project and tunnel policy. Published tunnels provide a forwarding address; private tunnels are reached by name or ID through an authenticated rstream client. -The first public release focuses on the Python-native surface that is ready for -production use: - -| Area | Supported | +| Integration | Python support | | --- | --- | -| Runtime client | Async control-channel client | -| Published tunnels | HTTP/1.1 bytestream tunnels | -| Private tunnels | Dial by tunnel name or ID | -| Local forwarding | `BytestreamTunnel.forward_to(host, port)` | -| Direct accept | `await tunnel.accept()` and async iteration | -| ASGI helper | Direct HTTP/1.1 bridge for ASGI apps | -| WSGI helper | Direct HTTP/1.1 bridge for WSGI apps | -| Live inventory | `client.list_tunnels()` and `client.list_clients()` with filters | -| Real-time events | `client.watch()` over SSE or WebSocket | -| Webhooks | Signature generation, verification, and event parsing | -| Config | CLI-compatible YAML config and environment variables | - -Datagram tunnels, QUIC runtime transport, HTTP/3 tunnel creation, custom -transport proxies, and external credential stores are rejected explicitly by -this SDK version instead of being ignored. - -## Install - -```bash -pip install rstreamlabs-rstream -``` - -For ASGI/FastAPI helpers: +| Application servers | Serve HTTP/1.1 through ASGI, WSGI or accepted bytestreams. | +| Existing services | Forward tunnel connections to a local TCP port. | +| Private connectivity | Dial bytestream tunnels by name or ID. | +| Service discovery | Query inventory and watch lifecycle events with optional HTTP dependencies. | +| Webhooks | Verify signatures and parse deliveries in your framework. | -```bash -pip install "rstreamlabs-rstream[asgi]" -``` - -For WSGI/Flask/Django helpers: - -```bash -pip install "rstreamlabs-rstream[wsgi]" -``` - -For managed project endpoint discovery through the Control plane API: +The runtime connects to the engine over TLS. Datagram tunnels, QUIC runtime transport and HTTP/3 tunnel creation are outside this SDK’s current scope. For broader protocol support, see the [Go reference SDK](https://github.com/rstreamlabs/rstream-go). -```bash -pip install "rstreamlabs-rstream[api]" -``` +## Publish a FastAPI application -For local example applications: +Install the SDK’s ASGI adapter and FastAPI: -```bash -pip install "rstreamlabs-rstream[examples]" +```sh +pip install "rstreamlabs-rstream[asgi]" fastapi ``` -## Configuration - -The SDK reads the same config file as the CLI by default: - -```text -~/.rstream/config.yaml -``` - -Configuration is resolved in this order: - -1. Explicit `Client(...)` options. -2. Environment variables. -3. The selected context in the config file. -4. SDK defaults. - -## Environment variables - -| Variable | Purpose | -| --- | --- | -| `RSTREAM_CONFIG` | Override the config file path. | -| `RSTREAM_CONTEXT` | Select a context from the config file. | -| `RSTREAM_ENGINE` | Use an explicit engine host and optional port. | -| `RSTREAM_AUTHENTICATION_TOKEN` | Use an explicit authentication token. | -| `RSTREAM_MTLS_CERT_FILE` | Client certificate file for mTLS authentication. | -| `RSTREAM_MTLS_KEY_FILE` | Client private key file for mTLS authentication. | -| `RSTREAM_API_URL` | Control plane API URL for managed project discovery. | -| `RSTREAM_REGION` | Authorized region to select for a managed project. | -| `RSTREAM_CONTROL_PLANE_HEADERS` | Additional Control plane request headers encoded as a JSON object. | - -`RSTREAM_ENGINE_ADDRESS` is also accepted for compatibility with older local -SDK workflows. Prefer `RSTREAM_ENGINE` in new code. - -See [docs/001-configuration.md](docs/001-configuration.md) for supported YAML fields and -error behavior. - -## FastAPI tunnel +The SDK reads the [configuration](docs/001-configuration.md) selected with the rstream CLI. Set up a project context with `rstream login` and `rstream project use my-project-endpoint`, replacing the endpoint with your own. Servers and devices can use project-scoped credentials or certificate files instead. ```python import asyncio @@ -133,186 +60,19 @@ async def main() -> None: asyncio.run(main()) ``` -The ASGI helper parses accepted rstream streams and dispatches them to the app -in-process. It does not start a loopback server. - -## Local forwarding - -`forward_to()` remains available for existing services that already listen on a -local TCP port: - -```python -await tunnel.forward_to("127.0.0.1", 8000) -``` - -It keeps accepting rstream streams and relays them to the local TCP service -until the tunnel or control channel is closed. - -The control channel uses a negotiated heartbeat deadline. If that deadline -expires, or the control transport ends unexpectedly, the SDK immediately stops -accepting new streams but lets already accepted streams and active -`forward_to()` relays drain normally. This avoids interrupting an established -application session because of a transient or asymmetric control-path outage. -An explicit tunnel/control close or a protocol violation remains a hard close -and terminates active local forwarding. Applications should use each stream's -EOF/error as its payload-lifecycle signal; `control.done()` only describes the -control plane. - -## Private dial - -```python -import asyncio - -import rstream - - -async def main() -> None: - async with ( - rstream.Client.from_env() as client, - await client.dial("private-api") as stream, - ): - stream.write(b"ping") - await stream.drain() - print(await stream.read(1024)) - - -asyncio.run(main()) -``` - -Private tunnels are addressed by name or ID. They do not expose a public -forwarding address. - -## Live inventory and real-time events - -The engine exposes its live state through the same client. `list_tunnels` and -`list_clients` return the current inventory, optionally filtered, and `watch` -streams lifecycle events (`tunnel.created`, `tunnel.updated`, -`tunnel.deleted`, and the client equivalents) as an async iterator. Label -filters make the inventory usable as a service registry: tag tunnels at -creation time, then discover them by label. - -```python -import asyncio - -import rstream - - -async def main() -> None: - async with rstream.Client.from_env() as client: - filters = rstream.TunnelFilters(labels={"role": "inference"}) - for tunnel in await client.list_tunnels(filters=filters): - print(tunnel.properties.name, tunnel.status) - async for event in client.watch(tunnels=filters, transport="websocket"): - print(event.type, event.object) - - -asyncio.run(main()) -``` - -Listing and the SSE transport require the `api` extra (`pip install -"rstreamlabs-rstream[api]"`); the WebSocket transport requires the `realtime` extra, which -adds the `websockets` dependency. The watch connection uses the runtime token -and ends when the surrounding task is cancelled. - -## Webhook receiver - -```python -from fastapi import Request - -import rstream - +Save this as `main.py` and run `python main.py`. Open the printed forwarding address to reach the application. The adapter handles HTTP in-process, so no local listening port is needed. The [runnable FastAPI example](examples/fastapi-tunnel) includes interrupt handling. -async def handle_webhook(request: Request) -> None: - payload = await request.body() - signature = request.headers["rstream-signature"] - secret = "whsec_..." +## Documentation - event = rstream.verify_event(payload, signature, secret) - resource_id = event.object.get("id") - if event.type == "tunnel.created": - print("Tunnel is online:", resource_id) -``` - -`event.id` is suitable for idempotency. Keep the raw request body unchanged when -verifying the signature. - -See [docs/003-webhooks.md](docs/003-webhooks.md) for the payload shape and headers. - -## Examples - -| Example | Purpose | +| Task | Guide | | --- | --- | -| [examples/forward-local-port](examples/forward-local-port) | Publish an existing local TCP service. | -| [examples/private-dial](examples/private-dial) | Dial a private tunnel by name or ID. | -| [examples/fastapi-tunnel](examples/fastapi-tunnel) | Publish a FastAPI app through the direct ASGI helper. | -| [examples/flask-tunnel](examples/flask-tunnel) | Publish a Flask app through the direct WSGI helper. | -| [examples/django-tunnel](examples/django-tunnel) | Publish a Django app through the direct WSGI helper. | -| [examples/aiohttp-local-forwarding](examples/aiohttp-local-forwarding) | Publish an aiohttp app through managed local forwarding. | -| [examples/webhook-receiver](examples/webhook-receiver) | Verify webhook deliveries inside a FastAPI route. | -| [examples/flask-webhook-receiver](examples/flask-webhook-receiver) | Verify webhook deliveries inside a Flask route. | -| [examples/django-webhook-receiver](examples/django-webhook-receiver) | Verify webhook deliveries inside a Django view. | - -## Development - -```bash -python -m venv .venv -. .venv/bin/activate -pip install -e ".[dev]" -ruff check . -ruff format --check . -mypy -pytest -python -m build -``` - -Real-engine tests are opt-in: - -```bash -RSTREAM_PYTHON_E2E=1 pytest tests/e2e -``` - -See [docs/004-testing.md](docs/004-testing.md) for local-engine and managed-environment -test commands. - -## Repository setup and release - -The intended GitHub repository is `rstreamlabs/rstream-python`. CI requires no -secret for normal pull request checks. Release automation uses release-please and -requires the maintainer-managed `RELEASE_PLEASE_TOKEN` secret plus the -`CI_ALLOWED_ACTOR` repository variable. - -See [docs/006-github-setup.md](docs/006-github-setup.md) before creating or publishing -the repository. - -## License - -Apache-2.0. See [LICENSE](LICENSE). - -## Engine HTTP access with certificates - -The existing `list_clients`, `list_tunnels` and `watch` methods support enrolled -file-based mTLS identities. Keep one `Client` in an `async with` block. It discovers -the dedicated project API through anonymous, verified HTTPS and caches the address -in memory, normally for one hour. Concurrent callers share discovery; cancellation -of one waiter does not cancel others, and closing the client cancels pending -lookup work. No YAML field, persistent cache or new login is required. - -Discovery never sends the certificate, a token, cookies or Control plane headers, -refuses redirects and verifies the server even when runtime TLS is marked insecure. -The ordinary Engine hostname never requests a certificate. Runtime requests use -the discovered authority with the existing identity and project permissions. -Both SSE and WebSocket certificate watches use TLS/TCP. Python does not implement -HTTP/3 or a TURN generation helper; use Go/JavaScript or the documented Engine API -for TURN issuance. Control plane administration and region selectors still require -a token; provision an explicit Engine address for a certificate-only device. - -Tests in `tests/integration/test_engine_mtls.py` use real TLS servers for discovery, -inventory, both watch transports, trust validation and cancellation. Opt-in -real-Engine inventory checks use `RSTREAM_PYTHON_E2E_ENGINE_API=1` with the -existing E2E credential configuration. - -## HTTP CORS +| Configure credentials, contexts and managed discovery | [Configuration](docs/001-configuration.md) | +| Forward a service, accept streams or dial privately | [Tunnels](docs/002-tunnels.md) | +| Integrate Flask, Django or another Python application | [Examples](examples/README.md) | +| Receive lifecycle notifications | [Webhooks](docs/003-webhooks.md) | +| Find advanced options or development checks | [Documentation index](docs/README.md) | +| Contribute to the SDK | [Contributing](CONTRIBUTING.md) and [coding style](CODING_STYLE.md) | -Pass `http_cors=HTTPCORS(allowed_origins=("https://dashboard.example",), allowed_methods=("GET", "PUT"), allowed_headers=("Authorization",), exposed_headers=("ETag",), max_age=600)` to `create_tunnel` or `CreateTunnelOptions`. Import `HTTPCORS` from `rstream`. +## Security and support -CORS requires a published HTTP tunnel. Allowed origins must be explicit HTTP(S) origins without paths or wildcards. Omitted method and request-header lists use GET/HEAD/POST and Authorization/Content-Type; credentials are disabled and max age is zero by default. An absent policy preserves upstream CORS. Engine answers valid preflights before request authentication, but every actual request still requires its usual authorization. A preflight does not grant access to the upstream application. +Use [Security](SECURITY.md) to report vulnerabilities privately. Usage questions and reproducible bugs belong in [GitHub issues](https://github.com/rstreamlabs/rstream-python/issues); remove credentials and customer identifiers before sharing a reproduction. Licensed under [Apache-2.0](LICENSE). diff --git a/SECURITY.md b/SECURITY.md index 07945e8..c42421b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,10 +1,5 @@ -# Security +# Security policy -Report security issues privately through the rstream project maintainers. - -Do not include authentication tokens, webhook signing secrets, private keys, or -customer endpoint URLs in public issues. - -The SDK avoids logging secrets and refuses ambiguous credential reuse when an -explicit engine override is configured. +Use GitHub private vulnerability reporting when it is enabled for this repository, or contact `reports@rstream.io`. Keep vulnerability details out of public issues. +Include the affected component, version, observed impact and a minimal reproduction. Remove authentication tokens, signing secrets, private keys and customer data from shared logs and examples. Reports are handled through coordinated investigation and disclosure. diff --git a/docs/001-configuration.md b/docs/001-configuration.md index 6b78998..b26bccc 100644 --- a/docs/001-configuration.md +++ b/docs/001-configuration.md @@ -91,3 +91,21 @@ The `exec` backend is supported by the Go SDK and CLI. Selecting a context or environment that uses it raises `ERR_RSTREAM_UNSUPPORTED_MTLS_STORAGE` before connecting; this SDK never executes the configured helper. Other contexts in the same configuration file remain usable. + +## Engine HTTP access with certificates + +The existing `list_clients`, `list_tunnels` and `watch` methods support enrolled +file-based mTLS identities. Keep one `Client` in an `async with` block. It discovers +the dedicated project API through anonymous, verified HTTPS and caches the address +in memory, normally for one hour. Concurrent callers share discovery; cancellation +of one waiter does not cancel others, and closing the client cancels pending +lookup work. No YAML field, persistent cache or new login is required. + +Discovery never sends the certificate, a token, cookies or Control plane headers, +refuses redirects and verifies the server even when runtime TLS is marked insecure. +The ordinary Engine hostname never requests a certificate. Runtime requests use +the discovered authority with the existing identity and project permissions. +Both SSE and WebSocket certificate watches use TLS/TCP. Python does not implement +HTTP/3 or a TURN generation helper; use Go/JavaScript or the documented Engine API +for TURN issuance. Control plane administration and region selectors still require +a token; provision an explicit Engine address for a certificate-only device. diff --git a/docs/002-tunnels.md b/docs/002-tunnels.md index edd1858..d581e12 100644 --- a/docs/002-tunnels.md +++ b/docs/002-tunnels.md @@ -5,10 +5,10 @@ JavaScript, and C++ SDKs. ## Serve ASGI directly -Install the optional ASGI extra: +Install the ASGI extra and the framework used by this example: ```bash -pip install "rstreamlabs-rstream[asgi]" +pip install "rstreamlabs-rstream[asgi]" fastapi ``` ```python @@ -50,10 +50,10 @@ HTTP server. ## Serve WSGI directly -Install the optional WSGI extra: +Install the WSGI extra and Flask for this example: ```bash -pip install "rstreamlabs-rstream[wsgi]" +pip install "rstreamlabs-rstream[wsgi]" flask ``` ```python @@ -200,3 +200,21 @@ matching the Go and C++ SDKs. Generating it once and reusing it is what makes it stable; the method returns `None` for engines that are not managed project hosts, in which case the engine allocates an address. The pure derivation is `rstream.generate_stable_domain(engine)`. + +## Connection lifecycle + +The control channel uses a negotiated heartbeat deadline. If that deadline +expires, or the control transport ends unexpectedly, the SDK immediately stops +accepting new streams but lets already accepted streams and active +`forward_to()` relays drain normally. This avoids interrupting an established +application session because of a transient or asymmetric control-path outage. +An explicit tunnel/control close or a protocol violation remains a hard close +and terminates active local forwarding. Applications should use each stream's +EOF/error as its payload-lifecycle signal; `control.done()` only describes the +control plane. + +## HTTP CORS + +Pass `http_cors=HTTPCORS(allowed_origins=("https://dashboard.example",), allowed_methods=("GET", "PUT"), allowed_headers=("Authorization",), exposed_headers=("ETag",), max_age=600)` to `create_tunnel` or `CreateTunnelOptions`. Import `HTTPCORS` from `rstream`. + +CORS requires a published HTTP tunnel. Allowed origins must be explicit HTTP(S) origins without paths or wildcards. Omitted method and request-header lists use GET/HEAD/POST and Authorization/Content-Type; credentials are disabled and max age is zero by default. An absent policy preserves upstream CORS. Engine answers valid preflights before request authentication, but every actual request still requires its usual authorization. A preflight does not grant access to the upstream application. diff --git a/docs/README.md b/docs/README.md index 761dbb2..d061f14 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,10 +1,21 @@ # Python SDK documentation -Read these documents in order: - -1. [Configuration](001-configuration.md) documents SDK configuration. -2. [Tunnels](002-tunnels.md) documents tunnel APIs and behavior. -3. [Webhooks](003-webhooks.md) documents webhook support. -4. [Testing](004-testing.md) describes local and CI validation. -5. [Test matrix](005-test-matrix.md) defines supported runtime combinations. -6. [GitHub setup](006-github-setup.md) documents repository CI configuration. +Start with the [repository overview](../README.md) for installation and a first application. The integration guides below explain the SDK’s behavior and options. + +## Build an integration + +| Guide | Use it to | +| --- | --- | +| [Configuration](001-configuration.md) | Select a context, credentials and an engine. | +| [Tunnels](002-tunnels.md) | Create published services, accept streams and dial private tunnels. | +| [Examples](../examples/README.md) | Start from a runnable integration for your application. | +| [Webhooks](003-webhooks.md) | Verify and process lifecycle notifications. | + +## Develop the SDK + +| Guide | Scope | +| --- | --- | +| [Contributing](../CONTRIBUTING.md) | Local setup, style and change expectations. | +| [Testing](004-testing.md) | Unit, local fixture and opt-in real-engine checks. | +| [Compatibility matrix](005-test-matrix.md) | Runtime and platform coverage. | +| [Repository automation](006-github-setup.md) | Maintainer CI and release configuration. | From f2e2d8ff3419ea029292ec778af4d8f9129d9895 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:04:19 +0100 Subject: [PATCH 03/11] docs: clarify Python certificate trust and current capabilities --- docs/001-configuration.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/001-configuration.md b/docs/001-configuration.md index b26bccc..e141907 100644 --- a/docs/001-configuration.md +++ b/docs/001-configuration.md @@ -42,6 +42,10 @@ deployment access layer. Authentication, forwarding, and hop-by-hop headers are reserved; malformed values and case-insensitive duplicates are rejected before network I/O. +## Trust the engine + +The TLS connection verifies the engine’s certificate and hostname. For a private CA, set `SSL_CERT_FILE` to its PEM bundle before starting Python, or configure the SDK’s `TLSOptions`. The engine address must match the certificate unless an explicit verification name is configured. + ## Config file ```yaml @@ -77,7 +81,7 @@ silently downgraded. Legacy `transport.useQuic` remains readable. ## Unsupported config -The Python SDK v0.1 supports bytestream tunnels. It rejects unsupported +The Python SDK supports bytestream tunnels. It rejects unsupported transport or credential storage settings instead of ignoring them: - QUIC transport. From 465d2a4546d4d8c4ce6b79e18534a8b89ba45b73 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:45:06 +0100 Subject: [PATCH 04/11] docs: describe remaining Python transport and lifecycle work --- CONTRIBUTING.md | 2 ++ TODO | 10 ---------- roadmap/001-datagram-transport.md | 3 +++ roadmap/002-tls-stream-shutdown.md | 3 +++ roadmap/003-reconnection.md | 3 +++ 5 files changed, 11 insertions(+), 10 deletions(-) delete mode 100644 TODO create mode 100644 roadmap/001-datagram-transport.md create mode 100644 roadmap/002-tls-stream-shutdown.md create mode 100644 roadmap/003-reconnection.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f0423c7..61188ad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,8 @@ changes, configuration semantics, or new tunnel capabilities, open an issue or discussion first so the SDK behavior can stay aligned with the Go, JavaScript, Java, and C++ SDKs. +See the [roadmap](roadmap/) for planned transport and lifecycle capabilities. + ## Local setup Use Python 3.10 or newer: diff --git a/TODO b/TODO deleted file mode 100644 index 917669b..0000000 --- a/TODO +++ /dev/null @@ -1,10 +0,0 @@ -# TODO - -- Add datagram tunnel support - The SDK rejects datagram tunnels explicitly today. The engine protocol and the Go implementation define the semantics: datagram channels routed by a 12-byte stream-derived channel ID over QUIC datagrams when the transport supports them, with a length-framed fallback over streams. Bringing this to Python unlocks UDP-like workloads (RTP, aiortc-based WebRTC) from async Python. Requires QUIC runtime transport work first. - -- Investigate APPLICATION_DATA_AFTER_CLOSE_NOTIFY on dialed stream teardown - Long-lived dialed streams occasionally fail with ssl.SSLError "application data after close notify" when the peer closes mid-exchange, surfacing through asyncio's strict TLS shutdown handling. Applications can treat it as a normal disconnect, but the SDK should map it to a clean end-of-stream so consumers do not need SSL-specific handling. Observed against a production engine during the vision sample work (2026-06-11). - -- Reconnect control channels and tunnels automatically - When the engine connection behind a control channel drops, every tunnel created on it closes permanently and the accept loop raises; applications must rebuild the control channel and recreate their tunnels themselves (the vision sample now carries supervisor loops for this). The Go SDK re-establishes sessions transparently; the Python client should reach parity, ideally with the same backoff behavior, so a long-lived worker survives engine restarts with no application code. Same applies to the engine-api watch streams (SSE/WebSocket), which currently end on the first network error (2026-06-12). diff --git a/roadmap/001-datagram-transport.md b/roadmap/001-datagram-transport.md new file mode 100644 index 0000000..ad50f36 --- /dev/null +++ b/roadmap/001-datagram-transport.md @@ -0,0 +1,3 @@ +# Add datagram tunnels + +The Python SDK currently supports bytestream tunnels over TLS and rejects datagrams. Define the supported datagram delivery modes, then implement their runtime paths with cancellation and bounded resource use. Match the Go reference semantics, including stream-framed delivery where supported and QUIC for native datagrams, and verify real client/engine interoperability. diff --git a/roadmap/002-tls-stream-shutdown.md b/roadmap/002-tls-stream-shutdown.md new file mode 100644 index 0000000..b182471 --- /dev/null +++ b/roadmap/002-tls-stream-shutdown.md @@ -0,0 +1,3 @@ +# Handle TLS stream shutdown consistently + +A peer closing during an exchange can surface `APPLICATION_DATA_AFTER_CLOSE_NOTIFY` through asyncio. Reproduce the close sequence and define which outcomes are clean end-of-stream. Preserve truncated-data and protocol errors; do not suppress SSL failures generally. Cover reads, writes, cancellation and repeated close before changing the mapping. diff --git a/roadmap/003-reconnection.md b/roadmap/003-reconnection.md new file mode 100644 index 0000000..b40ceaa --- /dev/null +++ b/roadmap/003-reconnection.md @@ -0,0 +1,3 @@ +# Define automatic reconnection + +Applications currently rebuild control channels and tunnels after an engine connection is lost, and restart interrupted watch streams themselves. Add an explicit retry policy with bounded backoff, cancellation and deterministic shutdown. Preserve tunnel identity and endpoint behavior, and test engine restarts and failed authorization without replaying operations unsafely. From d9241b0e51a2941df79836263d9b4a413190a809 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:06:08 +0100 Subject: [PATCH 05/11] docs: document supported webhook events and fix field table --- docs/003-webhooks.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/003-webhooks.md b/docs/003-webhooks.md index 428a5c6..ff3a89d 100644 --- a/docs/003-webhooks.md +++ b/docs/003-webhooks.md @@ -58,16 +58,19 @@ single request may contain more than one `v1` signature. | --- | --- | --- | | `id` | `str` | Event identifier for idempotency. | | `type` | `str` | Deliverable event type. | -| `created_at` | `str | None` | Event creation timestamp, when available. | -| `user_id` | `str | None` | User associated with the event, when available. | -| `workspace_id` | `str | None` | Workspace associated with the event, when available. | -| `project_id` | `str | None` | Project associated with the event, when available. | -| `cluster_id` | `str | None` | Cluster associated with the event, when available. | +| `created_at` | `str \| None` | Event creation timestamp, when available. | +| `user_id` | `str \| None` | User associated with the event, when available. | +| `workspace_id` | `str \| None` | Workspace associated with the event, when available. | +| `project_id` | `str \| None` | Project associated with the event, when available. | +| `cluster_id` | `str \| None` | Cluster associated with the event, when available. | | `object` | `Mapping[str, object]` | Event-specific resource snapshot. | | `raw` | `Mapping[str, object]` | Complete decoded payload. | -The launch catalog contains `client.created`, `client.deleted`, -`tunnel.created`, and `tunnel.deleted`. +The Python parser accepts `client.created`, `client.deleted`, `tunnel.created` +and `tunnel.deleted`. Select those types in the webhook destination's event +filters. It rejects WebTTY events even when their signatures are valid; use a +receiver that supports the [service event catalog](https://rstream.io/docs/integrations/webhooks#receiver-compatibility) +when subscribing to those events. ## Framework examples From 9d744034806dfd5e3fc9aae280d5afb3e2dcab6d Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:23:52 +0100 Subject: [PATCH 06/11] docs: link CLI installation before Python setup --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 389bd68..cc781ca 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Install the SDK’s ASGI adapter and FastAPI: pip install "rstreamlabs-rstream[asgi]" fastapi ``` -The SDK reads the [configuration](docs/001-configuration.md) selected with the rstream CLI. Set up a project context with `rstream login` and `rstream project use my-project-endpoint`, replacing the endpoint with your own. Servers and devices can use project-scoped credentials or certificate files instead. +The SDK reads the [configuration](docs/001-configuration.md) selected with the [rstream CLI](https://rstream.io/docs/getting-started/installation). Install the CLI, then select a project with `rstream login` and `rstream project use my-project-endpoint`, replacing the endpoint with your own. Servers and devices can use project-scoped credentials or certificate files instead. ```python import asyncio From 90348b36b038b0d861cf88d1c085436d6e73272a Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:01:54 +0100 Subject: [PATCH 07/11] docs: align repository guidance and agent entry points --- AGENTS.md | 11 +++++++++++ CLAUDE.md | 1 + 2 files changed, 12 insertions(+) create mode 100644 AGENTS.md create mode 120000 CLAUDE.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7def33c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,11 @@ +# Repository guidance + +## Shared conventions + +Follow the existing architecture, naming and coding style. Preserve public contracts, authentication, certificate verification and project policy. Keep changes in the component that owns the behavior. + +Update user documentation and examples when behavior changes. Run the relevant checks; place regression tests with the owning component. Keep secrets, execution logs, investigation notes and standalone upstream reproductions outside the repository. + +## Repository-specific guidance + +Follow `CODING_STYLE.md` and `CONTRIBUTING.md`. Keep the SDK framework-neutral and typed, with explicit lifecycle ownership. Preserve Python runtime support, optional dependency boundaries and ASGI/WSGI semantics. Reject unsupported capabilities explicitly; maintain the documented webhook parser limits. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file From 0cd7ac8b688c8347805627f08cbf41864d6feb7e Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:55:50 +0100 Subject: [PATCH 08/11] docs: clarify Python setup and verified engine tests --- CONTRIBUTING.md | 10 +++++++--- README.md | 16 ++++++++++++---- docs/004-testing.md | 34 ++++++++++++++++++---------------- examples/README.md | 16 ++++++++++++++-- 4 files changed, 51 insertions(+), 25 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 61188ad..280d3e0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,14 +13,18 @@ See the [roadmap](roadmap/) for planned transport and lifecycle capabilities. ## Local setup -Use Python 3.10 or newer: +Use Python 3.10 or newer with `venv` and pip, Git, and network access for uncached dependencies. Some Linux distributions package `venv` separately. Work from a checkout, not an installed site-packages directory: -```bash +```sh +git clone https://github.com/rstreamlabs/rstream-python.git +cd rstream-python python -m venv .venv . .venv/bin/activate -pip install -e ".[dev]" +python -m pip install -e ".[dev]" ``` +On Windows, activate the environment with `.venv\Scripts\Activate.ps1` instead of the POSIX activation command. Editable installation makes imports use `src/rstream` from this checkout. Local unit and fake-engine tests do not need a rstream account; real-engine checks have separate explicit configuration in [Testing](docs/004-testing.md). + ## Development checks Run the full local suite before opening a pull request: diff --git a/README.md b/README.md index cc781ca..bca369f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # rstream Python SDK -Connect Python applications to rstream without running a separate agent process. The SDK creates tunnels, dials private services and verifies webhook deliveries. Its async API fits `asyncio` applications, with adapters that serve ASGI and WSGI applications directly over accepted tunnel streams. +rstream connects services and devices through outbound connections, so they can be reached without opening inbound ports on their hosts. This SDK embeds that connection in a Python application, without a separate agent process. + +Its async API fits `asyncio` services and workers. ASGI and WSGI adapters serve an existing web application directly over accepted tunnel streams; the same SDK can dial private services and verify webhook deliveries. The package is named `rstreamlabs-rstream`; import it as `rstream`. Python 3.10 or newer is required. @@ -16,14 +18,20 @@ An rstream agent connects outbound to the edge, which routes traffic to the appl | Service discovery | Query inventory and watch lifecycle events with optional HTTP dependencies. | | Webhooks | Verify signatures and parse deliveries in your framework. | -The runtime connects to the engine over TLS. Datagram tunnels, QUIC runtime transport and HTTP/3 tunnel creation are outside this SDK’s current scope. For broader protocol support, see the [Go reference SDK](https://github.com/rstreamlabs/rstream-go). +The runtime connects to the engine over TLS. Datagram tunnels, QUIC runtime transport and HTTP/3 tunnel creation are outside this SDK’s current scope. The [SDK guide](https://rstream.io/docs/sdks) compares the available language and protocol choices. ## Publish a FastAPI application -Install the SDK’s ASGI adapter and FastAPI: +Use a Python virtual environment for the application: + +```sh +python -m venv .venv +``` + +Activate it with `. .venv/bin/activate` on a POSIX shell or `.venv\Scripts\Activate.ps1` in Windows PowerShell. Then install the SDK's ASGI adapter and FastAPI: ```sh -pip install "rstreamlabs-rstream[asgi]" fastapi +python -m pip install "rstreamlabs-rstream[asgi]" fastapi ``` The SDK reads the [configuration](docs/001-configuration.md) selected with the [rstream CLI](https://rstream.io/docs/getting-started/installation). Install the CLI, then select a project with `rstream login` and `rstream project use my-project-endpoint`, replacing the endpoint with your own. Servers and devices can use project-scoped credentials or certificate files instead. diff --git a/docs/004-testing.md b/docs/004-testing.md index e5d15f0..eafb08d 100644 --- a/docs/004-testing.md +++ b/docs/004-testing.md @@ -31,7 +31,7 @@ It covers: | Suite | Coverage | | --- | --- | | `tests/unit` | Config resolution, protocol framing, streams, tunnel objects, API helpers, direct ASGI and WSGI helpers, webhook signatures. | -| `tests/integration` | TLS fake engine, control-channel lifecycle, tunnel creation and close, stream handshakes, zero-RTT, proxy delivery, timeout and retry behavior. | +| `tests/integration` | TLS fake engine, control-channel lifecycle, tunnel creation and close, stream handshakes, the SDK `zero_rtt` option, proxy delivery, timeout and retry behavior. | | `tests/examples` | Syntax compilation for every example plus FastAPI, Flask, and Django receivers with valid and invalid webhook signatures. | ## Real-engine e2e @@ -43,7 +43,7 @@ RSTREAM_PYTHON_E2E=1 pytest tests/e2e ``` The private-tunnel e2e matrix creates a tunnel, dials it by name and ID, runs -zero-RTT both enabled and disabled, exercises concurrent dials, and validates a +the SDK stream-handshake `zero_rtt` option both enabled and disabled, exercises concurrent dials, and validates a direct WSGI handler through a private tunnel. Published HTTP tunnel checks are opt-in because they require the engine to serve @@ -68,30 +68,29 @@ pytest tests/e2e Set `RSTREAM_PYTHON_E2E_PUBLISHED_CONNECT_HOST` when the hostname returned by a local engine is not directly resolvable from the test process. -When bypassing the shared rstream config file, pass explicit engine settings: +When bypassing the shared rstream config file, pass explicit engine settings. +For a private CA, keep certificate verification enabled: ```bash +RSTREAM_PYTHON_E2E=1 \ RSTREAM_PYTHON_E2E_ENGINE="c.localhost.rstream.io:9443" \ RSTREAM_PYTHON_E2E_TOKEN="$RSTREAM_AUTHENTICATION_TOKEN" \ -RSTREAM_PYTHON_E2E_TLS_INSECURE=1 \ +RSTREAM_PYTHON_E2E_CA_FILE="/path/to/local-ca.pem" \ pytest tests/e2e ``` -If the local engine uses a private CA, prefer -`RSTREAM_PYTHON_E2E_CA_FILE="/path/to/local-ca.pem"` instead of -`RSTREAM_PYTHON_E2E_TLS_INSECURE=1`. `RSTREAM_PYTHON_E2E_SERVER_NAME` is only -needed when the certificate name intentionally differs from the engine host. - -## Local EE engine +Set `RSTREAM_PYTHON_E2E_SERVER_NAME` only when the certificate name intentionally +differs from the engine host. `RSTREAM_PYTHON_E2E_TLS_INSECURE=1` disables +certificate verification and is reserved for isolated throwaway fixtures +without a trusted certificate. -The engine repository documents the full local setup in its Enterprise Edition -runtime README: +The `zero_rtt` option tested here controls the rstream stream handshake; it does +not enable TLS 1.3 early data. -```text -cmd/rstream-engine-ee/README.md -``` +## Local self-hosted engine -Start the EE engine, select the test context, then run: +Follow the [self-hosted engine guide](https://rstream.io/docs/tunnels/self-hosted) +to configure a local engine, select its CLI context and run: ```bash RSTREAM_CONTEXT=tests \ @@ -100,3 +99,6 @@ RSTREAM_PYTHON_E2E_PUBLISHED=1 \ RSTREAM_PYTHON_E2E_PUBLISHED_TCP=1 \ pytest tests/e2e ``` + +Enable published checks only when the local engine supports them and its +forwarding addresses are reachable from the test process. diff --git a/examples/README.md b/examples/README.md index 4d50b37..3888f87 100644 --- a/examples/README.md +++ b/examples/README.md @@ -16,8 +16,20 @@ the other rstream SDKs. | [flask-webhook-receiver](flask-webhook-receiver) | Verify webhook deliveries inside a Flask route. | | [django-webhook-receiver](django-webhook-receiver) | Verify webhook deliveries inside a Django view. | -Install example dependencies from the repository root: +Use Python 3.10 or newer and activate a virtual environment as described in [Contributing](../CONTRIBUTING.md). Install example dependencies from the repository root: ```bash -pip install -e ".[examples]" +python -m pip install -e ".[examples]" ``` + +## Run a first service + +[Install the CLI](https://rstream.io/docs/getting-started/installation), then run `rstream login` and `rstream project use my-project-endpoint` with your project endpoint. The first HTTP example needs permission to create a published tunnel. + +From the repository root: + +```sh +python examples/fastapi-tunnel/main.py +``` + +Open the printed forwarding address while the process is running, then stop it with an interrupt. The ASGI adapter runs the app directly over tunnel streams; it does not bind a local HTTP port. The [FastAPI guide](fastapi-tunnel) explains that example; choose a webhook receiver when the task is verifying notifications rather than serving through a tunnel. From c5a9704ca33f71ef0a932f01450c7b8b39712c14 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:13:18 +0100 Subject: [PATCH 09/11] docs: keep public references independent of private repositories --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 7def33c..29ca5fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Follow the existing architecture, naming and coding style. Preserve public contracts, authentication, certificate verification and project policy. Keep changes in the component that owns the behavior. -Update user documentation and examples when behavior changes. Run the relevant checks; place regression tests with the owning component. Keep secrets, execution logs, investigation notes and standalone upstream reproductions outside the repository. +Update user documentation and examples when behavior changes. Run the relevant checks; place regression tests with the owning component. Keep secrets, execution logs, investigation notes and standalone upstream reproductions outside the repository. Do not link to private repositories from public source, documentation or PR descriptions. ## Repository-specific guidance From 928ed33bb513ad00f03e4416f7268dec7744c9d9 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:43:25 +0100 Subject: [PATCH 10/11] Clarify Python integration options and own ASGI example lifespans --- README.md | 3 +- docs/001-configuration.md | 32 ++++- docs/002-tunnels.md | 83 ++++++++++++- docs/003-webhooks.md | 44 +++++++ docs/005-test-matrix.md | 5 + docs/006-github-setup.md | 139 +++++++--------------- examples/django-tunnel/README.md | 2 +- examples/fastapi-tunnel/main.py | 6 +- examples/flask-tunnel/README.md | 2 +- examples/webhook-receiver/README.md | 6 +- tests/examples/test_framework_examples.py | 71 +++++++++++ 11 files changed, 285 insertions(+), 108 deletions(-) diff --git a/README.md b/README.md index bca369f..823aff8 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ async def root() -> dict[str, str]: async def main() -> None: async with ( + app.router.lifespan_context(app), rstream.Client.from_env() as client, await client.connect() as control, ): @@ -68,7 +69,7 @@ async def main() -> None: asyncio.run(main()) ``` -Save this as `main.py` and run `python main.py`. Open the printed forwarding address to reach the application. The adapter handles HTTP in-process, so no local listening port is needed. The [runnable FastAPI example](examples/fastapi-tunnel) includes interrupt handling. +Save this as `main.py` and run `python main.py`. Open the printed forwarding address to reach the application. The adapter handles HTTP in-process, so no local listening port is needed. The [runnable FastAPI example](examples/fastapi-tunnel) includes interrupt handling and owns FastAPI startup/shutdown explicitly. The direct adapter is HTTP-only; see its [lifecycle and scope limits](docs/002-tunnels.md#own-the-application-lifecycle) before moving an existing application. ## Documentation diff --git a/docs/001-configuration.md b/docs/001-configuration.md index e141907..87171cd 100644 --- a/docs/001-configuration.md +++ b/docs/001-configuration.md @@ -67,8 +67,7 @@ If an explicit engine override is provided, stored tokens or stored mTLS credentials from another context are refused. Pass an explicit token, explicit mTLS files, or `no_token=True` for local unauthenticated engines. -The shared transport selector is available through `ClientOptions.tunnel_transport` -and YAML: +Select the shared transport through the environment variables above or YAML: ```yaml transport: @@ -113,3 +112,32 @@ Both SSE and WebSocket certificate watches use TLS/TCP. Python does not implemen HTTP/3 or a TURN generation helper; use Go/JavaScript or the documented Engine API for TURN issuance. Control plane administration and region selectors still require a token; provision an explicit Engine address for a certificate-only device. + +## Client and TLS options + +`Client(...)` and `Client.from_env(...)` accept the same keyword options. The +constructor does not connect; entering its async context gives the application a +single owner that closes its control channels and HTTP discovery work. + +| Keyword | Default | Meaning | +| --- | --- | --- | +| `config_path`, `context`, `read_config_file` | shared path/default context; `True` | Select or disable shared YAML loading. Disabling YAML does not disable explicit/environment validation. | +| `engine`, `project_endpoint`, `api_url`, `region` | resolved context | Direct Engine authority or managed project resolution; region requires managed metadata. | +| `token`, `no_token`, `require_token` | resolved token; `None`; `False` | Explicit identity, suppress stored tokens, or require an authenticated identity (token or certificate). `no_token=True` is for a deliberately unauthenticated local Engine. | +| `control_plane_headers` | empty | Additional deployment-access headers, subject to reserved-header validation. | +| `tls` | verified system trust | `TLSOptions` for the native Engine connection and supported certificate API access. | +| `connect_timeout`, `operation_timeout` | 15 / 30 seconds | Positive connection and protocol-operation budgets, not a complete application request deadline. | +| `heartbeat`, `heartbeat_interval` | `True` / 5 seconds | Control admission liveness; enabled intervals are 1–300 seconds. Not a payload session lease. | +| `zero_rtt` | `True` | Optimizes the rstream stream handshake; does not enable TLS early data. | + +`TLSOptions(ca_file=..., server_name=...)` adds a private CA and an intentional +verification-name override. `cert_file`/`key_file` select an mTLS pair; inline +`certificate`/`key` are also supported. `insecure_skip_verify` defaults to false +and belongs only to isolated test fixtures. Never copy a personal CLI context to +a deployed device; inject its own scoped token or enrolled certificate files. + +The exported low-level `ClientOptions` resolution model also represents +`tunnel_transport`; the `Client` constructor currently selects transport through +environment/YAML. Python's supported result remains TLS. + +For the complete creation surface and adapter limits, see [Tunnels](002-tunnels.md). diff --git a/docs/002-tunnels.md b/docs/002-tunnels.md index d581e12..de52b6e 100644 --- a/docs/002-tunnels.md +++ b/docs/002-tunnels.md @@ -28,6 +28,7 @@ async def root() -> dict[str, str]: async def main() -> None: async with ( + app.router.lifespan_context(app), rstream.Client.from_env() as client, await client.connect() as control, ): @@ -48,6 +49,31 @@ application in-process. Request bodies are streamed through the ASGI `receive` callable and bounded by default request limits. It does not start a loopback HTTP server. +### Own the application lifecycle + +The helper serves **HTTP/1.1 requests only**. It does not dispatch ASGI `lifespan` +or WebSocket scopes. In the FastAPI example, the outer +`app.router.lifespan_context(app)` starts the application's lifespan before +connecting and stops it after tunnel/client cleanup, including setup errors and +cancellation. Put process resources on `app.state`; the adapter does not populate +ASGI lifespan `scope["state"]` from a yielded state mapping. Nested subapplication +lifespans remain the application's responsibility. + +For an application that needs WebSockets, another ASGI server feature, or a +framework with a different lifecycle, keep its normal server and use +[`forward_to()`](#managed-local-forwarding). For example, run Uvicorn on loopback +in one terminal and the forward-local-port example in another. The full server +then owns ASGI startup, shutdown and WebSocket handling; the SDK owns the tunnel. + +| Direct adapter option | Default | Use it for | +| --- | --- | --- | +| `max_header_size` | 65536 bytes | Bound an incomplete request-header block. | +| `max_body_size` | 16777216 bytes | Bound request bodies; WSGI buffers its input. | +| `read_timeout` | 30 seconds | Bound each request read; `None` disables this local read timeout. | + +These are arguments to `rstream.asgi.serve` or `rstream.wsgi.serve`, separate from +client connection/operation timeouts and from framework policy. + ## Serve WSGI directly Install the WSGI extra and Flask for this example: @@ -163,13 +189,17 @@ the same client. This turns the tunnel registry into a service registry: tag tunnels at creation time, discover them by label, and react to lifecycle events in real time. +Install `rstreamlabs-rstream[api]` for this inventory/SSE path; use the +`realtime` extra when selecting WebSocket watches. + ```python async with rstream.Client.from_env() as client: filters = rstream.TunnelFilters(labels={"role": "inference"}) workers = await client.list_tunnels(filters=filters) - async for event in client.watch(tunnels=filters): - if event.type in ("tunnel.created", "tunnel.deleted"): - ... # refresh the worker set + async with client.watch(tunnels=filters) as events: + async for event in events: + if event.type in ("tunnel.created", "tunnel.deleted"): + ... # refresh the worker set ``` `list_tunnels` returns `TunnelInventory` entries combining the tunnel @@ -213,8 +243,55 @@ and terminates active local forwarding. Applications should use each stream's EOF/error as its payload-lifecycle signal; `control.done()` only describes the control plane. +The low-level client does not recreate control channels or tunnels automatically. +When a serving operation ends, the application decides whether to stop or create a +new client/control/tunnel with bounded backoff. Keep that supervision outside the +request handler. Preserve a requested hostname across attempts when a consumer +needs the same public address, and do not replay application requests on recovery. +Explicit close/cancellation must stop the supervisor as well as its current +resources. The [vision application](https://github.com/rstreamlabs/rstream-examples/tree/main/python-vision-inference) +shows an application-owned reconnect loop. + +## Creation options + +`control.create_tunnel` accepts keyword arguments or `CreateTunnelOptions`. +Unset optional fields are sent as unspecified and the Engine validates their +combination and project permissions. Set `publish` explicitly in applications. +Do not treat inventory-only `id`, `host` or `creation_date` as creation inputs. + +| Options | Purpose and boundary | +| --- | --- | +| `name`, `labels` | Dialing/discovery identity and application metadata. A name is not a stable public hostname. | +| `publish`, `type`, `protocol` | Public entrypoint or private dial; this SDK implements bytestreams. Protocol availability still depends on the Engine/project. | +| `hostname`, `port` | Request a stable domain for eligible published protocols, or a previously reserved TCP port. Neither reserves a domain/port by itself. | +| `http_version`, `upstream_tls` | HTTP upstream mode. Use `http/1.1` for these direct adapters; a local h2c service can use forwarding. Explicit HTTP version and upstream TLS cannot conflict. HTTP/3 is rejected. | +| `token_auth`, `rstream_auth`, `challenge_mode` | Published HTTP request policy at the edge; independent of agent authentication. `auth=TunnelAuth(...)` is the grouped spelling. | +| `http_cors` | Explicit published HTTP browser-origin policy; see below. | +| `tls_mode`, `tls_min_version`, `tls_alpns`, `tls_ciphers`, `mtls_auth` | Published TLS termination/passthrough and downstream certificate policy. Passthrough leaves TLS policy to the application. | +| `trusted_ips`, `geo_ip` | Published source-address/country restrictions, enforced by the Engine. | +| `allow_cross_region_routing` | Override the project's private-routing choice where supported; not a region selector for the client. | + +Private tunnels reject public exposure/authentication options. Private protocol +inspection options are supported where the Engine accepts them; an opaque private +HTTP byte stream does not require a protocol declaration. + ## HTTP CORS Pass `http_cors=HTTPCORS(allowed_origins=("https://dashboard.example",), allowed_methods=("GET", "PUT"), allowed_headers=("Authorization",), exposed_headers=("ETag",), max_age=600)` to `create_tunnel` or `CreateTunnelOptions`. Import `HTTPCORS` from `rstream`. CORS requires a published HTTP tunnel. Allowed origins must be explicit HTTP(S) origins without paths or wildcards. Omitted method and request-header lists use GET/HEAD/POST and Authorization/Content-Type; credentials are disabled and max age is zero by default. An absent policy preserves upstream CORS. Engine answers valid preflights before request authentication, but every actual request still requires its usual authorization. A preflight does not grant access to the upstream application. + +## Find the next API + +| Surface | Purpose and owner | +| --- | --- | +| `Client.connect`, `dial` / `dial_bytestream` | Open a control or private stream; use async contexts and stream EOF/errors. | +| `ControlChannel.create_tunnel`, `close`, `done` | Admit tunnels and observe control liveness. `done` does not establish payload completion. | +| `BytestreamTunnel.accept`, async iteration, `forward_to`, `close` | Own accepted streams, or have the SDK relay them to a local TCP service. | +| `Client.list_clients`, `list_tunnels`, `watch` | Optional Engine HTTP inventory and event stream. Keep watches in `async with` or call `aclose` when leaving early. | +| `Client.generate_stable_hostname` | Derive a managed hostname once and retain it across supervised reconnects. | +| `rstream.verify_event`, signing/header helpers | Verify receiver bytes or produce synthetic local webhook deliveries; not Control plane administration. | + +Exact signatures are in [client.py](../src/rstream/client.py), +[tunnel.py](../src/rstream/tunnel.py), and [types.py](../src/rstream/types.py). +The core SDK remains framework-neutral; optional extras add integration protocols. diff --git a/docs/003-webhooks.md b/docs/003-webhooks.md index ff3a89d..b890895 100644 --- a/docs/003-webhooks.md +++ b/docs/003-webhooks.md @@ -82,3 +82,47 @@ includes runnable receivers for the common cases: | FastAPI | [examples/webhook-receiver](../examples/webhook-receiver) | | Flask | [examples/flask-webhook-receiver](../examples/flask-webhook-receiver) | | Django | [examples/django-webhook-receiver](../examples/django-webhook-receiver) | + +## Try a local delivery + +Start the FastAPI receiver from `examples/webhook-receiver` using its README. +In another terminal, use a configured CLI context and the same signing secret: + +```sh +rstream events --webhook --webhook-secret "$RSTREAM_WEBHOOK_SECRET" \ + --events tunnel.created,tunnel.deleted \ + --forward-to http://127.0.0.1:8000/webhooks/rstream +``` + +Set `RSTREAM_WEBHOOK_SECRET` in both terminals before starting either process. +Creating or closing a disposable tunnel in that project produces a verified +request; the receiver prints its event ID and returns 200. A malformed signature +returns 400. The CLI forwards live events locally; it does not configure durable +Control plane destinations or retain retries after exit. A hosted destination +cannot reach a loopback URL directly: publish a receiver deliberately and use +its HTTPS address for that separate workflow. + +Return 2xx after processing or durable storage, and use `event.id` for idempotency. + +For a deterministic first check without a configured Engine, run the receiver with +`RSTREAM_WEBHOOK_SECRET=whsec_local_example`. From the same example directory in +another activated terminal, send one synthetic event: + +```sh +RSTREAM_WEBHOOK_SECRET=whsec_local_example python - <<'PYTHON' +import os +from urllib.request import Request, urlopen +import rstream + +body = b'{"id":"evt_local_example","type":"tunnel.created","object":{"id":"tun_local"}}' +request = Request("http://127.0.0.1:8000/webhooks/rstream", data=body, headers={ + "content-type": "application/json", + "rstream-signature": rstream.sign_payload(body, os.environ["RSTREAM_WEBHOOK_SECRET"]), +}) +with urlopen(request, timeout=5) as response: + print(response.status, response.read().decode()) +PYTHON +``` + +The expected result is `200 {"received":true}`. This fixture secret is deliberately +public and belongs only to the local example, never to a real webhook destination. diff --git a/docs/005-test-matrix.md b/docs/005-test-matrix.md index b8f6163..459f9a8 100644 --- a/docs/005-test-matrix.md +++ b/docs/005-test-matrix.md @@ -1,5 +1,10 @@ # Test matrix +The configured CI matrix covers Python 3.10–3.15 on Linux, macOS and Windows; the package minimum is +Python 3.10. Framework extras may select different dependency versions per Python +release. This is a tested CI matrix, not a promise about every Python/platform +combination. See `.github/workflows/ci.yml` and `pyproject.toml`. + This matrix tracks the behavior that must stay covered before publishing the Python SDK. diff --git a/docs/006-github-setup.md b/docs/006-github-setup.md index d2b299b..e0db55c 100644 --- a/docs/006-github-setup.md +++ b/docs/006-github-setup.md @@ -1,108 +1,53 @@ -# GitHub setup +# Configure repository CI and releases -This repository is intended to be published as `rstreamlabs/rstream-python`. +This is a maintainer guide for `rstreamlabs/rstream-python`, not an application +installation step. Applications use the published `rstreamlabs-rstream` package; +contributors start with [Contributing](../CONTRIBUTING.md). -## Create the repository +## CI contract -From the repository root: +The configured CI matrix uses Python 3.10–3.15 on Linux, macOS and Windows. It +runs Ruff, strict Mypy and the local pytest suite without a rstream account. +A separate Python 3.13 job builds distributions and runs +`scripts/verify_distribution.py`. Real-engine checks remain opt-in as described +in [Testing](004-testing.md). -```bash -gh repo create rstreamlabs/rstream-python \ - --private \ - --source . \ - --remote origin \ - --push -``` +Protect `main` with reviewed pull requests and required CI, and restrict force +push/deletion. Normal source validation does not authorize a release. -Keep the repository private until the first maintainer review is complete. After -validation, make it public: +## Release configuration -```bash -gh repo edit rstreamlabs/rstream-python --visibility public -``` - -Recommended repository settings: - -```bash -gh repo edit rstreamlabs/rstream-python \ - --enable-issues=true \ - --enable-projects=false \ - --enable-wiki=false -``` - -## Required CI settings - -The normal CI workflow does not require secrets. It runs on pushes to `main` and -on pull requests: - -- Ruff lint and format check. -- Mypy strict type check. -- Pytest. -- Source distribution and wheel build. -- Linux, macOS, and Windows. -- Python 3.10, 3.11, 3.12, and 3.13. - -Release automation requires: - -| Kind | Name | Purpose | -| --- | --- | --- | -| Repository variable | `CI_ALLOWED_ACTOR` | GitHub login allowed to run release-please on `main`. | -| Repository secret | `RELEASE_PLEASE_TOKEN` | Token used by release-please to create and update release PRs. | - -`release-please-config.json` and `.release-please-manifest.json` are part of -the repository contract. Keep both files versioned so release-please can update -`pyproject.toml`, `src/rstream/version.py`, `CHANGELOG.md`, tags, and GitHub -releases from the same manifest state. - -`RELEASE_PLEASE_TOKEN` should have the minimum permissions needed to write -contents and pull requests in this repository. The workflow is guarded by -`CI_ALLOWED_ACTOR` so regular contributors cannot trigger release automation. - -## Branch protection - -Before making the repository public, protect `main` with: - -- pull request required before merge; -- CI required; -- no force pushes; -- no branch deletion; -- linear history if that remains consistent with the rest of the rstream SDK - repositories. - -## PyPI publishing - -The package distribution name is `rstreamlabs-rstream`. The import package -inside Python remains `rstream`, so application code uses `import rstream`. - -Prefer PyPI trusted publishing over a long-lived API token. Configure the PyPI -project with: - -| Field | Value | +| Setting | Purpose | | --- | --- | -| Owner | `rstreamlabs` | -| Repository | `rstream-python` | -| Project name | `rstreamlabs-rstream` | -| Workflow | the future publish workflow filename | -| Environment | `pypi`, if an environment gate is used | - -This repository currently includes CI and release-please. Add the PyPI publish -workflow only when the first public package release is approved. +| Repository variable `CI_ALLOWED_ACTOR` | Actor allowed to run release-please, candidate and promotion jobs. | +| Repository secret `RELEASE_PLEASE_TOKEN` | Minimum required contents/PR authority for release-please. | +| GitHub environment `pypi` | Protect stable promotion with the repository's maintainer approval policy. | +| PyPI trusted publisher | Owner `rstreamlabs`, repository `rstream-python`, workflow `publish.yml`, environment `pypi`, project `rstreamlabs-rstream`. | -If trusted publishing is not available, use a scoped `PYPI_API_TOKEN` secret, but -prefer keeping that path disabled until release policy is decided. +The existing promotion workflow requests `id-token: write` and uses PyPI trusted +publishing; it does not need a long-lived PyPI API token. Configure the publisher +and protected environment before attempting promotion. Do not replace this with +an ambient personal token as a quick-start workaround. -## First push checklist +Keep `release-please-config.json` and `.release-please-manifest.json` versioned. +Release-please coordinates the Python package version, runtime version file, +changelog, tag and draft GitHub release. -Before the first push: +## Candidate and stable promotion -```bash -ruff check . -ruff format --check . -mypy -pytest -python -m build -``` - -Also run at least one real-engine e2e command from [TESTING.md](004-testing.md) -against a local or managed engine and record the command in the release notes or -PR description. +| Workflow | Input and result | +| --- | --- | +| `release-please.yml` | An allowed push on `main` prepares the release PR/draft and tag. | +| `release-candidate.yml` | A `vX.Y.Z` tag verifies the version, builds wheel/sdist, validates them and retains a checksummed candidate for 90 days. It does not publish PyPI. | +| `publish.yml` | Explicit `release_tag` dispatch selects the successful candidate with the matching tag commit, checks integrity and PyPI state, publishes those retained bytes and then the GitHub release. It never rebuilds the candidate. | + +Promotion requires the GitHub release to remain a draft and refuses an older +release after a newer stable version. Existing PyPI files must match the retained +candidate; retries use that same artifact, not a new build with the same version. +Review the workflow and verification scripts when changing this contract. + +Before proposing a release, run the contributor checks, distribution verification +and relevant explicit real-engine matrix; retain the commands, environment and +results privately. An unrun opt-in test is not a passed qualification. Candidate +creation, publishing and repository-visibility changes are separate maintainer +operations and are not side effects of an ordinary build. diff --git a/examples/django-tunnel/README.md b/examples/django-tunnel/README.md index 2e0abad..450aef1 100644 --- a/examples/django-tunnel/README.md +++ b/examples/django-tunnel/README.md @@ -5,7 +5,7 @@ binding the app to a local port. ```bash pip install -e "../../[wsgi,examples]" -RSTREAM_CONTEXT=tests python main.py +python main.py ``` The example opens a published HTTP tunnel, then passes each accepted stream to diff --git a/examples/fastapi-tunnel/main.py b/examples/fastapi-tunnel/main.py index c91dcae..50ad8f6 100644 --- a/examples/fastapi-tunnel/main.py +++ b/examples/fastapi-tunnel/main.py @@ -16,7 +16,11 @@ async def root() -> dict[str, str]: async def main() -> None: - async with rstream.Client.from_env() as client, await client.connect() as control: + async with ( + app.router.lifespan_context(app), + rstream.Client.from_env() as client, + await client.connect() as control, + ): # Client.from_env reads the same config file and environment variables # used by the rstream CLI and the other SDKs. tunnel = await control.create_tunnel( diff --git a/examples/flask-tunnel/README.md b/examples/flask-tunnel/README.md index a8cdf4d..cabe065 100644 --- a/examples/flask-tunnel/README.md +++ b/examples/flask-tunnel/README.md @@ -5,7 +5,7 @@ binding the app to a local port. ```bash pip install -e "../../[wsgi,examples]" -RSTREAM_CONTEXT=tests python main.py +python main.py ``` The example opens a published HTTP tunnel, then passes each accepted stream to diff --git a/examples/webhook-receiver/README.md b/examples/webhook-receiver/README.md index 11206f7..c1601fa 100644 --- a/examples/webhook-receiver/README.md +++ b/examples/webhook-receiver/README.md @@ -3,7 +3,9 @@ FastAPI receiver that verifies rstream webhook signatures. ```bash -pip install -e "../../[asgi,examples]" +python -m pip install -e "../../[asgi,examples]" uvicorn export RSTREAM_WEBHOOK_SECRET="whsec_..." -uvicorn main:app --reload +python -m uvicorn main:app --host 127.0.0.1 --port 8000 ``` + +Run these commands from this example directory in an activated virtual environment. The receiver listens at `http://127.0.0.1:8000/webhooks/rstream`. Use the [local signed delivery walkthrough](../../docs/003-webhooks.md#try-a-local-delivery) to see a valid delivery return 200 and an invalid signature return 400. diff --git a/tests/examples/test_framework_examples.py b/tests/examples/test_framework_examples.py index 4943c75..1f6af93 100644 --- a/tests/examples/test_framework_examples.py +++ b/tests/examples/test_framework_examples.py @@ -152,3 +152,74 @@ def load_example_module(example: str) -> ModuleType: sys.modules[module_name] = module spec.loader.exec_module(module) return module + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["none", "connect", "serve", "cancel"]) +async def test_fastapi_entrypoint_owns_lifespan_on_success_and_failure( + monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + import asyncio + from collections.abc import AsyncIterator + from contextlib import asynccontextmanager + from unittest.mock import AsyncMock, MagicMock + + from fastapi import FastAPI + + module = load_example_module("fastapi_tunnel") + events: list[str] = [] + + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncIterator[None]: + app.state.ready = True + events.append("startup") + try: + yield + finally: + app.state.ready = False + events.append("shutdown") + + application = FastAPI(lifespan=lifespan) + monkeypatch.setattr(module, "app", application) + tunnel = MagicMock(forwarding_address="https://example.test") + control = MagicMock() + control.__aenter__ = AsyncMock(return_value=control) + control.__aexit__ = AsyncMock(return_value=False) + control.create_tunnel = AsyncMock(return_value=tunnel) + client = MagicMock() + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=False) + + async def connect() -> object: + assert application.state.ready + events.append("connect") + if failure == "connect": + raise RuntimeError("connect failed") + return control + + async def serve(app: FastAPI, accepted: object) -> None: + assert app is application + assert accepted is tunnel + assert app.state.ready + events.append("serve") + if failure == "serve": + raise RuntimeError("serve failed") + if failure == "cancel": + raise asyncio.CancelledError + + client.connect = connect + monkeypatch.setattr(rstream.Client, "from_env", lambda: client) + monkeypatch.setattr(rstream.asgi, "serve", serve) + expected = asyncio.CancelledError if failure == "cancel" else RuntimeError + if failure == "none": + await module.main() + else: + with pytest.raises(expected): + await module.main() + assert events == ( + ["startup", "connect", "shutdown"] + if failure == "connect" + else ["startup", "connect", "serve", "shutdown"] + ) + assert not application.state.ready + client.__aexit__.assert_awaited_once() From 75f0b8ec6c36a79aae08ab193517ff782a32e3f4 Mon Sep 17 00:00:00 2001 From: uartnet <140632163+uartnet@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:23:20 +0100 Subject: [PATCH 11/11] docs: name the maintainer CI and release guide explicitly --- docs/006-ci-and-releases.md | 53 +++++++++++++++++++++++++++++++++++++ docs/006-github-setup.md | 53 ------------------------------------- docs/README.md | 24 ++++++++--------- 3 files changed, 65 insertions(+), 65 deletions(-) create mode 100644 docs/006-ci-and-releases.md delete mode 100644 docs/006-github-setup.md diff --git a/docs/006-ci-and-releases.md b/docs/006-ci-and-releases.md new file mode 100644 index 0000000..70b9c68 --- /dev/null +++ b/docs/006-ci-and-releases.md @@ -0,0 +1,53 @@ +# Configure repository CI and releases + +This maintainer guide configures `rstreamlabs/rstream-python` CI and publishing. +Applications use the `rstreamlabs-rstream` package; SDK contributors start with +[Contributing](../CONTRIBUTING.md). + +## CI contract + +The configured CI matrix uses Python 3.10–3.15 on Linux, macOS and Windows. It +runs Ruff, strict Mypy and the local pytest suite without a rstream account. +A separate Python 3.13 job builds distributions and runs +`scripts/verify_distribution.py`. Real-engine checks remain opt-in as described +in [Testing](004-testing.md). + +Protect `main` with reviewed pull requests and required CI, and restrict force +push/deletion. Normal source validation does not authorize a release. + +## Release configuration + +| Setting | Purpose | +| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| Repository variable `CI_ALLOWED_ACTOR` | Actor allowed to run release-please, candidate and promotion jobs. | +| Repository secret `RELEASE_PLEASE_TOKEN` | Minimum required contents/PR authority for release-please. | +| GitHub environment `pypi` | Protect stable promotion with the repository's maintainer approval policy. | +| PyPI trusted publisher | Owner `rstreamlabs`, repository `rstream-python`, workflow `publish.yml`, environment `pypi`, project `rstreamlabs-rstream`. | + +The existing promotion workflow requests `id-token: write` and uses PyPI trusted +publishing; it does not need a long-lived PyPI API token. Configure the publisher +and protected environment before attempting promotion. Do not replace this with +an ambient personal token as a quick-start workaround. + +Keep `release-please-config.json` and `.release-please-manifest.json` versioned. +Release-please coordinates the Python package version, runtime version file, +changelog, tag and draft GitHub release. + +## Candidate and stable promotion + +| Workflow | Input and result | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `release-please.yml` | An allowed push on `main` prepares the release PR/draft and tag. | +| `release-candidate.yml` | A `vX.Y.Z` tag verifies the version, builds wheel/sdist, validates them and retains a checksummed candidate for 90 days. It does not publish PyPI. | +| `publish.yml` | Explicit `release_tag` dispatch selects the successful candidate with the matching tag commit, checks integrity and PyPI state, publishes those retained bytes and then the GitHub release. It never rebuilds the candidate. | + +Promotion requires the GitHub release to remain a draft and refuses an older +release after a newer stable version. Existing PyPI files must match the retained +candidate; retries use that same artifact, not a new build with the same version. +Review the workflow and verification scripts when changing this contract. + +Before proposing a release, run the contributor checks, distribution verification +and relevant explicit real-engine matrix; retain the commands, environment and +results privately. An unrun opt-in test is not a passed qualification. Candidate +creation, publishing and repository-visibility changes are separate maintainer +operations and are not side effects of an ordinary build. diff --git a/docs/006-github-setup.md b/docs/006-github-setup.md deleted file mode 100644 index e0db55c..0000000 --- a/docs/006-github-setup.md +++ /dev/null @@ -1,53 +0,0 @@ -# Configure repository CI and releases - -This is a maintainer guide for `rstreamlabs/rstream-python`, not an application -installation step. Applications use the published `rstreamlabs-rstream` package; -contributors start with [Contributing](../CONTRIBUTING.md). - -## CI contract - -The configured CI matrix uses Python 3.10–3.15 on Linux, macOS and Windows. It -runs Ruff, strict Mypy and the local pytest suite without a rstream account. -A separate Python 3.13 job builds distributions and runs -`scripts/verify_distribution.py`. Real-engine checks remain opt-in as described -in [Testing](004-testing.md). - -Protect `main` with reviewed pull requests and required CI, and restrict force -push/deletion. Normal source validation does not authorize a release. - -## Release configuration - -| Setting | Purpose | -| --- | --- | -| Repository variable `CI_ALLOWED_ACTOR` | Actor allowed to run release-please, candidate and promotion jobs. | -| Repository secret `RELEASE_PLEASE_TOKEN` | Minimum required contents/PR authority for release-please. | -| GitHub environment `pypi` | Protect stable promotion with the repository's maintainer approval policy. | -| PyPI trusted publisher | Owner `rstreamlabs`, repository `rstream-python`, workflow `publish.yml`, environment `pypi`, project `rstreamlabs-rstream`. | - -The existing promotion workflow requests `id-token: write` and uses PyPI trusted -publishing; it does not need a long-lived PyPI API token. Configure the publisher -and protected environment before attempting promotion. Do not replace this with -an ambient personal token as a quick-start workaround. - -Keep `release-please-config.json` and `.release-please-manifest.json` versioned. -Release-please coordinates the Python package version, runtime version file, -changelog, tag and draft GitHub release. - -## Candidate and stable promotion - -| Workflow | Input and result | -| --- | --- | -| `release-please.yml` | An allowed push on `main` prepares the release PR/draft and tag. | -| `release-candidate.yml` | A `vX.Y.Z` tag verifies the version, builds wheel/sdist, validates them and retains a checksummed candidate for 90 days. It does not publish PyPI. | -| `publish.yml` | Explicit `release_tag` dispatch selects the successful candidate with the matching tag commit, checks integrity and PyPI state, publishes those retained bytes and then the GitHub release. It never rebuilds the candidate. | - -Promotion requires the GitHub release to remain a draft and refuses an older -release after a newer stable version. Existing PyPI files must match the retained -candidate; retries use that same artifact, not a new build with the same version. -Review the workflow and verification scripts when changing this contract. - -Before proposing a release, run the contributor checks, distribution verification -and relevant explicit real-engine matrix; retain the commands, environment and -results privately. An unrun opt-in test is not a passed qualification. Candidate -creation, publishing and repository-visibility changes are separate maintainer -operations and are not side effects of an ordinary build. diff --git a/docs/README.md b/docs/README.md index d061f14..a3fd7da 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,18 +4,18 @@ Start with the [repository overview](../README.md) for installation and a first ## Build an integration -| Guide | Use it to | -| --- | --- | -| [Configuration](001-configuration.md) | Select a context, credentials and an engine. | -| [Tunnels](002-tunnels.md) | Create published services, accept streams and dial private tunnels. | -| [Examples](../examples/README.md) | Start from a runnable integration for your application. | -| [Webhooks](003-webhooks.md) | Verify and process lifecycle notifications. | +| Guide | Use it to | +| ------------------------------------- | ------------------------------------------------------------------- | +| [Configuration](001-configuration.md) | Select a context, credentials and an engine. | +| [Tunnels](002-tunnels.md) | Create published services, accept streams and dial private tunnels. | +| [Examples](../examples/README.md) | Start from a runnable integration for your application. | +| [Webhooks](003-webhooks.md) | Verify and process lifecycle notifications. | ## Develop the SDK -| Guide | Scope | -| --- | --- | -| [Contributing](../CONTRIBUTING.md) | Local setup, style and change expectations. | -| [Testing](004-testing.md) | Unit, local fixture and opt-in real-engine checks. | -| [Compatibility matrix](005-test-matrix.md) | Runtime and platform coverage. | -| [Repository automation](006-github-setup.md) | Maintainer CI and release configuration. | +| Guide | Scope | +| ----------------------------------------------- | -------------------------------------------------- | +| [Contributing](../CONTRIBUTING.md) | Local setup, style and change expectations. | +| [Testing](004-testing.md) | Unit, local fixture and opt-in real-engine checks. | +| [Compatibility matrix](005-test-matrix.md) | Runtime and platform coverage. | +| [Repository automation](006-ci-and-releases.md) | Maintainer CI and release configuration. |