DocsServer features
RPC & uploads
A Rust function the browser can call by name, beside the page that calls it. Typed arguments, typed returns, CSRF protection by default, server streaming, and uploads with progress.
An rpc answers once, and an RpcStream answers in pieces. When both sides need to speak for as long as the page is open, that is a WebSocket.
Placement and dispatch
The browser posts to the page URL it is currently on, with a header naming the function. The generated router dispatches page-owned names first, then falls through to the global component registry.
| Where the call happens | Where the #[rpc] goes |
|---|---|
| A page | The calling page.rs. |
| An application component | src/components/<component>.rs. |
| A library component | Beside the library component. |
| A layout, error, not-found or route.rs | Nowhere — expose an ordinary HTTP method from route.rs instead. |
Page RPCs are reachable only on their own page URLs, so two different pages may reuse a name. Component RPC names are application-wide, because a component can render on any page: they must be unique across everything linked, and cannot collide with a page RPC name.
The Rust side
// src/app/greeter/page.rs — beside the page that calls it.
use crate::rahti::rpc;
#[rpc]
pub async fn greet(name: String) -> Greeting {
Greeting {
text: format!("Hello, {name}."),
}
}#[rpc]takesauth, or nothing.#[rpc(auth)]answers 401 unless the browser carries a session. There is no other argument, and in particular no role.- functions may be sync or async, but cannot be methods or generic;
- parameters need plain names and owned, deserializable types —
String, not&str; - the payload key must match the Rust parameter name;
- return a serializable value, or
rahti::Result<T>; Option<T>accepts an absent or null argument;- the original function stays callable from Rust.
const result = await pp.rpc("greet", { name });Successful values resolve from JSON. An Err(Error) becomes an HTTP status plus a JSON error message, and the Promise rejects with a RpcError. Its status, errors, requestId, and body expose the status, validation fields, optional correlation id, and full parsed response. For 401 and 403 the client uses stable messages while preserving the response in body.
use crate::rahti::{Error, Result, rpc};
use axum::http::StatusCode;
#[rpc]
pub async fn note(id: u32) -> Result<Note> {
let note = store::find(id)
.await?
.ok_or_else(|| Error::new(StatusCode::NOT_FOUND, "no such note"))?;
Ok(note)
}Errors from below
rahti::Error implements From<E> for every E: std::error::Error, so a sea_orm::DbErr crosses ? inside rahti::Result<T> with no conversion written anywhere.
// `rahti::Error` implements `From<E>` for every `E: std::error::Error`, so
// a database error crosses `?` with no conversion written anywhere.
#[rpc]
pub async fn list() -> Result<Vec<todo::Model>> {
Ok(todo::Entity::find().all(db()).await?)
}Calls checked at compile time
html! checks every pp.rpc call in a template's client code — component scripts, handlers and bindings — against the #[rpc] it names. A misspelled name or payload key fails cargo check instead of answering 404 or 400 in the browser. The name resolves through the Rust module the template is written in, which is why the rpc lives in the same file as its caller.
// Beside `#[rpc] pub async fn rename(id: i32, name: String, note: Option<String>)`
// in the same page.rs, each of these fails `cargo check`:
pp.rpc("renam", { id, name }); // no such rpc; rustc suggests `rename`
pp.rpc("rename", { id, nmae }); // `rename` has no parameter `nmae`
pp.rpc("rename", { id }); // this call does not send `name`
pp.rpc(which, { id, name }); // the name must be a string literal
pp.rpc("rename", { id: 1, name: 12 }); // `name` expects a String
// Branch between rpcs with one literal call per branch.
editing ? pp.rpc("update", { id, name }) : pp.rpc("create", { name });| Payload | What is checked |
|---|---|
| An object literal | Every key is a parameter, and every required parameter is present. Option<T>, Option<RpcFile> and Vec<RpcFile> are optional. |
A payload the script builds — a helper's result, a const object, a spread of either | Followed to its literals: every required parameter is present. The keys it brings are not checked one by one. |
| A literal with a spread that cannot be followed, or a computed key | The written keys only; missing keys are not reported. |
| No payload | The rpc has no required parameters. |
Anything else — FormData, a variable or a call that cannot be followed | The name only. |
Payloads built in the script
A script that calls several rpcs usually writes their shared keys once. A payload built that way is followed back to the object literals it is made of, so a required parameter none of them supplies is refused at the call.
// One helper serves several calls. Each payload is followed to the literals
// it is made of, so every key that is sent is known.
function ids() {
return { project_id: projectId, instance_id: serviceId() };
}
const filter = { status: "open" };
pp.rpc("list_events", { ...ids(), ...filter, page });
pp.rpc("load_service", ids());
// Misspell `instance_id` inside ids() and every call that relies on it fails:
// error: rahti[RAHTI_RPC_MISSING_ARGUMENT]: this call to `load_service`
// does not send `instance_id`, which it requires.What is followed: a function called with no arguments that is declared once, is not async, and ends in its one return of an object literal; a const object that nothing names except as a payload, a spread or a field read; and spreads of either, to any depth. A let, an object given a field afterwards, one handed to a function, and anything declared outside the script are not followed.
A key that arrives through a spread or a variable is not required to be a parameter. One helper often serves rpcs that take different subsets of its keys, and the server ignores a key an rpc does not declare. Only a key written in the call itself is refused when the rpc has no such parameter.
A closed object literal also catches obvious value-shape mismatches against standard Rust types — strings, booleans, numbers, vectors and their Option wrappers — so name: 12 cannot satisfy name: String. String values pass, because a form field can carry JSON text. Variables are not type-checked, and of a call's result only the reads under Response reads and State reads are.
In a binding or handler the error lands on the offending token. A <script> body is one Rust string literal, which a compiler error cannot point inside, so its errors point at the script's first character and name the line of the call.
Wire shapes
The build reads each #[rpc]'s parameter and return types from source and writes the JSON they become as TypeScript, Serde attributes included. The result is in .rahti/manifest.json, so whoever writes the caller — you or a coding agent — reads the exact keys instead of opening the struct.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Saved {
pub contact_id: i32,
pub tags: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
#[rpc]
pub async fn save(name: String, note: Option<String>) -> Result<Saved> {
// ...
}"rpcContracts": [{
"name": "save",
"file": "src/app/contacts/page.rs",
"payload": {
"typescript": "{ name: string; note?: string | null }",
"schemaStatus": "resolved"
},
"response": {
"rustType": "Saved",
"typescript": "Saved",
"schemaStatus": "resolved"
}
}],
"rpcTypes": {
"src/app/contacts/page.rs": {
"Saved": "{ contactId: number; tags: string[]; note?: string | null }"
}
}The caller reads result.contactId, not result.contact_id: the shape is what Serde writes, not what the struct spells. Each contract in rpcContracts carries its payload and response shapes, and rpcTypes holds the named declarations per file. A type name is unique within its file, not across files.
A type is followed through the file's own items, its use declarations, crate:: and super:: paths, and module files, to a struct, enum or type alias that derives Serialize (a response) or Deserialize (a parameter). Renames, skips, flatten, transparent and every enum tagging are applied, and generic types keep their parameters.
| Rust | TypeScript |
|---|---|
String, &str, dates and times, Uuid, Decimal | string |
| Integers and floats | number |
bool | boolean |
() | null |
Option<T> | T or null |
Vec<T>, arrays, sets | T[] |
HashMap<K, V>, BTreeMap<K, V> | Record<string, V> |
| Tuples | [A, B] |
serde_json::Value | unknown |
RpcFile, RpcUpload | File |
Every shape carries a schemaStatus saying how much of it the source accounted for.
| Status | Meaning |
|---|---|
resolved | Every part was followed to a definition or a known type. |
partial | Some part is unknown: a type from another crate, a hand-written Serialize, or a with field. |
unresolved | Nothing about the type could be read. |
dynamic | JSON of any shape, such as serde_json::Value. |
stream | An RpcStream, whose events no type declares. |
Response reads checked at compile time
A component script that holds an awaited result in a variable has every field it reads off that variable checked against the rpc's response shape. A field the response does not have fails cargo check instead of reading undefined in the browser.
// `save` answers Saved = { contactId: number; tags: string[]; owner: Contact | null }
const result = await pp.rpc("save", { name });
result.contactId; // checked: a field of Saved
result.owner?.name; // checked through `| null`, into Contact
result.tags[0].trim(); // checked up to `tags`; a string's members are not
result.contact_id; // refused: Saved has no field `contact_id`
const { tags, total } = await pp.rpc("save", { name }); // `total` is refusederror: rahti[RAHTI_RPC_RESPONSE_FIELD]: `save` answers `Saved`, which has no field `contact_id` (line 42).
Its fields are `contactId`, `owner`, `tags`. The shape is the JSON Serde writes, not the Rust
spelling: see this rpc's `response` in `.rahti/manifest.json`.It is the JSON Serde writes that is checked, so a response with rename_all = "camelCase" is read as contactId, and renaming a field in Rust is a compile error in every script that still reads the old name.
A read is refused only when the value is an object whose every field is known and the name is not one of them. Everything else is left alone:
| Left alone | Why |
|---|---|
| A result returned, handed to a function, or passed down a longer promise chain | Only const x = await pp.rpc(…), the same through a helper, a destructuring of either, and the parameter of the call's own .then are certainly the response. A result stored in state is checked under State reads. |
| A variable assigned again, or given fields | result.extra = …, Object.assign(result, …) and delete change what it has. |
length, map, trim and a computed key | What an array, a string or a number answers to is JavaScript's, and result[key] is only known at run time. |
| A shape that is not fully known | unknown, a flattened map, a stream, or a type the build could not follow. |
| Bindings and handlers | Neither holds an awaited result. |
To read a field the shape does not declare, read it through another variable: const loose = result; loose.anything.
Through a helper, and in .then
A result that comes back through a helper of the script's own is checked the same way. A helper is a function the script declares that returns what its callback returns, or an empty value, and nothing else. The first parameter of a .then callback written on the call is the response too.
// A helper of the script's own that returns what its callback returns.
async function act(request) {
setBusy(true);
try {
return await request();
} catch (error) {
setFailure(error.message);
return null;
} finally {
setBusy(false);
}
}
const result = await act(() => pp.rpc("save", { name }));
result.contact_id; // refused, as if it were awaited directly
// The parameter of the call's own .then is the response too.
pp.rpc("save", { name }).then((saved) => show(saved.contact_id)); // refusedA helper that returns anything else — a fallback object, the result after another call, a variable the result was put in — is not followed, and neither is a callback that does more than return the one call. Only the first .then on the call is handed the response; a second one, .catch and .finally are not.
State reads checked at compile time
A pp.state value has no declared type, but a state that is only ever given one rpc's response holds that response. Every field read off it is then checked against the response's shape: in the script, in a binding, in a handler, and in the rows of a pp-for over it.
html! {
<section>
<p hidden={domains.length > 0}>"No domains yet."</p>
<ul>
<template pp-for="domain in domains">
<li key={domain.id}>
{domain.name}
<template pp-for="record in domain.records">
<span key={record.kind}>{record.value}</span>
</template>
</li>
</template>
</ul>
<script>r##"
// `domains` is only ever given what `list_domains` answers.
const [domains, setDomains] = pp.state([]);
async function load() {
setDomains(await pp.rpc("list_domains", {}));
}
pp.effect(() => { load(); }, []);
"##</script>
</section>
}error: rahti[RAHTI_STATE_FIELD]: `domain` has no field `nmae`: the state `domains`
only ever holds what `list_domains` answers.
Its fields are `id`, `name`, `records`. The shape is the JSON Serde writes,
not the Rust spelling: see that rpc's `response` in `.rahti/manifest.json`.
|
| <li key={domain.id}>{domain.nmae}</li>
| ^^^^Renaming a field in the Rust struct is a compile error in every row that still reads the old name. A state has a shape when everything the block puts into it is one of these, and every such value has the same shape:
| Given | For example |
|---|---|
| An awaited call, or a result a helper hands back | setRows(await pp.rpc(…)) |
| A variable holding such a result, or a part of one | setRows(page.rows), setOwner(page.owner) |
The setter handed to the call's own .then | pp.rpc(…).then(setRows) |
| An empty value, which contradicts nothing | [], null, undefined, an empty string, as the initial value or in a setter call |
| Either branch of a conditional | When both are one of the above. |
A state has no shape, and none of its reads are checked, when any one of these is true:
| No shape when | Why |
|---|---|
| Its setter is called with anything else | An object or array literal, a spread, a .map(…), an updater function, an event value, another state. |
| Its setter is named without being called | Passed to a function, forwarded to a component, handed to a second .then. |
| A field is written on it or on one of its rows in place | rows[0].open = true changes what it holds. |
| The block has no script, or more than one | There is no one set of states. |
To keep fields of your own beside the response's, give the state a value built in the script, as in setDomains(list.map(withOpenFlag)). That state has no shape and every read of it compiles. A field name the block assigns anywhere is never refused on any value, because a value reached through a callback can be given that field in place.
A state that starts from a server value
A state usually starts from data the page already loaded and is reloaded by an rpc. It holds the server value until the rpc answers, and the response after. A field read off it is refused when neither has it: the response, whose shape html! knows, and the server value, whose struct the compiler knows. The two need not be the same Rust type. A field only one of them has is not refused.
A state given nothing but the server value it starts from is checked as a server value is: every field, against the struct it is made of.
Loop rows
A row has a shape when its collection comes from a shaped state, or from an outer row, through steps that cannot change what the rows are: a path, a fallback to an empty value, a choice whose branches agree, an array method that returns the same elements, or a script function called with no arguments whose every return is made of those steps.
// Rows keep the state's shape through steps that cannot change what they are.
function shown() {
const all = domains || [];
if (!query) return all;
return all.filter((domain) => domain.name.includes(query));
}
// <template pp-for="domain in shown()"> checked
// <template pp-for="domain in domains ?? []"> checked
// <template pp-for="record in domain.records"> checked, inside a row
// <template pp-for="label in domains.map(name)"> not checked: built, not pickedServer value reads
A script also takes server values that are not state: data rendered once with the page and never reloaded. No rpc gives them a shape, and nothing has to be written for them to have one. The build reads the application's structs, the compiler knows the type of the value, and each field read off a top-level const that is a server value — in the script, in a binding, and in the rows of a loop over it — is checked against the struct the value is made of.
// The struct is public, so the build gives it a shape.
#[derive(Serialize)]
pub struct Project {
pub id: i32,
pub name: String,
pub databases: Vec<Database>,
}
pub async fn page() -> Html {
let projects = crate::services::projects::list().await;
html! {
<ul>
<template pp-for="project in projects">
<li key={project.id}>{project.name}</li>
</template>
<script>r##"
// Not state: rendered once with the page.
const projects = @{Json(&projects)};
"##</script>
</ul>
}
}error[E0277]: rahti[RAHTI_SERVER_VALUE_FIELD]: `project` has no field `nmae`: it comes
from the server value `projects`, whose Rust struct has no such field
|
| <li key={project.id}>{project.nmae}</li>
| ^^^^ `Missing<Project__id__name__databases>` names
| the struct this is, then its fieldsThe value may be the struct, a Vec, a slice or an Option of it, owned or borrowed, with or without Json. Each field of a read is checked on its own, so the error names the step that failed. A struct is checked when all of these hold:
| The struct | Why |
|---|---|
Derives Serialize, has named fields, and is not generic | Its JSON is what its fields say. |
Is pub or pub(crate), and so is every module on the way to it | The shapes live in one generated module, which has to be able to name the struct. A module declared in the crate root, and a page's own file, may be private. |
Is not behind a #[cfg] | Nor is a module above it. |
The shapes live in a module that rahti::shapes!() expands to at the end of the generated src/routes.rs. It is regenerated with the routes; never edit it, and do not name it from application code.
Client options
pp.rpc(name, data?, optionsOrAbort?). Passing true as the third argument is shorthand for { abortPrevious: true }.
| Option | Purpose |
|---|---|
| abortPrevious | Cancels the previous active call. The typeahead option. |
| url / csrfUrl | Override the endpoint and the CSRF source. The default URL is the current route. |
| credentials | The fetch credentials mode. |
| onStream / onStreamError / onStreamComplete | Server-streaming callbacks. |
| onUploadProgress / onUploadComplete | Upload progress callbacks. |
// The third argument is options, or `true` as shorthand for
// { abortPrevious: true }.
const results = await pp.rpc("search", { term }, true);
const saved = await pp.rpc("save", { text }, {
abortPrevious: false,
onUploadProgress: ({ percent }) => setPercent(percent ?? 0),
});If onStreamError is supplied, PulsePoint calls it for a failed request or stream instead of rejecting the outer Promise. Handle the failure in that callback.
Server streaming
Return an RpcStream to produce an event stream.
use crate::rahti::{RpcStream, rpc};
#[rpc]
pub async fn count(to: u32) -> RpcStream {
RpcStream::from_iter(1..=to)
}await pp.rpc("count", { to: 5 }, {
onStream: (value) => append(value),
onStreamError: (error) => showError(error),
onStreamComplete: () => finish(),
});| Construction | For |
|---|---|
| RpcStream::new(stream) | An asynchronous stream of serializable values. |
| RpcStream::from_iter(values) | An iterator. |
| RpcStream::channel(capacity) | A (RpcSender, RpcStream) pair. |
| RpcSender::send(value).await | One serialized event. |
Each event is one JSON value. The request stays active until the stream closes, and can be cancelled by abortPrevious or by component disposal.
Files that spool: RpcFile
Including a browser File or a non-empty FileList in the payload makes pp.rpc send multipart/form-data.
| Parameter type | Accepts |
|---|---|
| RpcFile | Exactly one file. |
| Option<RpcFile> | Zero or one. |
| Vec<RpcFile> | Several fields under the same payload key. |
use crate::rahti::{Result, RpcFile, rpc};
#[rpc]
pub async fn avatar(user: u32, image: RpcFile) -> Result<String> {
// The reported filename is user input. `safe_name` before a path, and
// still choose the destination directory yourself.
let path = std::path::Path::new("uploads").join(image.safe_name());
image.save(&path).await?;
Ok(path.display().to_string())
}// Including a File or a non-empty FileList makes pp.rpc use multipart.
const input = document.querySelector("input[type=file]");
await pp.rpc("avatar", { user: 7, image: input.files[0] }, {
onUploadProgress: ({ percent }) => setPercent(percent ?? 0),
onUploadComplete: () => setPercent(100),
});The API covers metadata (name, safe_name, content_type, len, is_empty, is_spilled), content (bytes, into_bytes, text, reader, into_stream) and persistence (save, copy_to). Small files stay in memory; larger ones spill to a temporary file while arriving. Clones keep a spilled file alive, and the temporary file is removed when no owner remains.
Bytes as they arrive: RpcUpload
Use RpcUpload when the server must process bytes as they arrive, without spooling the whole upload first.
use crate::rahti::{Result, RpcUpload, rpc};
// At most one RpcUpload, and it must be the final parameter — the browser's
// file value is last on the multipart wire.
#[rpc]
pub async fn store(note: String, upload: RpcUpload) -> Result<Stored> {
let bytes = upload.save("uploads/incoming.bin").await?;
Ok(Stored { note, bytes })
}- at most one
RpcUploadparameter; - it must be the final parameter;
- the browser's file value must be last on the multipart wire — the PulsePoint client deliberately appends all non-file fields before files;
- a missing or non-multipart file is an RPC error.
The API covers name, safe_name, content_type, read_so_far, chunk, save, copy_to and collect — the last converting the remaining stream into an RpcFile with a chosen spill threshold.
Limits
| Limit | Default | Override |
|---|---|---|
| Total request | 128 MiB | RAHTI_MAX_UPLOAD |
| Per file | Unlimited, except by the total | RAHTI_MAX_FILE |
| Spill threshold | 256 KiB | RAHTI_SPILL_THRESHOLD |
| Spill directory | The OS temporary directory | RAHTI_SPILL_DIR |
Values are byte counts, and the effective per-file limit never exceeds the total request limit. Keep application-level content validation separate from transport limits: a 10 MB file that is not a valid image is a transport success and an application failure.
