Keeping state in JS
Every call gets a fresh module: nothing a call leaves in memory reaches the next one. That's what makes a module safe to share, and it means a module that works on a series (running totals, a rate, a game, a parser that resumes) can't keep its own state. The app keeps it instead:
- Your page code loads the state: from a record, or from memory.
- It passes the state in with the call.
- The module returns the new state, and your code saves it.
The module stays a pure function, (state, input) → new state, which also makes it easy to test: each example in its manifest is one step.
The module
example/stats-tinygo keeps running statistics of a series of readings: count, mean, standard deviation, min and max. It uses Welford's method, so the state is five numbers however many readings it has seen. It has two functions:
add:{"state": <state or null>, "values": [...]}→ the new statereport: a state →{count, mean, stddev, min, max}
// State is everything the module needs to go on where the last call stopped. The app stores it as JSON.
type State struct {
Count int `json:"count"`
Mean float64 `json:"mean"`
M2 float64 `json:"m2"` // the sum of squared distances from the mean
Min float64 `json:"min"`
Max float64 `json:"max"`
}
func main() {
switch os.Args[1] {
case "--describe":
fmt.Print(manifest)
case "add":
var in struct {
State *State `json:"state"`
Values []float64 `json:"values"`
}
decode(&in)
s := State{}
if in.State != nil {
s = *in.State
}
for _, v := range in.Values {
// ... update count, mean, m2, min, max
}
encode(s)
case "report":
// ... stddev = sqrt(m2 / count)
default:
fail("no_such_function", os.Args[1])
}
}
Build it with TinyGo:
tinygo build -target=wasip1 -opt=z -no-debug -scheduler=none -o pb_hooks/stats.pb.wasm .
It's 283 KB. Its first call compiles it (about 80 ms); later calls load it from the cache in about 3 ms.
State in a record
Give the collection a JSON field for the state: here, a sensors collection with name (text) and stats (JSON). An API route takes new readings, runs them through the module with the sensor's state, and saves the new state on the record:
// pb_pages/sensors/[id]/readings.ts
// POST /sensors/{id}/readings {"values": [21.5, 22]}: adds readings to the sensor's running statistics
type Stats = { count: number; mean: number; m2: number; min: number; max: number } // the module's state
type Report = { count: number; mean: number; stddev: number; min: number; max: number }
export async function post(ctx: any) {
const sensor = ctx.app.findRecordById("sensors", ctx.params.id)
const { values } = ctx.req.body() as { values: number[] }
try {
const state: Stats | null = JSON.parse(sensor.getString("stats")) // null until the first readings
const next = await $wasm.call.async<Stats>("stats", "add", { state, values })
sensor.set("stats", next)
ctx.app.save(sensor)
return ctx.res.json(await $wasm.call.async<Report>("stats", "report", next))
} catch (err) {
const w = err as WasmError
if (w.name !== "WasmError" || w.retryable) throw err
return ctx.res.json(400, { code: w.code, message: w.message }) // bad_input, bad_value: the caller's mistake
}
}
curl -X POST localhost:8090/sensors/<id>/readings -H "Content-Type: application/json" -d '{"values":[21.5,22]}'
# {"count":2,"max":22,"mean":21.75,"min":21.5,"stddev":0.25}
The record now holds the state, {"count":2,"m2":0.125,"max":22,"mean":21.75,"min":21.5}, and the next readings start from it.
- An empty JSON field reads as
"null", soJSON.parsegivesnullthe first time, and the module starts a new series. - The module's errors come back as
WasmError, with its owncode. Answer the caller's mistakes (bad_input) yourself, and let the rest (busy,timeout) fail the request. - Two requests at once for the same sensor can both read the same state, and the second save drops the first one's readings. If that matters, send a sensor's readings one at a time, or save them as records and fold them into the state from a cron job.
State in memory
State the app can lose on a restart (a cache, a count since start) can stay in memory instead, in $app.store(). It's the app's own key-value store, shared by all its code, and it holds the module's output as it is:
const store = ctx.app.store()
const next = await $wasm.call.async<Stats>("stats", "add", { state: store.get("load") || null, values: [1] })
store.set("load", next)
Each app (each instance, under a host that runs many) has its own store, and a restart empties it: a change in pb_hooks/ restarts the app.
Why not keep it in the module?
A module can't: each call starts from the module's file, with fresh memory, and nothing outlives the call. That's on purpose. One caller's data never reaches another's call, a module that crashes takes nothing with it, and a folder of modules costs nothing between calls. Keeping state in the app also puts it where the app's other tools reach it: the dashboard shows it, backups keep it, and the API rules decide who reads it.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.