This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index at /llms.txt, or add .md to any page's URL.
Rust data sources
A data crate answers the view's sources in Rust instead of app.ts: an app's
data/ crate (Caltrain,
Fieldnotes) or a game's game.data
(game/README.md). Its type implements exact_runner::DataSource:
Method | What it does |
|---|---|
query(source, args) | Answer now, with no I/O: the build bakes this into the plan for the first frame. Err(DataError::Unavailable(…)) leaves the resource unbaked; every host asks again at launch. |
answer(store, source, args) | At run time: Answer::Now(value), or Answer::Later(request) for the host to run (storage, fetch). The default is query. A resource the build left unbaked is asked at boot, before the host has started storage. There Err(DataError::Unavailable(…)), UnknownSource, BadArguments or Interface refuses the boot: the app does not start (the agent says the app booted with an error; a release build shows no view). On a resource with something to show (its type's zero, or a declared placeholder), Failed(code, …) boots with the resource failed (failure(x)); DeferredAtBake and Answer::Later boot with it pending; Overrun boots with it pending and asks again twice, at 250 ms and 1 s, and a third fails the resource while the app runs on. A row that is another resource's else source() has nothing to show and must answer now: there each of these refuses the boot too. A source that needs storage answers Answer::Later and finishes in parse. |
parse(store, source, args, outcome) | What the host brought back for that request: answer, or hand back one more request. |
app_id() | The app's identity, which names its storage: com.example.my-app-3f9a2c (exact new writes the name and six random hex digits), or for a game com.exact.<Game::ID> unless its app.json names one. A source that names none takes app.json's app.id in the app's build, so its storage (app:/data, kept answers, persist states, an agent drive's --storage) is the app's; one that names its own keeps it, so write the same id as app.json or leave it out. |
grants() | One grant per line, the lines app.ts's grants takes (net.fetch …, sqlite.open …, fs.read …). |
An app outside this checkout names its data crate in app.json (LLP 1153.003 D2):
json
"rust": { "data": { "crate": "field-log-data", "type": "field_log_data::FieldLog" } }
type may name a pub use re-export or a type alias (an authored build script passing one to
exact_bake::host::app, exact_js_bake::build_mixed_with or build_beside wraps it in exact_bake::named! or
exact_js_bake::named!). source, optional, is what every host and the web's module run: the type itself (for a
unit struct, including one re-exported with pub use), its ::default() (the default) or its ::new(…) with
literal arguments ("field_log_data::FieldLog::new(true)"); a plain type alias uses ::default() or ::new(…). A source
built from anything else (a local, a path read at build time) is exported by a crate of the app's own,
named in app.json's rust.module.package (Update Lab's logic/), which supplies the module instead. Beside
app.ts, that crate also carries the data crate's RUST_SOURCES, which the web reads from the module:
exact_logic_abi::export_sources!(field_log_data::RUST_SOURCES); beside its export!.
The crate sits beside app.json and joins the workspace exact2 generates: its Cargo.toml sets
package.workspace = "../.exact/shells" and takes exact2's crates as workspace dependencies
(exact-runner.workspace = true; contract.workspace = true for a build script). Any other crate of
exact2's is taken the same way (exact-canvas.workspace = true), never by a path through
.exact/checkout: the workspace names exact2 by its real path, and a second path to the same crate is a
second package to Cargo, so a build refuses one and bun exact.mjs update rewrites it. The host crates are
generated under .exact/shells/ and link it; without app.ts they link no JavaScript engine. With
app.ts beside it the two compose: Rust answers the sources the crate lists in pub const RUST_SOURCES: &[&str], TypeScript the rest. exact new <path> --rust writes such an app: data/, whose type answers
the starter's source (the view's shapes are generated into it by contract rust), and rust.data.
cargo test, cargo clippy and rust-analyzer work in data/ once a verb has written .exact/shells/
(bun exact.mjs lock writes it): exact2 also writes rust-toolchain.toml and .cargo/config.toml
beside app.json, listed in .gitignore, so they use exact2's compiler and the app's target/. The
workspace resolves against exact2's Cargo.lock until the crate needs a version that lock lacks; a build
then stops and says to run bun exact.mjs lock, which captures Cargo.lock beside app.json. Commit it.
An app that exact new --rust made with apple/ and web/ crates and a root Cargo.toml, or one that
copied the generated workspace up only for a data or GPU crate, moves by hand:
1.
Delete the root Cargo.toml, Cargo.lock, .cargo/, rust-toolchain.toml and the host crates
(apple/, web/, and any linux/, android/ or windows/).
2.
In each remaining crate's Cargo.toml, set package.workspace = "../.exact/shells" (a GPU crate:
"../.exact/gpu"), and write exact2's crates as workspace dependencies: exact-runner.workspace = true, contract.workspace = true; a GPU crate's exact-gpu, wasm-bindgen, wasm-bindgen-futures
and web-sys likewise (docs/recipes/gpu-module.md).
3.
Add rust.data to app.json, naming the source the deleted build scripts baked.
4.
Run bun exact.mjs lock.
A source that wraps another implements exact_runner::DataSourceWrapper.
Every method is required, so adding a data-source method cannot silently use
a leaf's default in a wrapper. Forward each call or handle it explicitly.
A record is positional: Value::record(vec![…]) takes its fields in the order
the shape declares them. bun exact.mjs contract rust app.contract -o /tmp/shapes.rs writes each shape as a struct with its fields in that order.
It includes native-module call records only when an authored shape or a data
source's parameter or result type reaches them; contract::module_rust
generates the module bindings. A data crate's build script calls
contract::build_rust(Path::new("../app.contract")) to write OUT_DIR/shapes.rs.
Exact refreshes the generated Rust before each Cargo build, writing it only
when its contents change. The first build creates the file; Cargo establishes
its watch on the following build. Once warm, a view edit leaves the data crate
fresh when its shapes stay the same. Compiler flags, features and other Cargo
inputs still trigger builds. The dev watcher follows the generator's Contract
source graph even when the generated Rust stays unchanged. Existing build scripts
keep working. Replace their shape-generation calls with contract::build_rust
to get this reuse. Direct Cargo builds watch the Contract source graph. For custom generation,
contract::compile_path_for_rust returns the plan and call-record names to
pass to contract::rust; the names are compiler metadata, outside the binary
plan. Scoped names such as Point__exact become PointExact.
Value::Number, Value::str, Value::Bool and Value::list are the rest.
A package declares gpu.limits.required and gpu.limits.optional as objects of
WebGPU limit names to integer values in its main exact.json. It declares
gpu.features.required and gpu.features.optional as lists of WebGPU feature names.
The Contract compiler validates names and bounds in the declaration. A package
artifact requests its own requirements before its device is created. Optional values
are clamped to the adapter, with alignment minima ordered in reverse. Buffer binding
sizes also raise maxBufferSize; workgroup dimensions also raise
maxComputeInvocationsPerWorkgroup. A required value that exceeds either adapter
limit is refused; an optional value is clamped to both. An unavailable required limit or
feature refuses the owning package's surfaces while the other surfaces keep drawing.
The web backend does not expose subgroups, primitive-index or immediates:
optional requests omit them and required requests refuse the package's surfaces;
native grants them where the adapter offers them.
An app without requirements retains the existing device request.
Surface::device_ready(&mut self, features: wgpu::Features, limits: wgpu::Limits)
receives the actual grant, including on recovery and target reattachment. A fixture
requests the same grant through exact_gpu::fixture::device_with_requirements.
An authored GPU module passes a static &[exact_gpu::grants::Requirements] as the
second argument to exact_gpu::module!. See the GPU module recipe
for a declaration and package GPU surfaces
for packaging. Packages declare exactGpu: "0.4" and depend on exact-gpu = "0.4".
A GPU surface reads a color("surface.board") argument in bind with
exact_gpu::json::color(&inputs[0], "fill")?. The result is four finite
f32 components: straight linear sRGB (D65) and alpha in [0, 1].
RGB may extend below zero or above one. Keep the ColorTarget from
Surface::color_target. Use target.fragment(rgba) for a shader constant
written with replacement blending and target.clear(rgba) for a clear.
Both convert to the attachment's primaries, transfer and alpha association.
A change of attachment format, colour space or alpha mode rebinds colour
inputs even when their RGBA is unchanged. A straight linear-sRGB working
texture can use the input directly. For transparency leave Surface::opaque()
false. On an opaque-only target the helper writes straight colour at full alpha.
The opaque board matched its sibling in light, dark and after an ancestor pin
changed on macOS Metal, Chrome WebGPU, the iOS 27.2 simulator, the painted
Linux host running on macOS and Android API 35 and 36 emulators.
These measurements use one half-alpha swatch, color(display-p3 .6 .4 .3 / .5),
over white. RGB values are from sRGB captures.
Host and target | GPU | Sibling |
|---|---|---|
macOS 27.2.1 Metal SDR | (208, 177, 163) | (208, 177, 163) |
macOS 27.0.1 agent window, 8-bit Metal row | (208, 178, 164) | (209, 178, 164) |
macOS 27.0.1 agent window, float-request row | (209, 177, 164) | (209, 178, 164) |
Chrome, half-float or 8-bit with sRGB display primaries | (208, 177, 163) | (208, 177, 163) |
Chrome, 8-bit Display P3 on an sRGB destination | (207, 177, 162) | (208, 177, 163) |
Android API 35 and 36, host GPU, premultiplied sRGB RGBA8 | (208, 177, 163) | (208, 177, 163) |
iOS 27.2 simulator display, 8-bit P3 shader | (208, 177, 162) | (208, 177, 163) |
iOS 27.2 simulator display, float-request row | (208, 177, 163) | (208, 177, 163) |
iOS 27.2 and 26.5 simulator displays, literal P3 clear | (208, 177, 162) | (208, 177, 163) |
The painted Linux capture also matched its translucent sibling. The Android
float request also received RGBA8. The measured one-step differences apply
to this swatch. On iOS the same literal clear gave the same
display pixels before and after colour inputs. The 27.2 display spatially
dithered the float row’s opaque border. A plain UIKit app drawing the same
solid clear into a half-float Metal layer reproduced that variation.
The 27.2 agent window capture
on the parent gave (183, 138, 118) for that clear. HDR displays, Windows
presentation and physical mobile devices remain unverified.
A surface opts into raw input with Surface::wants_input. On macOS the canvas
also dispatches Contract pointer, wheel and context menu events. GPU module recipe
On Apple (macOS, iOS and tvOS), Android, Linux and Windows, a surface may implement:
rust
fn storage(&mut self, data: &std::path::Path, cache: &std::path::Path,
temporary: &std::path::Path) {
self.cache = Some(cache.to_path_buf());
}
The host calls this hook once for each canvas, after creation and before its first
bind. The three absolute paths resolve that session's app:/data, app:/cache
and app:/tmp. They are borrowed for the call; copy any path the surface keeps.
The native ABI preserves Unix path bytes and Windows UTF-16 code units, including
non-Unicode names. On Android, Linux and Windows, a storage delivery failure keeps
the canvas and logs once at creation. The module does not create directories or retain
paths for a surface that ignores them. Create a directory when needed and handle
filesystem errors in the surface. Device recovery keeps the surface and its paths; a recreated canvas receives them
again. Keep paths on the surface, since a loaded artifact can serve several sessions.
A file written under cache can be shown with image "app:/cache/<name>", shared
by that path, or read as an asset. Use distinct names for changed snapshots. Cache
and temporary files may be removed by the platform; durable files belong in data.
An agent drive's named store supplies its own roots. An unnamed drive uses temporary
process storage, not the installed app's files.
The web does not call storage. Its GPU artifact is WebAssembly with generated
wasm-bindgen JavaScript; Exact supplies it no filesystem or browser-storage bridge.
A GPU module that needs persistence must supply its own browser API integration.
The app's data module can separately use Exact's storage.fs and storage.sqlite
APIs, backed by browser storage on the web. Those APIs are not injected into GPU modules
and supply no paths usable by std::fs or native SQLite.
exact-gpu 0.4 carries the hook and the native gpu_storage export; rebuild GPU
artifacts with the host.
An app whose host crate does what no generated one does (its own build.rs or render entry, or a
dependency of the host crate itself) writes its whole Cargo workspace (LLP 1153.003 D3). A Cargo.toml
beside app.json makes every crate in it the app's: exact2 generates no host crate, and checks the
workspace's [patch.crates-io] and toolchain against its own. Nothing converts one shape into the
other. To start one, copy the generated workspaces up and rebase what pointed into them:
1.
Run a native verb once (bun exact.mjs mac): it writes .exact/shells/, and .exact/gpu/ for a
GPU crate.
2.
Copy the host's up: cp -R .exact/shells/. . && rm -rf module .stamp.json. The web build makes its
own Rust module for an authored workspace.
3.
The copied files are two directories shallower than they were, so each of their paths drops two
../. Run this on the root Cargo.toml and each copied host crate's Cargo.toml and build.rs, not
on your own crates: sed -i.bak 's#"\.\./\.\./#"#g' Cargo.toml web/Cargo.toml web/build.rs apple/Cargo.toml apple/build.rs (and linux/, android/, windows/ when copied), then delete the .bak files.
4.
In the root Cargo.toml, members lists "data" and "gpu", not "module". For a GPU crate, add
the lines under [workspace.dependencies] in .exact/gpu/Cargo.toml to the root's, each path
dropping two ../ as in step 3.
5.
In each of your own crates, package.workspace becomes "..".
6.
Delete .exact/ and Cargo.gpu.lock, and remove /rust-toolchain.toml and /.cargo/config.toml
from .gitignore: the copied toolchain and configuration are the workspace's now, and committed.
7.
Run bun exact.mjs lock, then build as before.
On native hosts and the web JS target a Rust source sends on a WebSocket with
TypeScript's rules (LLP 1016.003). Answer Answer::Later(Request::socket(url)) for a ws: or
wss: URL under a net.websocket grant. Its parse is the mapper: it gets
an Outcome::Message whose event is open, then one for each frame in
order (text in data, a binary frame in binary), then Outcome::Closed { code, reason, was_clean }. While it answers open or a frame,
store.socket() is that socket's handle; keep it to send from a mutation:
rust
fn answer(&mut self, store: &mut Store, source: &str, args: &[Value]) -> Result<Answer, DataError> {
match source {
"book" => Ok(Answer::Later(Request::socket("wss://stream.example/ws"))),
"subscribe" => {
let socket = self.book.ok_or(DataError::Unavailable("the book is not open".into()))?;
socket.send_text(store, r#"{"method":"SUBSCRIBE","params":["depth.SOL_USDC"]}"#)?;
Ok(Answer::Now(Value::Bool(true)))
}
_ => Err(DataError::UnknownSource(source.into())),
}
}
fn parse(&mut self, store: &mut Store, _: &str, _: &[Value], outcome: Outcome) -> Result<Answer, DataError> {
match outcome {
Outcome::Message(m) if m.event == "open" => {
let socket = store.socket().expect("a socket's mapper has its handle");
self.book = Some(socket);
socket.send_text(store, r#"{"method":"SUBSCRIBE","params":["trade.SOL_USDC"]}"#)?;
Ok(Answer::Now(Value::str("open")))
}
Outcome::Message(m) => Ok(Answer::Now(Value::str(&m.data))),
Outcome::Closed { code, .. } => Ok(Answer::Now(Value::str(&format!("closed {code}")))),
other => Err(DataError::Unavailable(other.summary())),
}
}
Socket has send_text, send_binary, close(store, code, reason),
buffered_amount and is_open. A mutation's answer may send on any open
socket of the app's resources, and must then answer Answer::Now; a mapper
sends only on its own socket. What either stages goes once its commit
stands. A refusal is an Err whose text names the DOM exception a
TypeScript handle would throw: InvalidStateError for a socket not open, a
handle from before the resource was asked again, or a send from a resource's
answer; QuotaExceededError past 256 operations or 1 MiB a call, which
fails a mapper's frame even when it ignores the error. The web's wasm host
and a worker-placed source cannot hold the handle, so they refuse
Request::socket by name rather than open a socket that only listens
(Request::socket is unavailable on the web's wasm host, … in a worker-placed source; place it on main).
Keep app and game data (best times, settings, saves, notes) in app
storage: SQLite databases and files under app:/data, the storage app.ts
reaches as storage.sqlite and storage.fs. A Rust source asks for it with
exact_data::storage::request(op, args) as an Answer::Later, and reads the
reply in parse with exact_data::storage::response(outcome), which is the
JSON result or the host's message. The operations:
op | args | Reply |
|---|---|---|
"sqlite" | {"path": "app:/data/x.db", "commands": [{"kind": "execute" or "query", "sql", "params"}]} | One result per command, in order: a query's {"columns", "rows"} (an integer is {"integer": "7"}, text a string), an execute's {"changes", "lastInsertRowid"} |
"sqlite.transaction" | the same, execute commands only | the executes' results, all or none |
"fs.readFile", "fs.atomicWriteFile", "fs.writeFile", "fs.appendFile" | {"path"}, and "text" (or "bytes") to write | read: {"base64"}; write: null |
"fs.mkdir", "fs.rm", "fs.stat", "fs.readdir", "fs.rename", "fs.copyFile" | {"path"}, and "destination" to move or copy | as storage.fs answers |
"fs.compressImage" | {"path", "destination", "maxDimension"}, "maxBytes", "quality" or both, and "type" ("image/png"; absent or null is JPEG), "rotate", "flip", "crop"; null is absent | {"path", "type", "size", "width", "height"}, as storage.fs.compressImage answers |
"fs.transformImage" | {"path", "destination"} and storage.fs.transformImage's options beside them ("rotate", "crop", "metadata", …; null is absent) | {"path", "type", "size", "width", "height", "colorSpace", "hdr", "metadata"}, as it answers |
Grant what it touches: sqlite.open app:/data/x.db, fs.read app:/data,
fs.write app:/data. Storage is asynchronous and starts after first pixel. It
is absent at build, so query answers a placeholder, and in a scripted drive
that names no scratch store: there response is an error, and the source
answers as if nothing were kept. --storage <name> gives a drive a store kept
between native drives (--reset-storage empties it); on the web the next drive
keeps it with --keep-storage. An authored test gets an empty one, and its reload restarts
on it. A game's data crate takes these crates from the SDK
(exact-data.workspace = true, serde_json.workspace = true).
Best times, one row a level, decided in SQL. This is the platformer's source
(the diary's R6). One request reads the previous best and writes the run where
it beats it:
rust
use exact_data::storage;
use exact_runner::{Answer, DataError, DataSource, Outcome, Store, Value};
use serde_json::json;
const DB: &str = "app:/data/scores.db";
const TABLE: &str = "CREATE TABLE IF NOT EXISTS best (level INTEGER PRIMARY KEY, ms INTEGER NOT NULL)";
#[derive(Default)]
pub struct Scores;
impl DataSource for Scores {
fn app_id(&self) -> &str { "com.exact.hopper" }
fn grants(&self) -> &str { "sqlite.open app:/data/scores.db" }
fn query(&mut self, source: &str, _: &[Value]) -> Result<Value, DataError> {
match source {
"best" => Ok(Value::record(vec![Value::list(vec![])])), // the build's first frame: nothing kept
_ => Err(DataError::Unavailable("asked at run time".into())),
}
}
fn answer(&mut self, _: &mut Store, source: &str, args: &[Value]) -> Result<Answer, DataError> {
let commands = match (source, args) {
("best", _) => json!([{"kind": "execute", "sql": TABLE, "params": []},
{"kind": "query", "sql": "SELECT level, ms FROM best ORDER BY level", "params": []}]),
("finish", [Value::Number(level), Value::Number(ms)]) => json!([{"kind": "execute", "sql": TABLE, "params": []},
{"kind": "execute", "sql": "INSERT INTO best VALUES (?, ?) ON CONFLICT(level) DO UPDATE SET ms = excluded.ms WHERE excluded.ms < best.ms", "params": [level, ms]}]),
_ => return Err(DataError::UnknownSource(source.into())),
};
Ok(Answer::Later(storage::request("sqlite", json!({"path": DB, "commands": commands}))))
}
fn parse(&mut self, _: &mut Store, source: &str, _: &[Value], outcome: Outcome) -> Result<Answer, DataError> {
let results = storage::response(outcome);
let int = |cell: &serde_json::Value| cell["integer"].as_str().and_then(|n| n.parse::<f64>().ok());
Ok(Answer::Now(match source {
// No storage here (a drive with no scratch store): nothing kept.
"best" => Value::record(vec![Value::list(results.ok().and_then(|r| r[1]["rows"].as_array().cloned()).unwrap_or_default()
.iter().filter_map(|row| Some(Value::record(vec![Value::Number(int(&row[0])?), Value::Number(int(&row[1])?)]))).collect())]),
_ => Value::record(vec![Value::Bool(results.map_err(DataError::Unavailable)?[1]["changes"].as_str() == Some("1"))]), // a new best?
}))
}
}
Store (store.get, store.set, under secret.keep <name>) is for
secrets: a session token, a key. Apple keeps them in the Keychain, Linux
in a file per secret only the user can read (0600, under
$XDG_DATA_HOME/exact/<app id>/secrets; not encrypted), Android in AES-GCM
files with Android Keystore-wrapped keys, and the web in origin-readable
localStorage; Windows keeps them in memory for now.
For web refresh and session tokens, use a server-set HttpOnly, Secure cookie:
web sign-in tokens and sessions covers the shared
native/web flow, selected at run time by exactHost() inside an answer
('web' or 'native', no grant; also on web workers). It refuses at module
initialization and outside an answer; the bake leaves its answers for the host.
Web secret.keep does not protect against injected scripts.
Opening Android's secret store deletes legacy
plaintext files without reading them; only encrypted entries are restored.
The host reads secrets into a snapshot before boot, so a read is synchronous,
and a scripted drive never keeps them. A best time is not
a secret: keep it in app storage. A lease on a secret (SharedSecrets::acquire,
from configure_secrets) needs the same grant: on Apple a name the grants do not
keep reads and writes as denied: secret.keep.
Is this helpful
Last updated November 30, 2026