rendor 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. rendor-1.0.0/.gitignore +5 -0
  2. rendor-1.0.0/LICENSE +21 -0
  3. rendor-1.0.0/PKG-INFO +333 -0
  4. rendor-1.0.0/README.md +286 -0
  5. rendor-1.0.0/pyproject.toml +103 -0
  6. rendor-1.0.0/src/rendor/__init__.py +92 -0
  7. rendor-1.0.0/src/rendor/__main__.py +36 -0
  8. rendor-1.0.0/src/rendor/_tasks.py +21 -0
  9. rendor-1.0.0/src/rendor/_types.py +94 -0
  10. rendor-1.0.0/src/rendor/actions.py +136 -0
  11. rendor-1.0.0/src/rendor/app.py +1606 -0
  12. rendor-1.0.0/src/rendor/asgi.py +195 -0
  13. rendor-1.0.0/src/rendor/catalog.py +211 -0
  14. rendor-1.0.0/src/rendor/channels.py +349 -0
  15. rendor-1.0.0/src/rendor/client.py +96 -0
  16. rendor-1.0.0/src/rendor/cors.py +98 -0
  17. rendor-1.0.0/src/rendor/diff.py +315 -0
  18. rendor-1.0.0/src/rendor/encode.py +862 -0
  19. rendor-1.0.0/src/rendor/errors.py +69 -0
  20. rendor-1.0.0/src/rendor/expand.py +649 -0
  21. rendor-1.0.0/src/rendor/http.py +199 -0
  22. rendor-1.0.0/src/rendor/identity.py +51 -0
  23. rendor-1.0.0/src/rendor/jcs.py +73 -0
  24. rendor-1.0.0/src/rendor/nodes.py +176 -0
  25. rendor-1.0.0/src/rendor/ops.py +181 -0
  26. rendor-1.0.0/src/rendor/plan.py +254 -0
  27. rendor-1.0.0/src/rendor/probe.py +96 -0
  28. rendor-1.0.0/src/rendor/progressive.py +298 -0
  29. rendor-1.0.0/src/rendor/py.typed +0 -0
  30. rendor-1.0.0/src/rendor/pytest_plugin.py +35 -0
  31. rendor-1.0.0/src/rendor/redis.py +547 -0
  32. rendor-1.0.0/src/rendor/request.py +300 -0
  33. rendor-1.0.0/src/rendor/routing.py +103 -0
  34. rendor-1.0.0/src/rendor/seal.py +165 -0
  35. rendor-1.0.0/src/rendor/stream.py +1541 -0
  36. rendor-1.0.0/src/rendor/testing.py +302 -0
  37. rendor-1.0.0/src/rendor/values.py +27 -0
  38. rendor-1.0.0/src/rendor/windowing.py +36 -0
  39. rendor-1.0.0/src/rendor/ws.py +280 -0
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ .ruff_cache/
rendor-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jayson Clark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rendor-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,333 @@
1
+ Metadata-Version: 2.5
2
+ Name: rendor
3
+ Version: 1.0.0
4
+ Summary: Rendor server SDK for Python: server-driven UI documents, ops, sections, progressive documents, live channels, and an ASGI adapter.
5
+ Project-URL: Homepage, https://jayson-clark.github.io/rendor/
6
+ Project-URL: Documentation, https://jayson-clark.github.io/rendor/guide/server#python
7
+ Project-URL: Repository, https://github.com/jayson-clark/rendor
8
+ Project-URL: Issues, https://github.com/jayson-clark/rendor/issues
9
+ Project-URL: Source, https://github.com/jayson-clark/rendor/tree/main/sdks/python
10
+ Author: Rendor contributors
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: asgi,fastapi,rendor,sdui,server-driven-ui,ui
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Framework :: FastAPI
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
26
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
27
+ Classifier: Topic :: Software Development :: User Interfaces
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.12
30
+ Requires-Dist: orjson>=3.10
31
+ Requires-Dist: pydantic>=2.7
32
+ Requires-Dist: xxhash>=3.4
33
+ Provides-Extra: brotli
34
+ Requires-Dist: brotli>=1.1; extra == 'brotli'
35
+ Provides-Extra: fastapi
36
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
37
+ Provides-Extra: redis
38
+ Requires-Dist: redis>=8.2; extra == 'redis'
39
+ Provides-Extra: serve
40
+ Requires-Dist: uvicorn>=0.30; extra == 'serve'
41
+ Requires-Dist: websockets>=13; extra == 'serve'
42
+ Provides-Extra: starlette
43
+ Requires-Dist: starlette>=0.37; extra == 'starlette'
44
+ Provides-Extra: validate
45
+ Requires-Dist: jsonschema>=4.18; extra == 'validate'
46
+ Description-Content-Type: text/markdown
47
+
48
+ # rendor (Python server SDK)
49
+
50
+ The Python server SDK for [Rendor](https://github.com/jayson-clark/rendor/blob/main/README.md). Servers return documents and op batches.
51
+ The SDK expands section references, encodes canonical JSON, checks it against the client's
52
+ catalog version, and serves it over HTTP following [spec/http.md](https://jayson-clark.github.io/rendor/spec/http).
53
+
54
+ - Python ≥ 3.12. Core dependencies: `pydantic`, `orjson`, `xxhash` (ETags).
55
+ - Extras: `rendor[fastapi]` or `rendor[starlette]` (the frameworks the ASGI adapter mounts
56
+ into; the adapter has no dependencies of its own), `rendor[brotli]` (brotli, quality 4, for responses of
57
+ 4 KiB and up; gzip level 6 below that and whenever brotli isn't accepted), `rendor[validate]` (full JSON Schema validation of props in development, via
58
+ `jsonschema`).
59
+
60
+ ## Install
61
+
62
+ ```sh
63
+ uv add "rendor[fastapi,brotli]"
64
+ ```
65
+
66
+ ## Generate builders from your catalog
67
+
68
+ ```sh
69
+ rendor gen catalog.json --out ui/components.py
70
+ ```
71
+
72
+ Each component becomes a keyword-only function. Props are snake_case (`a11y_label=`), token
73
+ props are `Literal` types, every prop also accepts a reference (`state(...)`, `literal(...)`),
74
+ and events are `on_<event>` (`on_press=`, `on_end_reached=`). Named slots are typed
75
+ (`slots={"empty": [...]}`). App actions get typed builders (`toast_show(text=..., tone=...)`),
76
+ and `CATALOG` carries the catalog's version tables, so `App(catalog=CATALOG)` works without
77
+ shipping catalog.json.
78
+
79
+ ## Quick start (FastAPI)
80
+
81
+ ```python
82
+ from fastapi import FastAPI
83
+ from pydantic import BaseModel
84
+ from rendor import App, Document, ops, server, state
85
+ from ui.components import CATALOG, Button, List, ListItem, Stack, Text, toast_show
86
+
87
+ app = App(catalog=CATALOG, auth=lambda request: sessions.user(request)) # user.id is the identity
88
+
89
+
90
+ def cart_total(cart):
91
+ return Text(id="cart-total", variant="title", text=money(cart.total))
92
+
93
+
94
+ cart = app.route("/cart")
95
+
96
+
97
+ @cart.screen
98
+ async def cart_screen(ctx):
99
+ cart = await carts.get(ctx.user.id)
100
+ return Document(
101
+ root=Stack(gap="md", padding="lg", children=[
102
+ List(id="cart-items", slots={"empty": [Text(text="Your cart is empty")]}, children=[
103
+ ListItem(id=f"item-{i.sku}", title=i.name, children=[
104
+ Button(label="Remove", busy=state(f"removing-{i.sku}"),
105
+ on_press=server("cart.remove", args={"sku": i.sku},
106
+ pending=f"removing-{i.sku}", concurrency="drop",
107
+ concurrency_key=f"remove-{i.sku}",
108
+ optimistic=[ops.remove(f"item-{i.sku}", animate=True)])),
109
+ ]) for i in cart.items
110
+ ]),
111
+ cart_total(cart),
112
+ ]),
113
+ meta={"title": "Cart"},
114
+ )
115
+
116
+
117
+ class RemoveArgs(BaseModel):
118
+ sku: str
119
+
120
+
121
+ @cart.event("cart.remove")
122
+ async def remove(ctx, args: RemoveArgs):
123
+ cart = await carts.remove_item(ctx.user.id, args.sku)
124
+ return [
125
+ ops.remove(f"item-{args.sku}", if_exists=True),
126
+ ops.replace(cart_total(cart)),
127
+ ops.run(toast_show(text="Removed")),
128
+ ]
129
+
130
+
131
+ api = FastAPI(lifespan=app.lifespan) # closes stream connections on shutdown
132
+ api.mount("/ui", app.asgi())
133
+
134
+ if __name__ == "__main__":
135
+ app.serve(port=8788, asgi=api) # explicit port beats PORT; HOST/PORT apply when omitted, else 127.0.0.1:8787; uvicorn (pip install 'rendor[serve]'), graceful shutdown
136
+ ```
137
+
138
+ - **Screens** take `ctx` and the path parameters they name (`app.route("/p/:slug")` or
139
+ `"/p/{slug}"`, then `@route.screen` on `def page(ctx, slug: str)`), and return a `Document`
140
+ (or a dict with a `root`); `None` answers 404. `@route.screen(etag=..., varies=[...],
141
+ cache=...)`: a cheap version function answered with 304 before rendering, and what the
142
+ output depends on, which sets `Vary` and `Cache-Control` (http.md §3.1, §7). In
143
+ development a render that reads something `varies` leaves out fails with `500
144
+ undeclared_varies`; production pays nothing for the check.
145
+ - **Events** are `(ctx, args)`: `@route.event("cart.remove")` on `def remove(ctx, args:
146
+ RemoveArgs)`. The args type comes from the annotation (a pydantic model, or any type pydantic
147
+ validates). The screen's state is `ctx.state`, typed by `@route.event(name, state=Model)`.
148
+ Failures answer 400 `invalid_args`/`invalid_state`. `@app.event("recs.dismiss")` registers a
149
+ global event (the name must be namespaced). A repeated `Rendor-Event-Id` runs the handler
150
+ once, even when the repeats are concurrent (single-flight).
151
+ - **Sections**: `@app.section("recs", varies=[...], meta={...})`, with params typed by the
152
+ render function's second parameter. Reference them with
153
+ `section("recs", {"limit": 6}, id="home-recs")` anywhere a node goes, or render one now with
154
+ `await ctx.section(...)`. `section(name, params=None, *, id=None, fallback=None)`.
155
+ - **Context**: `ctx.request`, `ctx.user` (from `auth`, sync or async), `ctx.client` (protocol,
156
+ catalog name and version, platform, app version, locale from `Rendor-Locale`,
157
+ time zone, `supports(name)`), `ctx.params`, `ctx.query`, `ctx.state`, `ctx.section_id`,
158
+ `ctx.event_id`, and the lazy `ctx.identity`.
159
+ - **Errors**: `raise RendorError("cart.not_found", status=404, ops=[ops.refresh()])`. In
160
+ production a 5xx response carries only the code; its message and the exception go to the
161
+ log, with the method, path, and event.
162
+ - **Modes**: `"production"` (the default) strips output a client can't render and logs it
163
+ (catalog-format §3); `"development"` raises instead and sends error messages. Without
164
+ `mode=`, the `RENDOR_MODE` environment variable decides: exactly `development` or
165
+ `production` (surrounding whitespace is trimmed; an empty value counts as unset; anything
166
+ else raises at `App` creation). The resolved mode is logged once at `INFO` on the `rendor`
167
+ logger. In development, install `rendor[validate]` for full JSON Schema validation of props
168
+ (a one-time warning is logged without it).
169
+ - **Identity**: the user `auth` returns is identified by `App(identity=lambda user: ...)`, else
170
+ `user.id`, else `user.sub` (attribute or key), else the user itself when it is a string or
171
+ integer. It owns stream connections, is the `user` variant, and is mixed into version
172
+ ETags. It is computed on first read, so a request that never reads it never pays. A user it
173
+ can't identify answers `500 internal` and logs a configuration error; it never falls back
174
+ to `str(user)`. No `auth` hook means anonymous.
175
+ - **Sync functions**: `App(sync_handlers="thread")` (default) runs non-async handlers, screens,
176
+ sections, version functions, channel authorizers, the `auth` hook, and a sync `DedupeStore`
177
+ in a worker thread (`asyncio.to_thread`), so blocking I/O doesn't stall other requests;
178
+ `"inline"` runs them on the event loop (lowest overhead, for functions that never block).
179
+ Async functions always run on the loop.
180
+ - **Type hints** on args, state, params, and path parameters must resolve when the function
181
+ is registered (a `TypeError` says which one doesn't); annotations of other parameters, such
182
+ as `ctx: Context` imported under `TYPE_CHECKING`, aren't evaluated.
183
+ - **Validation is strict**: event args/state and section params are validated with pydantic
184
+ `strict=True` (`"3"` is not an int). Path parameters come from URL strings, so annotated
185
+ ones (`id: int`) are still converted; a failed conversion is a 404.
186
+ - **Version ETags and `Vary`**: a screen's `etag=` result is combined with the user's id
187
+ (`user.id`, `user["id"]`, or the user itself) unless `varies=` is set and excludes `"user"`;
188
+ with no user nothing is mixed in. Screens that vary on `locale` send `Vary: Rendor-Locale`
189
+ (also on 304s).
190
+ - Without FastAPI: `App.handle(Request(...))` is framework-agnostic, and `app.asgi()` is a
191
+ plain ASGI app (Starlette `Mount`, or `uvicorn module:asgi`, or `app.serve()`).
192
+
193
+ ## Streaming
194
+
195
+ Progressive documents and live channels ([spec/streaming.md](https://jayson-clark.github.io/rendor/spec/streaming)); see
196
+ [server guide](https://jayson-clark.github.io/rendor/guide/server#streaming-in-the-python-sdk) for the details.
197
+
198
+ ```python
199
+ from rendor import StreamOptions, defer, section
200
+
201
+ app = App(catalog=CATALOG, auth=auth, stream=StreamOptions()) # defaults: MemoryBackend, 20 s pings
202
+
203
+ @app.route("/").screen
204
+ def home(ctx):
205
+ return Document(root=Stack(children=[
206
+ Text(text="Hello"),
207
+ # NDJSON clients get the skeleton now and the node when `recs` finishes; others get it inline.
208
+ defer("recs", Skeleton(lines=2), lambda: recommendations(ctx.user), # returns a coroutine
209
+ fallback=Text(text="Unavailable")),
210
+ ]))
211
+
212
+ @app.channel("cart/:user")
213
+ def can_watch(ctx, user: str) -> bool:
214
+ return ctx.user.id == user
215
+
216
+ @app.section("cart.total", varies=["locale", "catalog"])
217
+ def cart_total_section(ctx, p: CartParams):
218
+ return cart_total(carts.get(p.user), ctx.client.locale)
219
+
220
+ @app.route("/cart").event("cart.remove")
221
+ async def remove(ctx, args: RemoveArgs):
222
+ ...
223
+ await app.publish(f"cart/{ctx.user.id}", [
224
+ ops.replace(section("cart.total", {"user": ctx.user.id}, id="cart-total")),
225
+ ])
226
+ return [...]
227
+ ```
228
+
229
+ - `defer` renders run as asyncio tasks: a timeout (`App(defer_timeout=30.0)` or `timeout=`) or
230
+ a client that disconnects cancels them.
231
+ - `app.asgi()` streams NDJSON and SSE (`GET /_rendor/stream?channels=...`; over SSE a client changes its channels by reconnecting),
232
+ pings idle connections, drops clients that stop reading, and compresses SSE with
233
+ small-window gzip whose state is released while idle.
234
+ - WebSocket transport ([spec/websocket.md](https://jayson-clark.github.io/rendor/spec/websocket)): `app.asgi()` also serves
235
+ `{base_path}/_rendor/ws` (subprotocol `rendor.v1`), carrying channels and events over one socket with the
236
+ same fan-out, replay, and limits as SSE. Messages are uncompressed unless `app.serve(websocket_compression=True)`
237
+ (running uvicorn yourself, pass `ws_per_message_deflate=False`: its default is on, at about 50 KB per socket).
238
+ It is on by default; `App(websocket=False)` turns it off, and clients
239
+ fall back to SSE and HTTP. The upgrade needs a server with WebSocket support: uvicorn needs the `websockets`
240
+ or `wsproto` package (`pip install 'rendor[serve]'` includes `websockets`, or use `uvicorn[standard]`);
241
+ without one, uvicorn passes the upgrade on as a plain request, which gets `404`, and clients fall back. A server that supports the ASGI
242
+ `websocket.http.response` extension (uvicorn does) sends refusals as HTTP `400`/`403`/`404`/`503` with the
243
+ JSON error; others close the handshake. At most `StreamOptions(max_events_per_socket=32)` events run at once
244
+ on a socket (`429 too_many_events`).
245
+ - Limits (`StreamOptions`): 100 channels per connection (`too_many_channels`), 10 connections
246
+ per user (`429 too_many_connections`), 10,000 per process (`503 overloaded`), 16 concurrent
247
+ `authorize` calls per request, 1,000 replayed batches per channel, and a 24 h connection age
248
+ after which clients reconnect and are authorized again.
249
+ - Shutdown: `FastAPI(lifespan=app.lifespan)` (or `async with app.lifespan():` in your own)
250
+ closes streams when the server stops, and new ones get `503 shutting_down`. `app.serve()`
251
+ runs uvicorn and closes streams on SIGINT/SIGTERM first, so shutdown doesn't wait on them
252
+ (with your own server, call `app.close_streams()` from the signal handler); see [examples/server-python](https://github.com/jayson-clark/rendor/blob/main/examples/server-python/app/main.py).
253
+ - `Document(root=..., refresh_on_focus=True, offline=True)` sets the document options.
254
+ - `app.publish_threadsafe(channel, ops)` publishes from another thread (a sync handler) and
255
+ returns a `concurrent.futures.Future` of the seq.
256
+ - `app.stream_metrics()` and `StreamOptions(on_delivered=...)` report the stream tier.
257
+ - `MemoryBackend` serves one process: run a single stream instance (or route sticky). For
258
+ several instances use `RedisBackend` (below); see
259
+ [deployment guide](https://jayson-clark.github.io/rendor/guide/deployment).
260
+
261
+ ## Sealed args, CORS, section previews, Redis
262
+
263
+ All opt-in; see the [server guide](https://jayson-clark.github.io/rendor/guide/server#optional-features-in-the-python-sdk).
264
+
265
+ ```python
266
+ from rendor import App, Cors, StreamOptions, server, feed_window
267
+ from rendor.redis import RedisBackend # pip install rendor[redis]
268
+
269
+ app = App(
270
+ catalog=CATALOG,
271
+ seal_keys=[("k1", os.environ["RENDOR_SEAL_KEY"])], # first seals, all open
272
+ cors=Cors(origins=["https://app.example.com"]),
273
+ section_endpoints=lambda ctx: ctx.user.is_admin,
274
+ stream=StreamOptions(backend=RedisBackend("redis://localhost:6379")),
275
+ )
276
+
277
+ Button(label="Remove", on_press=server("cart.remove", args={"sku": "A"}, seal=True))
278
+
279
+ @app.route("/cart").event("cart.remove", sealed=True) # 400 invalid_seal on a bad seal
280
+ def remove(ctx, args: RemoveArgs): ...
281
+
282
+ ops.set_state(...), *feed_window(list_id="feed", page=n, node=page(n), size=5, placeholder=placeholder, end_reached=more(n + 1))
283
+ ```
284
+
285
+ `rendor.diff(before, after)` returns the ops (`update`, `insert`, `remove`, `move`, or a `replace`) that turn one rendering of a node into another, for a handler that can render a section before and after a change ([spec](https://jayson-clark.github.io/rendor/spec/diff)). `before` needs an id and `after` the same id or none, else `ValueError`; use it only when `before` is what the client shows, otherwise `replace`.
286
+
287
+ `python -m rendor sections export module:app` prints the section manifest. Pass
288
+ `lifespan=app.lifespan` so the Redis backend starts and closes with the server.
289
+
290
+ ## Testing
291
+
292
+ ```python
293
+ import pytest
294
+ from rendor.testing import Harness
295
+
296
+ @pytest.mark.anyio
297
+ async def test_remove():
298
+ rendor = Harness(app)
299
+ res = await rendor.screen("/cart", user=user, device={"catalog": 12, "platform": "ios"})
300
+ assert res.find("cart-total")["props"]["text"] == "$24.00"
301
+
302
+ batch = await rendor.event("/cart", "cart.remove", args={"sku": "A"}, user=user)
303
+ assert {"op": "remove", "id": "item-A", "ifExists": True} in batch
304
+ ```
305
+
306
+ `rendor.testing` is async-first: `Harness(app).screen` and `.event` run without HTTP, with full
307
+ output validation, and raise `RendorError`. `.progressive(path)` returns every NDJSON line of
308
+ a progressive load (`deferred` ids first), and `async with await h.stream(channels=[...],
309
+ user=...) as s` opens a real stream connection (`await s.next()`). The bundled pytest plugin
310
+ adds a `rendor` fixture (a `Harness`) when you define a `rendor_app` fixture. It is opt-in:
311
+ `pytest -p rendor.pytest_plugin`, the same in `addopts`, or `pytest_plugins =
312
+ ["rendor.pytest_plugin"]` in a top-level `conftest.py`. Async tests need the `anyio` marker
313
+ (and an `anyio_backend` fixture returning `"asyncio"`).
314
+
315
+ ## Development
316
+
317
+ ```sh
318
+ cd sdks/python
319
+ uv run --python 3.15 pytest -q # or: pnpm test:python (from the repo root)
320
+ uv run --python 3.12 pytest -q
321
+ uv run ruff check && uv run pyright
322
+ ```
323
+
324
+ The tests include the `serialize`, `expand`, `args`, `progressive`, `stream`, `encode`, and
325
+ `http` conformance fixtures (read from `spec/conformance`; skipped outside the repository), a
326
+ run under a real uvicorn server, and the performance budgets, including the stream tier's
327
+ (`tests/test_stream_budgets.py`; `RENDOR_SKIP_BUDGETS=1` skips them).
328
+ `tests/shop_components.py` is generated from `tests/fixtures/shop.catalog.json` (the TypeScript
329
+ SDK's test catalog). Until the CLI is rebuilt, regenerate with the in-repo generator:
330
+
331
+ ```sh
332
+ npx tsx sdks/python/scripts/gen.ts sdks/python/tests/fixtures/shop.catalog.json sdks/python/tests/shop_components.py
333
+ ```
rendor-1.0.0/README.md ADDED
@@ -0,0 +1,286 @@
1
+ # rendor (Python server SDK)
2
+
3
+ The Python server SDK for [Rendor](https://github.com/jayson-clark/rendor/blob/main/README.md). Servers return documents and op batches.
4
+ The SDK expands section references, encodes canonical JSON, checks it against the client's
5
+ catalog version, and serves it over HTTP following [spec/http.md](https://jayson-clark.github.io/rendor/spec/http).
6
+
7
+ - Python ≥ 3.12. Core dependencies: `pydantic`, `orjson`, `xxhash` (ETags).
8
+ - Extras: `rendor[fastapi]` or `rendor[starlette]` (the frameworks the ASGI adapter mounts
9
+ into; the adapter has no dependencies of its own), `rendor[brotli]` (brotli, quality 4, for responses of
10
+ 4 KiB and up; gzip level 6 below that and whenever brotli isn't accepted), `rendor[validate]` (full JSON Schema validation of props in development, via
11
+ `jsonschema`).
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ uv add "rendor[fastapi,brotli]"
17
+ ```
18
+
19
+ ## Generate builders from your catalog
20
+
21
+ ```sh
22
+ rendor gen catalog.json --out ui/components.py
23
+ ```
24
+
25
+ Each component becomes a keyword-only function. Props are snake_case (`a11y_label=`), token
26
+ props are `Literal` types, every prop also accepts a reference (`state(...)`, `literal(...)`),
27
+ and events are `on_<event>` (`on_press=`, `on_end_reached=`). Named slots are typed
28
+ (`slots={"empty": [...]}`). App actions get typed builders (`toast_show(text=..., tone=...)`),
29
+ and `CATALOG` carries the catalog's version tables, so `App(catalog=CATALOG)` works without
30
+ shipping catalog.json.
31
+
32
+ ## Quick start (FastAPI)
33
+
34
+ ```python
35
+ from fastapi import FastAPI
36
+ from pydantic import BaseModel
37
+ from rendor import App, Document, ops, server, state
38
+ from ui.components import CATALOG, Button, List, ListItem, Stack, Text, toast_show
39
+
40
+ app = App(catalog=CATALOG, auth=lambda request: sessions.user(request)) # user.id is the identity
41
+
42
+
43
+ def cart_total(cart):
44
+ return Text(id="cart-total", variant="title", text=money(cart.total))
45
+
46
+
47
+ cart = app.route("/cart")
48
+
49
+
50
+ @cart.screen
51
+ async def cart_screen(ctx):
52
+ cart = await carts.get(ctx.user.id)
53
+ return Document(
54
+ root=Stack(gap="md", padding="lg", children=[
55
+ List(id="cart-items", slots={"empty": [Text(text="Your cart is empty")]}, children=[
56
+ ListItem(id=f"item-{i.sku}", title=i.name, children=[
57
+ Button(label="Remove", busy=state(f"removing-{i.sku}"),
58
+ on_press=server("cart.remove", args={"sku": i.sku},
59
+ pending=f"removing-{i.sku}", concurrency="drop",
60
+ concurrency_key=f"remove-{i.sku}",
61
+ optimistic=[ops.remove(f"item-{i.sku}", animate=True)])),
62
+ ]) for i in cart.items
63
+ ]),
64
+ cart_total(cart),
65
+ ]),
66
+ meta={"title": "Cart"},
67
+ )
68
+
69
+
70
+ class RemoveArgs(BaseModel):
71
+ sku: str
72
+
73
+
74
+ @cart.event("cart.remove")
75
+ async def remove(ctx, args: RemoveArgs):
76
+ cart = await carts.remove_item(ctx.user.id, args.sku)
77
+ return [
78
+ ops.remove(f"item-{args.sku}", if_exists=True),
79
+ ops.replace(cart_total(cart)),
80
+ ops.run(toast_show(text="Removed")),
81
+ ]
82
+
83
+
84
+ api = FastAPI(lifespan=app.lifespan) # closes stream connections on shutdown
85
+ api.mount("/ui", app.asgi())
86
+
87
+ if __name__ == "__main__":
88
+ app.serve(port=8788, asgi=api) # explicit port beats PORT; HOST/PORT apply when omitted, else 127.0.0.1:8787; uvicorn (pip install 'rendor[serve]'), graceful shutdown
89
+ ```
90
+
91
+ - **Screens** take `ctx` and the path parameters they name (`app.route("/p/:slug")` or
92
+ `"/p/{slug}"`, then `@route.screen` on `def page(ctx, slug: str)`), and return a `Document`
93
+ (or a dict with a `root`); `None` answers 404. `@route.screen(etag=..., varies=[...],
94
+ cache=...)`: a cheap version function answered with 304 before rendering, and what the
95
+ output depends on, which sets `Vary` and `Cache-Control` (http.md §3.1, §7). In
96
+ development a render that reads something `varies` leaves out fails with `500
97
+ undeclared_varies`; production pays nothing for the check.
98
+ - **Events** are `(ctx, args)`: `@route.event("cart.remove")` on `def remove(ctx, args:
99
+ RemoveArgs)`. The args type comes from the annotation (a pydantic model, or any type pydantic
100
+ validates). The screen's state is `ctx.state`, typed by `@route.event(name, state=Model)`.
101
+ Failures answer 400 `invalid_args`/`invalid_state`. `@app.event("recs.dismiss")` registers a
102
+ global event (the name must be namespaced). A repeated `Rendor-Event-Id` runs the handler
103
+ once, even when the repeats are concurrent (single-flight).
104
+ - **Sections**: `@app.section("recs", varies=[...], meta={...})`, with params typed by the
105
+ render function's second parameter. Reference them with
106
+ `section("recs", {"limit": 6}, id="home-recs")` anywhere a node goes, or render one now with
107
+ `await ctx.section(...)`. `section(name, params=None, *, id=None, fallback=None)`.
108
+ - **Context**: `ctx.request`, `ctx.user` (from `auth`, sync or async), `ctx.client` (protocol,
109
+ catalog name and version, platform, app version, locale from `Rendor-Locale`,
110
+ time zone, `supports(name)`), `ctx.params`, `ctx.query`, `ctx.state`, `ctx.section_id`,
111
+ `ctx.event_id`, and the lazy `ctx.identity`.
112
+ - **Errors**: `raise RendorError("cart.not_found", status=404, ops=[ops.refresh()])`. In
113
+ production a 5xx response carries only the code; its message and the exception go to the
114
+ log, with the method, path, and event.
115
+ - **Modes**: `"production"` (the default) strips output a client can't render and logs it
116
+ (catalog-format §3); `"development"` raises instead and sends error messages. Without
117
+ `mode=`, the `RENDOR_MODE` environment variable decides: exactly `development` or
118
+ `production` (surrounding whitespace is trimmed; an empty value counts as unset; anything
119
+ else raises at `App` creation). The resolved mode is logged once at `INFO` on the `rendor`
120
+ logger. In development, install `rendor[validate]` for full JSON Schema validation of props
121
+ (a one-time warning is logged without it).
122
+ - **Identity**: the user `auth` returns is identified by `App(identity=lambda user: ...)`, else
123
+ `user.id`, else `user.sub` (attribute or key), else the user itself when it is a string or
124
+ integer. It owns stream connections, is the `user` variant, and is mixed into version
125
+ ETags. It is computed on first read, so a request that never reads it never pays. A user it
126
+ can't identify answers `500 internal` and logs a configuration error; it never falls back
127
+ to `str(user)`. No `auth` hook means anonymous.
128
+ - **Sync functions**: `App(sync_handlers="thread")` (default) runs non-async handlers, screens,
129
+ sections, version functions, channel authorizers, the `auth` hook, and a sync `DedupeStore`
130
+ in a worker thread (`asyncio.to_thread`), so blocking I/O doesn't stall other requests;
131
+ `"inline"` runs them on the event loop (lowest overhead, for functions that never block).
132
+ Async functions always run on the loop.
133
+ - **Type hints** on args, state, params, and path parameters must resolve when the function
134
+ is registered (a `TypeError` says which one doesn't); annotations of other parameters, such
135
+ as `ctx: Context` imported under `TYPE_CHECKING`, aren't evaluated.
136
+ - **Validation is strict**: event args/state and section params are validated with pydantic
137
+ `strict=True` (`"3"` is not an int). Path parameters come from URL strings, so annotated
138
+ ones (`id: int`) are still converted; a failed conversion is a 404.
139
+ - **Version ETags and `Vary`**: a screen's `etag=` result is combined with the user's id
140
+ (`user.id`, `user["id"]`, or the user itself) unless `varies=` is set and excludes `"user"`;
141
+ with no user nothing is mixed in. Screens that vary on `locale` send `Vary: Rendor-Locale`
142
+ (also on 304s).
143
+ - Without FastAPI: `App.handle(Request(...))` is framework-agnostic, and `app.asgi()` is a
144
+ plain ASGI app (Starlette `Mount`, or `uvicorn module:asgi`, or `app.serve()`).
145
+
146
+ ## Streaming
147
+
148
+ Progressive documents and live channels ([spec/streaming.md](https://jayson-clark.github.io/rendor/spec/streaming)); see
149
+ [server guide](https://jayson-clark.github.io/rendor/guide/server#streaming-in-the-python-sdk) for the details.
150
+
151
+ ```python
152
+ from rendor import StreamOptions, defer, section
153
+
154
+ app = App(catalog=CATALOG, auth=auth, stream=StreamOptions()) # defaults: MemoryBackend, 20 s pings
155
+
156
+ @app.route("/").screen
157
+ def home(ctx):
158
+ return Document(root=Stack(children=[
159
+ Text(text="Hello"),
160
+ # NDJSON clients get the skeleton now and the node when `recs` finishes; others get it inline.
161
+ defer("recs", Skeleton(lines=2), lambda: recommendations(ctx.user), # returns a coroutine
162
+ fallback=Text(text="Unavailable")),
163
+ ]))
164
+
165
+ @app.channel("cart/:user")
166
+ def can_watch(ctx, user: str) -> bool:
167
+ return ctx.user.id == user
168
+
169
+ @app.section("cart.total", varies=["locale", "catalog"])
170
+ def cart_total_section(ctx, p: CartParams):
171
+ return cart_total(carts.get(p.user), ctx.client.locale)
172
+
173
+ @app.route("/cart").event("cart.remove")
174
+ async def remove(ctx, args: RemoveArgs):
175
+ ...
176
+ await app.publish(f"cart/{ctx.user.id}", [
177
+ ops.replace(section("cart.total", {"user": ctx.user.id}, id="cart-total")),
178
+ ])
179
+ return [...]
180
+ ```
181
+
182
+ - `defer` renders run as asyncio tasks: a timeout (`App(defer_timeout=30.0)` or `timeout=`) or
183
+ a client that disconnects cancels them.
184
+ - `app.asgi()` streams NDJSON and SSE (`GET /_rendor/stream?channels=...`; over SSE a client changes its channels by reconnecting),
185
+ pings idle connections, drops clients that stop reading, and compresses SSE with
186
+ small-window gzip whose state is released while idle.
187
+ - WebSocket transport ([spec/websocket.md](https://jayson-clark.github.io/rendor/spec/websocket)): `app.asgi()` also serves
188
+ `{base_path}/_rendor/ws` (subprotocol `rendor.v1`), carrying channels and events over one socket with the
189
+ same fan-out, replay, and limits as SSE. Messages are uncompressed unless `app.serve(websocket_compression=True)`
190
+ (running uvicorn yourself, pass `ws_per_message_deflate=False`: its default is on, at about 50 KB per socket).
191
+ It is on by default; `App(websocket=False)` turns it off, and clients
192
+ fall back to SSE and HTTP. The upgrade needs a server with WebSocket support: uvicorn needs the `websockets`
193
+ or `wsproto` package (`pip install 'rendor[serve]'` includes `websockets`, or use `uvicorn[standard]`);
194
+ without one, uvicorn passes the upgrade on as a plain request, which gets `404`, and clients fall back. A server that supports the ASGI
195
+ `websocket.http.response` extension (uvicorn does) sends refusals as HTTP `400`/`403`/`404`/`503` with the
196
+ JSON error; others close the handshake. At most `StreamOptions(max_events_per_socket=32)` events run at once
197
+ on a socket (`429 too_many_events`).
198
+ - Limits (`StreamOptions`): 100 channels per connection (`too_many_channels`), 10 connections
199
+ per user (`429 too_many_connections`), 10,000 per process (`503 overloaded`), 16 concurrent
200
+ `authorize` calls per request, 1,000 replayed batches per channel, and a 24 h connection age
201
+ after which clients reconnect and are authorized again.
202
+ - Shutdown: `FastAPI(lifespan=app.lifespan)` (or `async with app.lifespan():` in your own)
203
+ closes streams when the server stops, and new ones get `503 shutting_down`. `app.serve()`
204
+ runs uvicorn and closes streams on SIGINT/SIGTERM first, so shutdown doesn't wait on them
205
+ (with your own server, call `app.close_streams()` from the signal handler); see [examples/server-python](https://github.com/jayson-clark/rendor/blob/main/examples/server-python/app/main.py).
206
+ - `Document(root=..., refresh_on_focus=True, offline=True)` sets the document options.
207
+ - `app.publish_threadsafe(channel, ops)` publishes from another thread (a sync handler) and
208
+ returns a `concurrent.futures.Future` of the seq.
209
+ - `app.stream_metrics()` and `StreamOptions(on_delivered=...)` report the stream tier.
210
+ - `MemoryBackend` serves one process: run a single stream instance (or route sticky). For
211
+ several instances use `RedisBackend` (below); see
212
+ [deployment guide](https://jayson-clark.github.io/rendor/guide/deployment).
213
+
214
+ ## Sealed args, CORS, section previews, Redis
215
+
216
+ All opt-in; see the [server guide](https://jayson-clark.github.io/rendor/guide/server#optional-features-in-the-python-sdk).
217
+
218
+ ```python
219
+ from rendor import App, Cors, StreamOptions, server, feed_window
220
+ from rendor.redis import RedisBackend # pip install rendor[redis]
221
+
222
+ app = App(
223
+ catalog=CATALOG,
224
+ seal_keys=[("k1", os.environ["RENDOR_SEAL_KEY"])], # first seals, all open
225
+ cors=Cors(origins=["https://app.example.com"]),
226
+ section_endpoints=lambda ctx: ctx.user.is_admin,
227
+ stream=StreamOptions(backend=RedisBackend("redis://localhost:6379")),
228
+ )
229
+
230
+ Button(label="Remove", on_press=server("cart.remove", args={"sku": "A"}, seal=True))
231
+
232
+ @app.route("/cart").event("cart.remove", sealed=True) # 400 invalid_seal on a bad seal
233
+ def remove(ctx, args: RemoveArgs): ...
234
+
235
+ ops.set_state(...), *feed_window(list_id="feed", page=n, node=page(n), size=5, placeholder=placeholder, end_reached=more(n + 1))
236
+ ```
237
+
238
+ `rendor.diff(before, after)` returns the ops (`update`, `insert`, `remove`, `move`, or a `replace`) that turn one rendering of a node into another, for a handler that can render a section before and after a change ([spec](https://jayson-clark.github.io/rendor/spec/diff)). `before` needs an id and `after` the same id or none, else `ValueError`; use it only when `before` is what the client shows, otherwise `replace`.
239
+
240
+ `python -m rendor sections export module:app` prints the section manifest. Pass
241
+ `lifespan=app.lifespan` so the Redis backend starts and closes with the server.
242
+
243
+ ## Testing
244
+
245
+ ```python
246
+ import pytest
247
+ from rendor.testing import Harness
248
+
249
+ @pytest.mark.anyio
250
+ async def test_remove():
251
+ rendor = Harness(app)
252
+ res = await rendor.screen("/cart", user=user, device={"catalog": 12, "platform": "ios"})
253
+ assert res.find("cart-total")["props"]["text"] == "$24.00"
254
+
255
+ batch = await rendor.event("/cart", "cart.remove", args={"sku": "A"}, user=user)
256
+ assert {"op": "remove", "id": "item-A", "ifExists": True} in batch
257
+ ```
258
+
259
+ `rendor.testing` is async-first: `Harness(app).screen` and `.event` run without HTTP, with full
260
+ output validation, and raise `RendorError`. `.progressive(path)` returns every NDJSON line of
261
+ a progressive load (`deferred` ids first), and `async with await h.stream(channels=[...],
262
+ user=...) as s` opens a real stream connection (`await s.next()`). The bundled pytest plugin
263
+ adds a `rendor` fixture (a `Harness`) when you define a `rendor_app` fixture. It is opt-in:
264
+ `pytest -p rendor.pytest_plugin`, the same in `addopts`, or `pytest_plugins =
265
+ ["rendor.pytest_plugin"]` in a top-level `conftest.py`. Async tests need the `anyio` marker
266
+ (and an `anyio_backend` fixture returning `"asyncio"`).
267
+
268
+ ## Development
269
+
270
+ ```sh
271
+ cd sdks/python
272
+ uv run --python 3.15 pytest -q # or: pnpm test:python (from the repo root)
273
+ uv run --python 3.12 pytest -q
274
+ uv run ruff check && uv run pyright
275
+ ```
276
+
277
+ The tests include the `serialize`, `expand`, `args`, `progressive`, `stream`, `encode`, and
278
+ `http` conformance fixtures (read from `spec/conformance`; skipped outside the repository), a
279
+ run under a real uvicorn server, and the performance budgets, including the stream tier's
280
+ (`tests/test_stream_budgets.py`; `RENDOR_SKIP_BUDGETS=1` skips them).
281
+ `tests/shop_components.py` is generated from `tests/fixtures/shop.catalog.json` (the TypeScript
282
+ SDK's test catalog). Until the CLI is rebuilt, regenerate with the in-repo generator:
283
+
284
+ ```sh
285
+ npx tsx sdks/python/scripts/gen.ts sdks/python/tests/fixtures/shop.catalog.json sdks/python/tests/shop_components.py
286
+ ```