Rust #
The microsoft-webui crate, imported as webui, provides build and rendering
APIs. Load one Protocol at startup and reuse it with request state.
WebUIHandler writes HTML through ResponseWriter; the host chooses buffered
output or a backpressured streaming writer.
Custom writers only need to implement write and end. The optional
write_escaped and write_escaped_attribute methods let buffered writers append
escaped values directly to their output buffer. Their defaults handle escaping;
overrides must preserve encode_safe's replacements for &, <, >, ", ',
and /. Attribute names passed to write_escaped_attribute must be trusted.
Installation #
To install the standalone compiler without npm, use Rust 1.99.1 or newer:
cargo install microsoft-webui-cli
This builds the CLI without Node/npm. Native application checking also requires the release-matched native toolchain with its native TypeScript compiler.
For a Rust application host, add the rendering library:
[dependencies]
microsoft-webui = "*" # see https://crates.io/crates/microsoft-webui for latest version
serde_json = "1"
The crate is published as microsoft-webui on crates.io; the bare webui name is owned by an unrelated project. Cargo's default rename rules mean items remain importable as use webui::... because the crate sets [lib] name = "webui" internally.
Scaffold an application #
With the native toolchain and Cargo installed:
webui init my-app --server rust --no-interactive
cd my-app
webui app check
webui app dev
The native default creates Cargo.toml, src/main.rs, web/, and
webui.toml, with no package.json or JavaScript build scripts. Frontend
compilation does not require Node. Cargo provides the renderer; Rust hosts do
not use the standalone C ABI SDK.
Use webui app build followed by webui app start for a complete production
build. Start verifies the recorded executable and protocol and performs no
compilation or restoration. Only dist/public/ is public static content.
The generated server drains requests before releasing renderer resources.
For direct Cargo commands, prepare the frontend first:
webui app build --frontend-only
cargo check
cargo run --release
Cargo does not rebuild browser assets or templates. Native app builds use the
project's target/ directory, independently of inherited CARGO_TARGET_DIR.
See app commands for native development and
production workflows.
Lazy template packs #
Lazy bodies need no request-time API. webui::build()
returns their packs in BuildResult::lazy_pack_files, and
webui::build_to_disk() writes them; call webui::write_lazy_packs(out_dir, &packs) when you build in memory. Serve <out>/_webui/packs/ as immutable
static files. Templates reference packs by paths relative to the asset base
(BuildOptions::asset_base, or $webui.assetBase per request).
When the build has lazy regions, BuildResult::lazy_scripts_module is the
generated lazy.webui.js (webui::LAZY_SCRIPTS_MODULE). It registers
dynamic imports of scripted components not already loaded at startup.
Import it before starting the renderer; registration starts no component loads.
Your bundler owns splitting and public paths.
Its declaration is lazy.webui.d.ts (webui::LAZY_SCRIPTS_DECLARATION),
which supplies the runtime types without allowJs; write it next to the module. Relative
specifiers start at BuildOptions::modules_out, or at app_dir without one.
build_to_disk() writes both files to modules_out, defaulting to the output
directory. Each LazyPackFile also reports its region, owner, trigger,
components, scripts, stylesheets, and, when metafile is set,
brotli_bytes; path(), bytes(), and hash() return its asset-base path,
raw size, and content hash. stylesheets holds the paths, relative to the
asset base, of the stylesheets the region loads with its pack in a
CssStrategy::Link build (entries of BuildResult::css_files, including
bundled chunks); it is empty for Style and Module builds, whose packs carry
the CSS. A service worker that precaches a region needs its path(), its
stylesheets, and the bundler outputs for its scripts.
Examples #
These examples render an existing dist/protocol.bin. They buffer into a
string; the streaming example below uses a bounded transport.
use actix_web::{web, App, HttpServer, HttpRequest, HttpResponse};
use webui::{Protocol, WebUIHandler, RenderOptions, ResponseWriter};
use serde_json::json;
use std::fs;
struct StringWriter(String);
impl ResponseWriter for StringWriter {
fn write(&mut self, content: &str) -> webui::HandlerResult<()> {
self.0.push_str(content);
Ok(())
}
fn end(&mut self) -> webui::HandlerResult<()> { Ok(()) }
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let protocol_bytes = fs::read("./dist/protocol.bin").unwrap();
let protocol = Protocol::from_protobuf(&protocol_bytes).unwrap();
let protocol = web::Data::new(protocol);
HttpServer::new(move || {
App::new()
.app_data(protocol.clone())
.route("/{path:.*}", web::get().to(|proto: web::Data<Protocol>, req: HttpRequest| async move {
let state = json!({ "title": "Home" });
let mut writer = StringWriter(String::new());
let handler = WebUIHandler::new();
let options = RenderOptions::new("index.html", req.path());
handler.render(proto.get_ref(), &state, &options, &mut writer).unwrap();
HttpResponse::Ok().content_type("text/html").body(writer.0)
}))
})
.bind("127.0.0.1:3000")?
.run()
.await
}
use axum::{routing::get, Router, extract::{State, Request}};
use webui::{Protocol, WebUIHandler, RenderOptions, ResponseWriter};
use serde_json::json;
use std::{fs, sync::Arc};
struct StringWriter(String);
impl ResponseWriter for StringWriter {
fn write(&mut self, content: &str) -> webui::HandlerResult<()> {
self.0.push_str(content);
Ok(())
}
fn end(&mut self) -> webui::HandlerResult<()> { Ok(()) }
}
#[tokio::main]
async fn main() {
let protocol_bytes = fs::read("./dist/protocol.bin").unwrap();
let protocol = Arc::new(Protocol::from_protobuf(&protocol_bytes).unwrap());
let app = Router::new()
.route("/{*path}", get(|State(proto): State<Arc<Protocol>>, req: Request| async move {
let state = json!({ "title": "Home" });
let mut writer = StringWriter(String::new());
let handler = WebUIHandler::new();
let options = RenderOptions::new("index.html", req.uri().path());
handler.render(proto.as_ref(), &state, &options, &mut writer).unwrap();
axum::response::Html(writer.0)
}))
.with_state(protocol);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
use hyper::{server::conn::http1, service::service_fn, body::Bytes, Request, Response};
use hyper_util::rt::TokioIo;
use http_body_util::Full;
use webui::{Protocol, WebUIHandler, RenderOptions, ResponseWriter};
use serde_json::json;
use std::{fs, sync::Arc};
struct StringWriter(String);
impl ResponseWriter for StringWriter {
fn write(&mut self, content: &str) -> webui::HandlerResult<()> {
self.0.push_str(content);
Ok(())
}
fn end(&mut self) -> webui::HandlerResult<()> { Ok(()) }
}
#[tokio::main]
async fn main() {
let protocol_bytes = fs::read("./dist/protocol.bin").unwrap();
let protocol = Arc::new(Protocol::from_protobuf(&protocol_bytes).unwrap());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
loop {
let (stream, _) = listener.accept().await.unwrap();
let proto = protocol.clone();
tokio::spawn(async move {
http1::Builder::new()
.serve_connection(TokioIo::new(stream), service_fn(move |req: Request<_>| {
let proto = proto.clone();
async move {
let state = json!({ "title": "Home" });
let mut writer = StringWriter(String::new());
let handler = WebUIHandler::new();
let options = RenderOptions::new("index.html", req.uri().path());
handler.render(proto.as_ref(), &state, &options, &mut writer).unwrap();
Ok::<_, hyper::Error>(Response::new(Full::new(Bytes::from(writer.0))))
}
}))
.await
.ok();
});
}
}
Owned partial-navigation responses #
Protocol::render_partial(state, entry, path, inventory) returns JSON with
state projected to the active components. For direct serialization to response
bytes or a writer, call Protocol::prepare_partial(state, entry, path, inventory).
It consumes the owned serde_json::Value and returns a serializable
PartialNavigation with the same projection policy. Check is_match() when
choosing a response status, then serialize it once with serde_json::to_vec or
serde_json::to_writer. Unknown component requirements retain full state for
correctness, so render state must contain only client-safe data.
Use Protocol::matches_route(entry, path) when only route existence is needed.
Router-aware request helper #
Use webui::server::serve_request when one endpoint serves both initial HTML
documents and webui-delivery JSON partials. Build the ServeRequest with the
complete RenderOptions value for that HTTP response:
use webui::{
server::{serve_request, ServeRequest, ServeResponse},
RenderOptions,
};
let options = RenderOptions::new("index.html", request_path)
.with_nonce(csp_nonce);
let request = ServeRequest::new(
options,
accepts_json,
inventory_header,
);
match serve_request(&protocol, &handler, state, &request)? {
ServeResponse::Html(html) => send_html(html),
ServeResponse::Json(json) => send_json(json),
}
For full documents, the helper forwards all render options, including the nonce for generated inline scripts. Use a fresh nonce per document and send the same value in the Content Security Policy header. JSON partials use the entry, request path, and client inventory; they do not emit document scripts.
Streaming SSR #
webui::streaming::StreamingWriter coalesces small writes, sends them over a
bounded tokio::mpsc channel for backpressure, and can recycle buffers through
a shared ChunkPool. You can use it with WebUIHandler::render for transport
streaming. To make authored <boundary> checkpoints hydrate before the
response completes, call the opt-in WebUIHandler::render_streaming API shown
below. It commits every boundary as final. Use stream_response when backend
readiness controls checkpoint timing or an island needs later server state.
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use tokio::sync::{mpsc, Semaphore};
use tokio_stream::StreamExt;
use webui::streaming::{ChunkPool, StreamingWriter};
use webui::{WebUIHandler, RenderOptions, ResponseWriter};
// One shared pool per server (constructed at startup, lives forever).
let chunk_pool = Arc::new(ChunkPool::new(
256, // ~1.25 MiB peak pool memory
StreamingWriter::CHUNK_TARGET + 1024,
));
let render_permits = Arc::new(Semaphore::new(4));
// Per request:
// Acquire before `spawn_blocking`; its internal queue is not an admission limit.
let render_permit = match Arc::clone(&render_permits).try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
return HttpResponse::ServiceUnavailable()
.insert_header(("Retry-After", "1"))
.body("streaming render capacity is temporarily exhausted");
}
};
let (tx, rx) = mpsc::channel::<Bytes>(StreamingWriter::DEFAULT_CHANNEL_CAPACITY);
actix_web::rt::task::spawn_blocking({
let chunk_pool = Arc::clone(&chunk_pool);
move || {
let _render_permit = render_permit;
// `with_flush_timeout` bounds the slow-loris DoS surface to
// `30s × concurrent_renders`. `end()` returns the typed error
// from the final flush. Log truncated streams at debug.
let mut writer = StreamingWriter::new_pooled(tx, chunk_pool)
.with_flush_timeout(Duration::from_secs(30));
let options = RenderOptions::new("index.html", &request_path)
.with_nonce(&csp_nonce)
.with_body_inject(&livereload_script); // per-request inject
if let Err(e) = handler.render_streaming(&proto, &state, &options, &mut writer) {
log::error!("render failed: {e}");
if let Err(flush_error) = ResponseWriter::end(&mut writer) {
log::debug!("stream truncated: {flush_error}");
}
}
}
});
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.streaming(tokio_stream::wrappers::ReceiverStream::new(rx).map(Ok::<_, actix_web::Error>))
Host-driven boundaries and state updates #
stream_response returns a synchronous session that discovers runtime
occurrences as it renders:
use webui::{BoundaryMode, RenderOptions, WebUIHandler};
let options = RenderOptions::new("index.html", "/");
let mut response = handler.stream_response(&protocol, &options, &mut writer)?;
let mut step = response.start(initial_state)?;
while !step.done {
step = match step.boundary.as_ref() {
Some(boundary) => {
let state = load_state(
&boundary.owner,
&boundary.name,
boundary.key.as_ref(),
)?;
response.resume(
boundary.instance_id,
state,
BoundaryMode::Final,
)?
}
None => response.advance()?,
};
}
start writes the shell prefix through the first descriptor, or completes
immediately when the selected path has none. resume must use the currently
pending BoundaryInstanceId and writes only that occurrence through its
checkpoint. Its result normally has no descriptor and done == false.
advance writes the following parent or shell bytes until the next descriptor
or terminal. Flush the resumed occurrence before waiting for more data.
The status states are exact: a descriptor requires resume; no descriptor with
done == false requires advance; done == true completes the response. The
completed status has no descriptor, and the writer already contains the tail
and terminal.
WebUIHandler::render_streaming borrows one state value for the complete
response. Use stream_response to supply newly resolved state at each
occurrence. Move freshly loaded
state into start and resume when the caller no longer needs it; pass &Value
only when retaining caller ownership. When no state
changed, resume_current skips that overlay while retaining the checkpoint
pause before advance.
Every descriptor contains instance_id, declaration_id, owner, name, and
an optional string or numeric key. A component-owned declaration reached from
multiple static callsites in one entry traversal requires a key, and
simultaneously live keys must be unique. A boundary-bearing subtree under
<for> is rejected with boundary-in-repeat; a complete <for> may instead be
inside one boundary.
To send later state, resume the occurrence as BoundaryMode::Updatable, retain
its instance ID, then call:
response.update(search_instance, &json!({ "query": "webui" }))?;
update accepts an object patch, emits a projected markerless state record, and
flushes immediately. It is valid between the occurrence's resume and
advance, inserts no markup, and does not rerun hydration.
The session accepts owned state or borrows state only for its call. It does not await,
allocate a task, or synchronize concurrent callers. An async server should use a
bounded command channel and one admitted blocking worker that owns the session
and StreamingWriter; examples/app/streaming is the reference implementation.
The public writer contract is:
pub trait FlushWriter: ResponseWriter {
fn flush(&mut self) -> HandlerResult<()>;
}
render_streaming and stream_response accept a FlushWriter;
StreamingWriter implements that trait. resume flushes immediately after the
occurrence's hydration checkpoint. The matching advance separately flushes
the following parent bytes through the next descriptor or terminal. Generated
component span completions, state updates, and terminal records also flush. The
normal render method still accepts any ResponseWriter.
The entry template must load its application module with an early
<script type="module" async> in <head>, before boundary content. See
Progressive Streaming Hydration
and the
<boundary> directive for the
authoring and lifecycle contract. That application entry must import
@microsoft/webui-framework/streaming.js before component registration
modules. The default framework entry does not include the streaming coordinator.
At start, WebUI freezes only projected top-level keys required to continue,
plus lexical locals and route/component scope. Resume state overlays that frozen
parent surface. Resolution order is lexical locals, resume state, then frozen
parent state.
The browser can hydrate a completed child boundary before its parent's tail
arrives, in Light or open Shadow DOM. Use hydratedCallback() for setup that
requires that component's bindings and refs.
The bounded channel limits bytes retained by a running render, but it does not
bound how many requests can queue in Tokio's blocking pool. Acquire a
process-wide permit with try_acquire_owned() before spawn_blocking, return
HTTP 503 with Retry-After when saturated, and move the permit into the closure
so it is held for the render's full lifetime.
FlushWriter::flush means all currently buffered bytes were handed to the HTTP
transport. It cannot force an HTTP adapter, compressor, reverse proxy, or CDN to
deliver them immediately. Disable response buffering where applicable and test
the production delivery path. Checkpoints are strictly in document
order.
Per-request HTML injection #
with_head_inject / with_body_inject splice host-provided HTML at the
parser-synthesized head_end / body_end structural boundaries. They cannot
mis-fire on </head> / </body> literals appearing inside HTML comments,
<iframe srcdoc>, or inline <script>. Typical uses include per-request
<link rel="preload"> hints, a development livereload script, and OpenTelemetry
trace IDs.
Safety: the HTML is written verbatim, no escaping. Untrusted input is a direct XSS vector. Pre-escape with
webui_handler::encode_safe(re-exported for this purpose) if your content path may include user data.
Reserved $webui state channel #
A reserved top-level "$webui" object in the render state carries the same
boundary HTML without a Rust-only builder, so non-Rust hosts get the capability
through the state JSON they already send:
{
"$webui": {
"headEnd": "<link rel=\"preload\" as=\"image\" href=\"/hero.avif\">",
"bodyStart": "<!-- after <body> -->",
"bodyEnd": "<script src=\"/livereload.js\"></script>",
"assetBase": "https://cdn.example.com/b123/"
}
}
Every member is optional. The HTML members must be strings; anything else is
ignored rather than an error. The key is stripped from the hydration payload,
so it never reaches the client state. headEnd is emitted after
with_head_inject, and bodyEnd is emitted after with_body_inject.
bodyStart has no corresponding RenderOptions injection.
assetBase overrides the build's BuildOptions::asset_base for this response:
stylesheet links are prefixed with it, the document head carries it as
<meta name="webui-asset-base">, and the browser receives it to resolve
stylesheet and lazy pack paths. Module preload hints keep their paths, because
they name the application's own scripts. null keeps the build default. Any
other value must pass webui::validate_asset_base; otherwise rendering fails
with HandlerError::InvalidState before any output is written.
Safety: HTML values are written verbatim with no escaping, exactly like
with_head_inject. Never let request-derived data reach$webui.
Typed streaming errors #
StreamingWriter returns HandlerError::ClientDisconnected (receiver dropped)
or HandlerError::StreamTimeout (flush deadline exceeded) from writes,
boundary flushes, and the final end(), so callers can distinguish a completed
delivery from a cancelled or stalled stream.
API Reference #
Build #
| Function | Description |
|---|---|
build(options) | Build templates into a protocol. Returns BuildResult |
prepare_build(options) | Compile once and retain a PreparedBuild across client bundling; finish(manifests) consumes it and returns BuildResult |
build_to_disk(options, out_dir) | Build and write protocol.bin, CSS files, and lazy packs to out_dir, and component ESM inputs, lazy.webui.js, and lazy.webui.d.ts to modules_out (default out_dir) |
inspect(path) | Read a protocol file and return JSON |
inspect_bytes(bytes) | Convert protocol bytes to JSON |
BuildOptions #
| Field | Type | Default | Description |
|---|---|---|---|
app_dir | PathBuf | - | Path to app folder |
entry | String | "index.html" | Entry file |
css | CssStrategy | Link | CSS delivery: Link, Style, or Module |
dom | DomStrategy | Shadow | Fallback for unwrapped components: Shadow or global Light |
plugin | Option<Plugin> | None | Parser plugin (see Plugins for the available identifiers) |
components | Vec<String> | [] | External component sources |
component_asset_roots | Vec<String> | [] | Root component tags emitted as static .webui.js ESM assets |
metafile | bool | false | Produce BuildResult::metafile: the component asset graph and the lazyPacks report, when the build emits either. Also measures each pack's brotli_bytes |
component_modules | BTreeMap<String, String> | {} | Module specifiers keyed by custom element tag, for components without a usable .ts or .js sibling. Written verbatim in lazy.webui.js; checked by webui::validate_component_module |
modules_out | Option<PathBuf> | None | Directory for generated modules; relative specifiers in lazy.webui.js start here, at app_dir when None |
projection_manifests | Vec<ProjectionManifestSource> | [] | Disk, inline, or prepared projection fragments; empty preserves full state |
css_file_name_template | String | "[name].[ext]" | Emitted filename template for Link-mode CSS. Tokens: [name], [hash], [ext] |
asset_base | Option<String> | None | Public URL or path ending in / that maps to the build output. Stored in the protocol; requests override it with $webui.assetBase. Checked by webui::validate_asset_base |
theme | Option<TokenFile> | None | Loaded design-token theme used to validate unresolved CSS tokens during build |
Unwrapped components default to generated open Shadow roots. Set
DomStrategy::Light to make unwrapped components global Light DOM; authored
sole open Shadow roots remain Shadow in either mode. Light CSS uses ordinary
selectors, and :host, :host-context, and ::slotted fail with
unsupported-light-css.
BuildResult::component_asset_files contains stable version 4 ESM inputs: one
module per asset-owned component plus a thin root entry with static imports for
its closure. Entry-reachable dependencies remain in the protocol as external
prerequisites. Asset-only protocol records are pruned after the files are
rendered. Pass the generated inputs to the application bundler, which owns final
splitting, hashes, public paths, caching, and delivery. Component assets cannot
be combined with <route>.
Set metafile: true to populate BuildResult::metafile when the build emits
component assets or lazy packs. Its inputs and outputs use esbuild's
metafile format, and its lazyPacks array lists every pack, as described in
Build metafile:
let result = webui::build(BuildOptions {
app_dir: "src".into(),
plugin: Some(Plugin::WebUI),
component_asset_roots: vec!["settings-dialog".into(), "mail-thread".into()],
metafile: true,
..BuildOptions::default()
})?;
if let Some(metafile) = result.metafile {
std::fs::write("dist/component-assets-meta.json", metafile)?;
}
Root outputs in the metafile have entryPoint records and static
import-statement edges to component inputs. build_to_disk() validates
protocol.bin, CSS files, component assets, lazy.webui.js, and
lazy.webui.d.ts as one output set before writing, so filename collisions fail
without leaving partial output.
Component input publication is shared with the CLI through
webui::component_asset_output. publish() writes immutable dependencies before
stable roots and preserves unchanged input modification times. publish_with()
also runs a caller's atomic output finalizer inside the asset rollback boundary,
and publish_modules_with() also publishes generated modules such as
lazy.webui.js, each with its declaration, as stable roots. Serialize
publishers targeting one directory.
Publication, including build_to_disk(), overwrites current stable roots but
does not delete older generated payloads or unrelated files. If your pipeline
requires a clean output, remove and recreate its disposable build directory
before calling WebUI.
Load themes with webui::resolve_theme_path() and webui::load_token_file().
When theme is set, missing required CSS tokens fail as parser diagnostics
before the protocol is returned. Tokens used only with a literal var()
fallback (e.g. var(--brand, #000)) are exempt; if such a token is also absent
from every theme it is reported as a non-fatal advisory in
BuildResult::warnings (a likely typo) instead of failing the build.
When generated modules must exist before client bundling, call
prepare_build(options) and prepared.write_modules() first. It writes to
modules_out, or app_dir when omitted, with the shared transactional publisher.
The lazy_scripts_module(), component_asset_files(), and lazy_pack_files()
accessors also support caller-owned publication or virtual bundler inputs.
After the client bundle completes, call
prepared.finish(vec![manifest_path.into()]). This validates completed manifests
and serializes the retained template/CSS snapshot without recompilation. Sources
are merged with any given during preparation; an empty set keeps full state.
The handle is consumed even on failure. Start a new preparation after editing
templates or styles. BuildStats::duration excludes host work between phases.
Use ProjectionManifestSource::Path for normal builds. Orchestrators that build
many protocols against one client bundle can call
prepare_projection_manifests() once and reuse
ProjectionManifestSource::Prepared. Every non-empty source set is
hash-validated, merged by tag, and required to cover every compiled scripted
component.
BuildStats #
| Field | Type | Description |
|---|---|---|
duration | Duration | Build time |
fragment_count | usize | Total fragments |
component_count | usize | Components registered |
css_file_count | usize | CSS files produced |
protocol_size_bytes | usize | Protocol binary size |
token_count | usize | CSS tokens discovered |
RenderOptions #
| Field / builder | Type | Description |
|---|---|---|
RenderOptions::new(entry_id, request_path) | constructor | Entry fragment + route-matching path |
with_nonce(&str) | builder | CSP nonce reflected onto inline <script> tags (including the <script type="importmap"> tags that register Module-strategy CSS). Empty string normalises to None. |
with_head_inject(&str) | builder | Raw HTML emitted immediately before </head> at the parser's structural boundary (see Streaming SSR). |
with_body_inject(&str) | builder | Raw HTML emitted immediately before </body>. Same structural-boundary contract. |
Router-aware server requests #
| API | Description |
|---|---|
ServeRequest::new(render_options, accept_json, inventory_hex) | Store the complete borrowed render configuration and the client's partial-navigation metadata without a heap allocation |
serve_request(protocol, handler, state, request) | Inject route parameters, then return either a full ServeResponse::Html document rendered with the supplied options or a ServeResponse::Json partial |
Protocol::render_partial(state, entry_id, request_path, inventory_hex) | Consume parsed Rust state and move its selected values into a complete JSON partial without a serialize/reparse cycle |
Protocol::prepare_partial(state, entry_id, request_path, inventory_hex) | Prepare the same projected response for direct serialization; inspect is_match() before sending |
Protocol::render_partial_json(state_json, entry_id, request_path, inventory_hex) | Validate and project serialized state without materializing a duplicate state tree |
Host-driven streaming #
| API | Description |
|---|---|
WebUIHandler::stream_response(protocol, options, writer) | Create one progressive response session |
StreamingResponse::start(state) | Borrow or move state, then render and flush through the first runtime occurrence or terminal |
StreamingResponse::resume(instance_id, state, mode) | Borrow or move a state overlay, then flush only the pending occurrence |
StreamingResponse::resume_current(instance_id, mode) | Commit with retained state and preserve the checkpoint pause |
StreamingResponse::advance() | Render following parent bytes through the next occurrence or terminal |
StreamingResponse::update(instance_id, patch) | Send projected object state to a committed updatable occurrence |
StreamingResponse::is_done() | Report whether terminal and writer end completed |
StreamingResponse borrows the writer for the response's lifetime and avoids
returning a separate byte buffer for each call.
When you would rather own the bytes - for example to feed a channel, a test
harness, or a transport whose writer cannot be borrowed for that long —
StreamingSession offers the same step machine and returns a Vec<u8> per
call instead. Its owned-state variants avoid copying freshly loaded values:
let mut session = StreamingSession::new(
Arc::clone(&handler),
Arc::clone(&protocol),
SessionOptions::new("index.html", "/"),
)?;
let mut step = session.start(initial_state)?;
loop {
sink.send(std::mem::take(&mut step.bytes))?;
if step.done {
break;
}
step = match step.boundary.as_ref() {
Some(boundary) => {
let state =
load_state(&boundary.owner, &boundary.name, boundary.key.as_ref())?;
session.resume(boundary.instance_id, state, BoundaryMode::Final)?
}
None => session.advance()?,
};
}
The session holds its own Arc clones, so it may outlive the bindings you
created it from. start and resume accept either owned Values or borrowed
state: moving freshly decoded or loaded values avoids clones of changed
subtrees, while borrowing lets shared-state callers retain ownership. Equal
values keep the prior state-reference base. If the host already knows no state
changed, resume_current also avoids the equality walk. Every resume form still
returns immediately after the checkpoint flush; advance remains a separate
call after any async wait.
This is the same type Node, WASM, C, and C# drive, so behaviour is identical
across hosts. Prefer stream_response in Rust servers: it writes straight into
the writer and avoids the per-chunk buffer.
HandlerError variants #
| Variant | When |
|---|---|
ClientDisconnected | Streaming receiver dropped; caller should abort the render. |
StreamTimeout | with_flush_timeout deadline exceeded; ops should alert on slow-loris patterns. |
MissingFragment(String) | entry_id not found in the protocol. |
TypeError(String) / Evaluation(String) | Template/expression runtime errors. |