Persistence
Updated
A Persistable keeps data for its entity on a persistence service, so the data is still there after a reload, the next day, or in a new session: a visit counter, a guest book, a high score, the state of a puzzle. Every peer that holds the same entity reads and writes the same record, so the data is shared as well as kept.
Before you start
Section titled “Before you start”- You know how to find an entity and get its component in a script. See Working with entities.
- You can write
asyncfunctions and useawait,tryandcatch. Every Persistable call goes to the service and returns a promise. - You know how a Signal Emitter turns component events into signals. See Scripting.
Persistence and networking
Section titled “Persistence and networking”Persistence and networking solve different problems, and a scene often uses both.
| Networkable | Persistable | |
|---|---|---|
| Shares | Live state with the people in the room now. | Stored data, whoever is connected. |
| Lasts | As long as the room keeps the object. | Across reloads and sessions, until it expires or is dropped. |
| Good for | Moving objects, switches, a live scoreboard. | Counters, high scores, guest books, saved progress. |
How it works
Section titled “How it works”- The Persistable entity (
ent-persistable) carries a required Persistable component. Its record is keyed by the entity’s id, which is saved with the scene, so the data comes back after a reload. - Values are JSON values stored under string keys, like the fields of an object.
- Scripts read and write the record through the component. Every call is asynchronous.
- With a Signal Emitter on the entity, the Persistable reports changes: its own, and those other peers make.
- Persistable is offered on the Persistable entity and the AI Agent entity.
PersistableComponent, type comp-persistable.
| Prop | Type | Default | Description |
|---|---|---|---|
storage |
'memory' or 'disk' |
'memory' |
Which of the service’s two stores keeps the record. A new Persistable entity uses 'disk'. |
retention |
number | none | How long the record is kept after it was last used, in minutes, from 60 (an hour) to 43 200 (30 days). Each successful read or write renews it. A new Persistable entity uses 10 080 (7 days). Left out, no retention is set. |
Methods
Section titled “Methods”| Member | Description |
|---|---|
get(key, default |
The stored value, or defaultValue when the key is absent or the request fails. |
set(key, value) |
Store a value under key, replacing what was there. |
delete(key) |
Remove one key. |
inc(key, value) |
Add value to a stored number. |
mult(key, value) |
Multiply a stored number by value. |
arr |
Append to a stored array. |
arr |
Insert into a stored array at index. |
arr |
Remove every occurrence of value from a stored array. |
arr |
Remove the item at index from a stored array. |
inspect() |
The whole stored state, or null on failure. |
clear() |
Reset the stored state to an empty object. Resolves true on success. |
drop() |
Delete the record outright. Resolves true when it was removed or already absent. |
ttl(timestamp) |
Expire the stored state at a Unix timestamp, in milliseconds. Resolves true on success. |
lock(timeout) |
Take the lock for timeout milliseconds, so this instance’s writes are accepted while others are held off. Resolves true when it got it. |
unlock() |
Release a lock this instance holds. Calling it without holding the lock is an error. |
locked |
Whether this instance holds the lock. |
The writing calls (set, delete, inc, mult and the arr… calls) resolve to the stored state after the change, and reject when the service refuses. Wrap them in try and catch. delete and arrPull also succeed when there is nothing to remove.
Events
Section titled “Events”Add a Signal Emitter to the Persistable’s entity to receive these:
| Event | Data | When |
|---|---|---|
Persistable::change |
{ prop?, values?, origin?, event |
A write changed the stored state. |
Persistable::cleared |
{ values?, origin?, event |
The state was emptied with clear() or deleted with drop(). |
Persistable::error |
{ message } |
A call failed. |
| Field | Description |
|---|---|
prop |
The key a local write changed, when it named one. |
values |
The stored state after the change. |
origin |
Absent for this peer’s own writes; 'remote' for a change another peer made; 'sync' when the state was read again to catch up. |
eventId |
The id of a remote change, to tell repeats apart. |
message |
What went wrong, on error. |
- Reads (
get,inspect) and locking send no event. - Changes made by other peers are followed only while the entity has an enabled Signal Emitter with a signal. A Persistable nobody listens to does no background work.
- Every failure is also written to the script log.
Examples
Section titled “Examples”1. A visit counter
Section titled “1. A visit counter”#pragma lifecycle(startup)
async function startup() { const store = findEntity('Visits').getComponent(PersistableComponent); const label = findEntity('Visit Count').getComponent(UILabelComponent);
try { const state = await store.inc('count', 1); label.setProps({ text: `Visit number ${state.count}` }); } catch (error) { const count = await store.get('count', 0); label.setProps({ text: `Visits: ${count} (offline)` }); }}A Persistable adds one to a stored count each time the scene starts, with inc, and a UI Label shows the total, or the last known value when the write fails.
Read the label, then run the example again. Without the persistence service the write fails and the label shows the offline value.
incadds one and resolves to the whole stored state, sostate.countis the new total.- If the write fails,
getwith a default still shows something.
Snippets
Section titled “Snippets”1. A live guest book
Section titled “1. A live guest book”#pragma lifecycle(startup)
// Scene: a Persistable entity named "Guest Book" with a Signal Emitter on// 'guestbook'. A "Name" UI Input with a Signal Emitter on 'guestbook/input',// and an "Entries" UI Label.let store;let entries;
function render(names) { entries.setProps({ text: (names ?? []).slice(-10).join('\n') || 'Be the first to sign!' });}
async function startup() { store = findEntity('Guest Book').getComponent(PersistableComponent); entries = findEntity('Entries').getComponent(UILabelComponent);
render(await store.get('names', []));
// Our writes and other peers' writes both arrive here. on('guestbook', (event) => { if (event.eventType === EventType.Persistable.Change) render(event.data.values?.names); if (event.eventType === EventType.Persistable.Error) log('Guest book:', event.data.message); });
on('guestbook/input', async (event) => { if (event.eventType !== EventType.UIInput.Submit) return; const name = event.data.text.trim(); if (!name) return; try { await store.arrPush('names', name); } catch (error) { log('Could not sign the book'); } });}arrPushappends to the stored array; thechangeevent carries the full state invalues.- Because the Signal Emitter has a signal, changes made by other visitors arrive too, with
origin: 'remote'. - The label shows the last ten names.
2. A high score that only goes up
Section titled “2. A high score that only goes up”#pragma lifecycle(startup)
// Scene: a Persistable entity named "Records". Game scripts emit// 'game/over' with the final score as data.let store;
async function submit(score) { // Hold the record while we compare and write, so two players cannot overwrite each other. if (!(await store.lock(2000))) { log('Record busy, try again'); return; } try { const best = await store.get('best', 0); if (score > best) { await store.set('best', score); log(`New record: ${score}`); } } finally { if (store.locked) await store.unlock(); }}
function startup() { store = findEntity('Records').getComponent(PersistableComponent); on('game/over', (score) => submit(score));}lock(2000)holds the record for at most two seconds; while it is held, other peers’ writes are refused.- The
finallyblock always releases the lock, checkinglockedfirst sounlockis never called without it. emit('game/over', 120)from another script passes120straight to the callback.
3. Resetting a puzzle
Section titled “3. Resetting a puzzle”#pragma lifecycle(startup)
// Scene: a Persistable entity named "Puzzle" with a Signal Emitter on 'puzzle',// and a "Reset" UI Button with a Signal Emitter on 'puzzle/reset'.let store;
async function startup() { store = findEntity('Puzzle').getComponent(PersistableComponent);
const state = await store.inspect(); log('Saved puzzle:', state ? JSON.stringify(state) : 'unavailable');
on('puzzle', (event) => { if (event.eventType === EventType.Persistable.Cleared) log('Puzzle was reset'); });
on('puzzle/reset', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; if (await store.clear()) { // Forget it entirely one day from now if nobody plays again. await store.ttl(Date.now() + 24 * 60 * 60 * 1000); } });}inspectreads the whole record at once, ornullwhen the service cannot be reached.clearempties the state and sendsPersistable::clearedto every listening peer.ttltakes an absolute time in milliseconds, so it is built fromDate.now().
Common mistakes
Section titled “Common mistakes”- Not awaiting. Every call returns a promise. Without
await, you read the promise instead of the value. - No
tryaround writes. Writes reject when the service refuses or is unreachable; an uncaught rejection stops the script. - Expecting remote changes without a signal. Other peers’ changes are followed only while the entity has a Signal Emitter with a signal.
- Spawned copies. The record follows the entity’s id. A spawned copy has a new id, so it gets a record of its own.
- Storing functions or class instances. Only JSON values are stored.