How Stof Works
A few ideas explain almost everything Stof does. This page goes through them in order.
A Document Is a Graph of Objects
A Stof document is a set of objects. Each object holds named pieces of data, its fields and functions, and can have child objects:
server: {
port: 8080
address: 'localhost'
fn url() -> str {
`https://${self.address}:${self.port}`
}
}
Here server is an object with two fields and a function. Inside a function, three words find your way around:
selfis the object the function is on, soself.portis theportfield next tourl.superis that object's parent.rootis the top-level object above it.
The top level of a document is an object too, the main root. A document can have other roots (root Settings { .. }), and imports can create them.
Inside the runtime, a document is stored flat: a list of objects and a list of data, connected by IDs. Fields, functions, and other data (like an image or a PDF) are all the same kind of thing, a component attached to an object, a bit like an entity-component system in a game engine. That's why moving, copying, or sending part of a document is cheap, and why functions can be treated like any other data.
Data and Logic in One Document
Any JSON document is already a Stof document:
{
"name": "Stof",
"age": 30,
"active": true
}
The quotes, commas, and outer braces are optional. Add types where you want them, and a function next to the data:
name: 'Stof'
int age: 30
bool active: true
fn greet() -> str {
`Hello, ${self.name}!`
}
Nothing moved to a separate codebase. The function sits on the same object as the fields, found the same way, and travels with them.
Functions Are Data
Because a function is a component on an object, everything you can do with data works for logic too:
- Store it in a field:
discount: (p: float): float => p * 0.8, thenself.discount(20). - Find it by attribute:
self.funcs('rule')lists the functions tagged#[rule], so new rules join in without anything else changing. - Merge it: parse two documents into one, and their functions are side by side.
- Send it: export an object as binary Stof (
bstf) and its functions go with it, ready to run on the other side.
Sandboxed by Default
A document can only see and change itself, and call the library functions it has. File system, environment variables, file imports, and the network are all off until the app running it turns them on, and it can turn on the network for only a few hosts. Each call also has a time limit.
That's what makes it safe to run a document from somewhere you don't fully trust: a model, a customer, an API, another service. The app decides what the document can reach, usually by giving it a few specific functions of its own. See Using Stof in Your App.
A document can check what it has before using it. Lib?::func() gives null when a library or function isn't there, so the same document works with or without an optional host library:
const sent = App?::notify('order shipped') ?? false;
Documents Change Themselves
A running document can parse new fields, types, and functions into itself, and remove them again. In this example the app supplies some rules (they could come from a database or a model), and the document loads them, runs them, and drops them:
order: { total: 120, country: 'DE' }
fn apply_rules() {
using rules = new {}; // dropped when this function ends
parse(await App::rules(), rules); // Stof source from the app
for (const rule in rules.funcs('rule')) rule(self.order);
}
- TypeScript
- Python
- Rust
doc.lib('App', 'rules', async () => `
#[rule]
fn vat(order: obj) { if (order.country == 'DE') order.vat = order.total * 0.19; }
#[rule]
fn free_shipping(order: obj) { order.shipping = order.total >= 100 ? 0 : 5; }
`, true);
await doc.call('apply_rules');
doc.record(); // { order: { total: 120, country: 'DE', vat: 22.8, shipping: 0 } }
doc.lib('App', 'rules', lambda: """
#[rule]
fn vat(order: obj) { if (order.country == 'DE') order.vat = order.total * 0.19; }
#[rule]
fn free_shipping(order: obj) { order.shipping = order.total >= 100 ? 0 : 5; }
""")
doc.call('apply_rules')
json.loads(doc.string_export('json')) # {'order': {'total': 120, 'country': 'DE', 'vat': 22.8, 'shipping': 0}}
In Rust, App::rules is a LibFunc you add with graph.insert_libfunc(..) (see Using Stof in Your App). Then:
Runtime::call(&mut graph, "apply_rules", vec![])?;
graph.stringify("json", None)?; // {"order":{"total":120,"country":"DE","vat":22.8,"shipping":0}}
There's no build step. Logic arrives as data, runs, and leaves.
One Runtime, Everywhere
Stof's runtime is written in Rust. The JavaScript package is that same runtime compiled to WebAssembly, and the Python package wraps it too, so a document gives the same result in a browser, in Node.js, on a server, and in Python. It runs in your app's process, with no server or container.
Inside the runtime, each call runs as a lightweight process. Processes take turns, so async functions and await work the same way on every platform, including in a browser. See Async.
Back Out Again
A document built from JSON and extended with types and functions still exports as JSON, YAML, TOML, or any other format the runtime has, at any time:
- TypeScript
- Python
- Rust
doc.stringify('json'); // functions are left out
doc.stringify('yaml');
doc.blobify('bstf'); // everything, functions included
doc.string_export('json') # functions are left out
doc.string_export('yaml')
doc.binary_export() # everything, functions included
graph.stringify("json", None)?; // functions are left out
graph.stringify("yaml", None)?;
graph.blobify("bstf", None)?; // everything, functions included
Add logic, run it, and hand the result to something that has never heard of Stof.