Using Stof in Your App
Stof runs inside your app, as a library. Your app creates documents, puts data and logic into them, calls their functions, and reads the results. This page covers each of those steps. Every example is in TypeScript, Python, and Rust: pick your language on any example, and the rest of the docs follow. The table at the end lists the methods side by side.
Loading a Document
Create a document from Stof source (in JavaScript, StofDoc.new also takes an object or bytes):
- TypeScript
- Python
- Rust
import { StofDoc } from '@formata/stof';
const doc = await StofDoc.new(`
pricing: {
rate: 2
fn total(units: int) -> float { units * self.rate }
}
`);
from pystof import Doc
doc = Doc()
doc.parse("""
pricing: {
rate: 2
fn total(units: int) -> float { units * self.rate }
}
""")
use stof::model::Graph;
let mut graph = Graph::default();
graph.parse_stof_src(r#"
pricing: {
rate: 2
fn total(units: int) -> float { units * self.rate }
}
"#, None, Default::default())?;
A document can keep taking in more, in any format it knows. Each parse adds to what's already there:
- TypeScript
- Python
- Rust
doc.parse({ customer: { name: 'Ada', plan: 'pro' } }); // a JavaScript object
doc.parse('limits:\n calls: 100\n', 'yaml'); // YAML (also 'json', 'toml', ...)
doc.parse(rulesFromAModel); // more Stof: data, functions, or both
doc.parse(pluginSource, 'stof', 'plugins.weather', 'untrusted'); // into an object, running nothing
doc.string_import('{"customer": {"name": "Ada", "plan": "pro"}}', 'json') # JSON
doc.string_import('limits:\n calls: 100\n', 'yaml') # YAML (also 'toml', ...)
doc.parse(rules_from_a_model) # more Stof: data, functions, or both
doc.parse(plugin_source, 'plugins.weather', 'untrusted') # into an object, running nothing
use stof::model::Profile;
graph.string_import("json", r#"{"customer": {"name": "Ada", "plan": "pro"}}"#, None, &Default::default())?;
graph.string_import("yaml", "limits:\n calls: 100\n", None, &Default::default())?; // also "toml", ...
graph.parse_stof_src(rules_from_a_model, None, Default::default())?; // more Stof: data, functions, or both
let weather = graph.host_object("plugins.weather");
graph.string_import("stof", plugin_source, weather, &Profile::untrusted())?; // into an object, running nothing
That's how data and logic from different places end up in one document. Parsing Stof can run it (a field's value can be an expression, and #[init] functions run), so parse source you didn't write with the 'untrusted' profile and seal it confined before calling it. See Formats for every format.
Calling Functions
call takes a path to a function and its arguments, and returns what the function returns:
- TypeScript
- Python
- Rust
await doc.call('pricing.total', 21); // 42
await doc.call('pricing.total', '4'); // 8: arguments are cast to the parameter's type
doc.call('pricing.total', [21]) # 42.0
doc.call('pricing.total', ['4']) # 8.0: arguments are cast to the parameter's type
use stof::runtime::{Runtime, Val};
Runtime::call(&mut graph, "pricing.total", vec![Val::from(21i64)])?; // 42.0
Runtime::call(&mut graph, "pricing.total", vec![Val::from("4")])?; // 8.0: arguments are cast to the parameter's type
Paths start at the document's top level, so 'pricing.total' is the total function on the pricing object. In JavaScript, calls are async because a document can do async work, like waiting on one of your functions.
Running Code Without Keeping It
Sometimes you have logic to run once, like a check or a script from a model, and don't want it in the document afterward. callSource (call_source in Python and Rust) parses a function, calls it as if it were defined at the top level of the document (or on the object you pass), and removes it after:
- TypeScript
- Python
- Rust
await doc.callSource(`
fn quote(qty: int) -> float {
self.pricing.total(qty) * self.discount()
}
fn discount() -> float { 0.9 }
`, [10]); // the first function is called; the rest are helpers it can reach through self
doc.call_source("""
fn quote(qty: int) -> float {
self.pricing.total(qty) * self.discount()
}
fn discount() -> float { 0.9 }
""", [10]) # the first function is called; the rest are helpers it can reach through self
Runtime::call_source(&mut graph, r#"
fn quote(qty: int) -> float {
self.pricing.total(qty) * self.discount()
}
fn discount() -> float { 0.9 }
"#, None, vec![Val::from(10i64)])?; // the first function is called; the rest are helpers it can reach through self
Changes the function makes to the document stay; the function and its helpers don't. To take something out of the document yourself, remove takes a path, like drop in Stof:
- TypeScript
- Python
- Rust
doc.remove('pricing.old_total'); // a function or field
doc.remove('customers.c_42'); // an object
doc.remove('order.customer', true); // shallow: just the field, not the object it points to
doc.remove('pricing.old_total') # a function or field
doc.remove('customers.c_42') # an object
doc.remove('order.customer', True) # shallow: just the field, not the object it points to
graph.remove("pricing.old_total", false); // a function or field
graph.remove("customers.c_42", false); // an object
graph.remove("order.customer", true); // shallow: just the field, not the object it points to
Running by Attribute
When you don't know what a document's functions are called, tag them, and run every function with an attribute:
- TypeScript
- Python
- Rust
const doc = await StofDoc.new(`
ticket: { text: 'Where is my refund?' }
#[triage]
fn route() {
if (self.ticket.text.lower().contains('refund')) self.ticket.team = 'billing';
}
`);
await doc.run('triage'); // every #[triage] function
doc.get('ticket.team'); // 'billing'
doc = Doc()
doc.parse("""
ticket: { text: 'Where is my refund?' }
#[triage]
fn route() {
if (self.ticket.text.lower().contains('refund')) self.ticket.team = 'billing';
}
""")
doc.run('triage') # every #[triage] function
doc.get('ticket.team') # 'billing'
let mut graph = Graph::default();
graph.parse_stof_src(r#"
ticket: { text: 'Where is my refund?' }
#[triage]
fn route() {
if (self.ticket.text.lower().contains('refund')) self.ticket.team = 'billing';
}
"#, None, Default::default())?;
let attributes: stof::rustc_hash::FxHashSet<String> = ["triage".to_string()].into_iter().collect();
Runtime::run_attribute_functions(&mut graph, None, &Some(attributes), true) // every #[triage] function
.expect("a #[triage] function failed"); // (the error is a String)
graph.field_value("ticket.team", graph.main_root()); // Some("billing")
This is the usual setup when logic comes from somewhere else, like a model or a customer. The attribute is the agreement: your app runs #[triage] functions, and the document can have as many as it needs, with any names. run() with no attribute runs #[main] functions (in Rust, graph.run(None, true)).
Reading and Writing Values
Read and write any value by path:
- TypeScript
- Python
- Rust
doc.get('pricing.rate'); // 2
doc.set('pricing.rate', 3);
doc.set('customer.vip', true); // creates the field if it isn't there
doc.get('pricing.rate') # 2
doc.set('pricing.rate', 3)
doc.set('customer.vip', True) # creates the field if it isn't there
use stof::runtime::Variable;
graph.field_value("pricing.rate", graph.main_root()); // Some(2)
graph.set_field(Variable::val(Val::from(3i64)), "pricing.rate", graph.main_root()); // changes a field that's there
graph.string_import("json", r#"{"customer": {"vip": true}}"#, None, &Default::default())?; // adds one (imports merge)
Numbers, strings, booleans, lists, and maps come back as JavaScript or Python values (a Val in Rust). An object comes back as its ID, a string you can pass to the functions that take a node (like blobify below).
Giving Documents Your Functions
A document can only call what it's given. lib adds one of your functions as a library function the document can call (in JavaScript, pass true after an async function so the document can await it):
- TypeScript
- Python
- Rust
doc.lib('App', 'notify', (message: string) => notifications.send(message));
doc.lib('App', 'customer_name', async (id: number) => (await db.customers.find(id)).name, true); // async
doc.lib('App', 'notify', lambda message: notifications.send(message))
doc.lib('App', 'customer_name', lambda id: db.customers.find(id).name)
In Rust, a host function is a LibFunc added with graph.insert_libfunc(..): its func returns the instructions the call runs. Stof's own libraries are written this way; see the standard libraries for examples.
fn on_refund(id: int) {
const name = await App::customer_name(id);
App::notify(`Refund started for ${name}`);
}
This is how you connect a document to the rest of your app on your terms: it gets these functions and nothing else. See Adding Your Own in Libraries.
Host functions belong to the document you add them to. Two documents can give the same name different functions, and a document never sees another document's:
- TypeScript
- Python
- Rust
const acme = await StofDoc.new();
const globex = await StofDoc.new();
acme.lib('App', 'plan', () => 'enterprise');
globex.lib('App', 'plan', () => 'starter');
for (const doc of [acme, globex]) doc.parse('fn plan() -> str { App.plan() }');
console.log(await acme.call('plan'), await globex.call('plan')); // enterprise starter
acme, globex = Doc(), Doc()
acme.lib('App', 'plan', lambda: 'enterprise')
globex.lib('App', 'plan', lambda: 'starter')
for doc in (acme, globex):
doc.parse("fn plan() -> str { App.plan() }")
print(acme.call('plan'), globex.call('plan')) # enterprise starter
In Rust, each Graph has its own library table, so a LibFunc added with insert_libfunc belongs to that graph alone.
Python can share a document across threads. Calls on one document run one at a time (a call from another thread waits its turn), and a running call releases the GIL, so your other threads go on meanwhile: a web server keeps answering requests, and a call whose Http.fetch reaches a server in the same process gets its answer. A lib function runs with the GIL on the thread making the call. It can call other documents, but calling back into the document that's running it raises an error instead of waiting on itself. The package ships type stubs, so editors and type checkers know every Doc method.
What a Document Can Reach
A document can read and change itself and call library functions. It can't reach the file system, environment variables, other files, or the network unless you allow it:
- TypeScript
- Python
- Rust
doc.allowHttp(['api.example.com']); // network access to these hosts only
doc.allowHttp(); // network access to any public host (never your machine or private network)
doc.allow_http_hosts(['api.example.com']) # network access to these hosts only
doc.allow_http() # network access to any public host (never your machine or private network)
graph.allow_http_hosts(["api.example.com"]); // network access to these hosts only (the http feature)
graph.allow_http(); // network access to any public host (never your machine or private network)
In Python and Rust, allow_system() also gives access to files and environment variables. The JavaScript package has no file system access at all. Libraries has the full table.
Each call also has a time limit (2 minutes by default) and a memory limit (256 MB by default), so a document that loops forever or keeps growing can't hang or crash your app:
- TypeScript
- Python
- Rust
doc.setMaxExecutionTime(500); // milliseconds, or null for no limit
doc.setMaxMemory(64 * 1024 * 1024); // bytes, or null for no limit
doc.set_max_execution_time(0.5) # seconds, or None for no limit
doc.set_max_memory(64 * 1024 * 1024) # bytes, or None for no limit
graph.max_execution_time = Some(std::time::Duration::from_millis(500)); // or None for no limit
graph.max_memory = Some(64 * 1024 * 1024); // bytes, or None for no limit
execution timed out (max execution time exceeded)
at root.spin (defined at 1:1)
To lock the parts of a document you trust so other code can call them but not change them, seal them: doc.seal('<Engine>'). To keep code you didn't write to what you give it, parse it untrusted and seal it confined: doc.parse(src, 'stof', 'plugins.weather', 'untrusted'), then doc.seal('plugins.weather', { reads: ['inputs'], hosts: ['api.weather.example'], libs: ['Std', 'Str', 'Http'], time: 2000 }), with calls for the functions of yours it may call. To check where logic or data came from, sign and verify it with the same keys in your app and in documents (StofDoc.sign, Key::verify). Security and the Sandbox covers sealing, keys and signatures, confining, the network rules, and the limits in full.
Errors
A function that throws makes the call fail, with a plain message and the Stof call stack:
- TypeScript
- Python
- Rust
try {
await doc.call('pricing.total');
} catch (error) {
console.log(String(error)); // missing argument 'units' for total(units: int)
}
try:
doc.call('pricing.total')
except ValueError as error:
print(error) # missing argument 'units' for total(units: int)
if let Err(error) = Runtime::call(&mut graph, "pricing.total", vec![]) {
println!("{error}"); // missing argument 'units' for total(units: int)
}
A document that doesn't parse fails to load, with the line and column:
parse error: unexpected end of input (expected '}')
--> line 1, column 5
|
1 | a: {
| ^
For line numbers on runtime errors too, parse with the test profile: StofDoc.new(src, 'stof', 'test'), doc.parse(src, profile='test') in Python, or Profile::test() in Rust. The default profile leaves them out to keep documents smaller.
These messages are written to be read by people and by models. When a model wrote the document, pass the error back to it and ask for a fix.
Exporting
A document exports to any format it knows:
- TypeScript
- Python
- Rust
doc.stringify('json'); // a JSON string (functions are left out)
doc.stringify('yaml');
doc.record(); // a plain JavaScript object
doc.string_export('json') # a JSON string (functions are left out)
doc.string_export('yaml')
json.loads(doc.string_export('json')) # a plain dict
graph.stringify("json", None)?; // a JSON string (functions are left out)
graph.stringify("yaml", None)?;
To keep the functions, export binary Stof (bstf). It holds the whole document, or one object, and loads anywhere Stof runs:
- TypeScript
- Python
- Rust
const bytes = doc.blobify('bstf', doc.get('pricing')); // just the pricing object, functions included
const copy = await StofDoc.new(bytes, 'bstf');
await copy.call('total', 5); // 10
data = doc.binary_export('bstf', doc.get('pricing')) # just the pricing object, functions included
copy = Doc()
copy.binary_import(data, 'bstf')
copy.call('total', [5]) # 10.0
let pricing = graph.host_object("pricing");
let bytes = graph.blobify("bstf", pricing)?; // just the pricing object, functions included
let mut copy = Graph::default();
copy.binary_import("bstf", bytes, None, &Default::default())?;
Runtime::call(&mut copy, "total", vec![Val::from(5i64)])?; // 10.0
Store those bytes, send them over HTTP or a WebSocket, and run them in another service, a browser, or Python.
An html export is safe to put on a page (see Formats), and your app can limit it to exactly the elements it renders, like its own components. A document can't change that list:
- TypeScript
- Python
- Rust
doc.allowHtmlTags(['div', 'section', 'ui-card', 'ui-metric']);
el.innerHTML = doc.stringify('html', 'dashboard');
doc.allow_html_tags(['div', 'section', 'ui-card', 'ui-metric'])
html = doc.string_export('html', 'dashboard')
graph.allow_html_tags(["div", "section", "ui-card", "ui-metric"]);
let dashboard = graph.host_object("dashboard");
let html = graph.stringify("html", dashboard)?;
A stof export is the document as readable Stof, with its functions as source (see Formats).
Editing Stof text in place
To change a document people also edit by hand (Ex. a settings page saving into a hand-written file), edit its text instead of exporting it again: only what you change is rewritten, and comments, formatting, and everything else stay as they were. Nothing in the text runs while it's outlined or edited.
- TypeScript
- Python
- Rust
const defs = StofDoc.outline(text); // every field and function: path, kind, value, source
const next = StofDoc.edit(text, [
{ set: 'pricing.rate', value: 3 }, // a JSON value
{ set: 'pricing.limit', stof: '2GB' }, // Stof source
{ set_fn: 'pricing.total', stof: 'fn total(units: int) -> float { units * self.rate * 0.9 }' },
{ rename: 'pricing.old', to: 'legacy' },
{ remove: 'pricing.legacy' },
]);
defs = Doc.outline(text) # every field and function: path, kind, value, source
next_text = Doc.edit(text, [
{'set': 'pricing.rate', 'value': 3}, # a JSON value
{'set': 'pricing.limit', 'stof': '2GB'}, # Stof source
{'set_fn': 'pricing.total', 'stof': 'fn total(units: int) -> float { units * self.rate * 0.9 }'},
{'rename': 'pricing.old', 'to': 'legacy'},
{'remove': 'pricing.legacy'},
])
use stof::parser::edit::{edit_json, outline};
let defs = outline(&text)?; // every field and function: path, kind, value, source
let next = edit_json(&text, r#"[
{ "set": "pricing.rate", "value": 3 },
{ "set": "pricing.limit", "stof": "2GB" },
{ "set_fn": "pricing.total", "stof": "fn total(units: int) -> float { units * self.rate * 0.9 }" },
{ "rename": "pricing.old", "to": "legacy" },
{ "remove": "pricing.legacy" }
]"#)?;
A set adds what isn't there, with the objects on its path, in the style of the object it goes into. If the text or the result doesn't parse, or an edit doesn't make sense, edit fails and nothing changes.
Exports call a format's computed values (#[attr] and #[text] functions) first. A computed value that calls one of your async host functions can't finish in stringify: export from Stof instead, with await doc.callSource('fn view() -> str { stringify("html", self) }', [], 'dashboard').
Performance
A document runs inside your process, so there's no server, network hop, or cold start. Rough numbers for Stof 0.11.4, measured from Python on a small Linux machine (yours will differ, but not by much in kind):
| Work | Time |
|---|---|
| Parse a small document (a few fields and functions) | about 0.2 ms |
| Call a small function | 3 to 5 µs |
| One loop iteration | about 2.5 µs |
| One call inside a document (recursion, helpers) | about 5 µs |
That's fast for rules, pricing, validation, and agent tools: logic that makes a decision and returns. It isn't meant for number crunching over millions of items. To keep things fast:
- Load once, call many times. Parsing is the expensive step. Keep a document around and call its functions, instead of parsing it for every request.
- Give heavy work to host functions. Searching a database, parsing a large file, or any tight loop over lots of data belongs in your app. Hand it to the document with
lib, and let the document decide what to do with the result. - Keep limits on. The time and memory limits cost little and stop a runaway document, so set them for logic you didn't write.
In 0.11.4, function calls do about 20% less work and loops and lists about 12% less. The Python package also uses a faster memory allocator, which makes calls another 15 to 25% faster.
Cleaning Up
In JavaScript, a document lives in WebAssembly memory, which the garbage collector doesn't free. Call doc.dispose() when you're done with a document you created for a short task.
By Language
The same steps, side by side:
| Step | JavaScript | Python | Rust |
|---|---|---|---|
| Create | await StofDoc.new(src) | doc = Doc() then doc.parse(src) | Graph::default() then graph.parse_stof_src(src, None, Default::default()) |
| Parse other formats | doc.parse(src, 'yaml') | doc.string_import(src, 'yaml') | graph.string_import("yaml", src, None, &Default::default()) |
| Parse untrusted Stof | doc.parse(src, 'stof', path, 'untrusted') | doc.parse(src, path, 'untrusted') | graph.string_import("stof", src, Some(node), &Profile::untrusted()) |
| Call | await doc.call('pricing.total', 21) | doc.call('pricing.total', [21]) | Runtime::call(&mut graph, "pricing.total", vec![Val::from(21i64)]) |
| Call source | await doc.callSource(src, [21]) | doc.call_source(src, [21]) | Runtime::call_source(&mut graph, src, None, vec![Val::from(21i64)]) |
| Remove | doc.remove(path) | doc.remove(path) | graph.remove(path, false) |
| Run by attribute | await doc.run('triage') | doc.run('triage') | Runtime::run_attribute_functions(&mut graph, None, &Some(attributes), true) |
| Read and write | doc.get(path), doc.set(path, value) | doc.get(path), doc.set(path, value) | graph.field_value(path, graph.main_root()), graph.set_field(var, path, graph.main_root()) |
| Host functions | doc.lib('App', 'notify', fn) | doc.lib('App', 'notify', fn) | graph.insert_libfunc(LibFunc { .. }) |
| Network access | doc.allowHttp(hosts) | doc.allow_http_hosts(hosts) | graph.allow_http_hosts(hosts) |
| Files and environment | not available | doc.allow_system() | graph.allow_system() |
| Time limit | doc.setMaxExecutionTime(ms) | doc.set_max_execution_time(seconds) | graph.max_execution_time = Some(duration) |
| Memory limit | doc.setMaxMemory(bytes) | doc.set_max_memory(bytes) | graph.max_memory = Some(bytes) |
| HTML elements | doc.allowHtmlTags(tags) | doc.allow_html_tags(tags) | graph.allow_html_tags(tags) |
| Seal | doc.seal(path) | doc.seal(path) | graph.seal_path(path, false, None) |
| Keep function source | doc.keepSource() | doc.keep_source() | graph.keep_source(true) |
| Edit text | StofDoc.outline(text), StofDoc.edit(text, edits) | Doc.outline(text), Doc.edit(text, edits) | stof::parser::edit::{outline, edit} |
| Export | doc.stringify('json'), doc.blobify('bstf') | doc.string_export('json'), doc.binary_export() | graph.stringify("json", None), graph.blobify("bstf", None) |
The same document gives the same results in all three.