Ask a running host what its actors do
await actor.state() tells you which state a running actor is in, and await host.hostStats() counts what each chart has done.
Read an actor's state and variables
actor.state(), actor.context() and actor.get() each return a promise. Each reads the host as it is at the call, and settles on a later turn of the event loop.
An application calls these on its Actors. An operator asks the same of host, as in await host.actorState({ session }) (Operating a host).
This program adds tea to an order, then reads its state, its variables and its mailbox.
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="order" initial="open">
<datamodel>
<data id="items" expr="[]"/>
</datamodel>
<state id="open" initial="browsing">
<state id="browsing">
<transition event="add"><script>items.push(_event.data)</script></transition>
</state>
</state>
</scxml>` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const order = host.spawn('order', { name: 'first' });
order.send('add', 'tea');
await host.idle(); // the actor has started and handled 'add'
const { value } = await host.actorState({ session: order });
console.log('state:', JSON.stringify(value));
const { variables } = await order.context();
console.log('variables:', JSON.stringify(variables));
const actor = await order.get();
console.log('actor:', actor.chart, 'mailbox', actor.mailbox);
host.close();state: {"open":"browsing"}
variables: {"items":["tea"]}
actor: order mailbox 0A state reads as nested objects, one key per compound state: {"open": "browsing"} is browsing inside open. A parallel state has one key per region: {"p": {"r1": ..., "r2": ...}}.
Await host.idle() before you ask. Until a spawned actor first runs, it has no active state and every variable reads undefined, its params included.
Its <data> get their values, from expr or params, when it first runs. Then a variable holding undefined reads undefined and one holding null reads null, on both datamodels.
See when an actor acts next
actorGet tells when a waiting actor acts next, and actorState which state it will go back to.
timersThe actor's pending delayed sends, each<send delay>not yet due and not cancelled, earliest first, as{ sendid, event, due }.dueis in milliseconds on the clockhost.now()reads, and a send without anidhas asendidofnull.timersPendingHow many pending delayed sends there are. The list holds at most 32, so atimersPendingabove its length says it was cut.historyFor each history state the actor has recorded, its parent state as it would be entered again, in the shape ofvalue. A history state records when its parent is exited, so before the first exit it is absent andhistoryis{}.
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'review.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="review" initial="reviewing">
<state id="reviewing" initial="draft">
<onentry><send id="sla" event="breach" delay="7200s"/></onentry>
<history id="back" type="deep"><transition target="draft"/></history>
<state id="draft"><transition event="submit" target="legal"/></state>
<state id="legal"/>
<transition event="hold" target="held"/>
</state>
<state id="held"><transition event="release" target="back"/></state>
</scxml>` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'docs', clock });
compiled.close();
const doc = host.spawn('review');
doc.send('submit');
doc.send('hold');
await host.idle();
clock.increment(60_000); // a minute later
const { timers, timersPending } = await host.actorGet({ session: doc });
for (const { sendid, event, due } of timers) console.log(sendid, event, 'in', (due - host.now()) / 1000, 's');
console.log('pending:', timersPending);
const { value, history } = await host.actorState({ session: doc });
console.log('state:', JSON.stringify(value), 'history:', JSON.stringify(history));
host.close();sla breach in 7140 s
pending: 1
state: "held" history: {"back":{"reviewing":"legal"}}A deep history (type="deep") returns to the atomic states it recorded, so its value goes down to them. A shallow one names only the child it recorded, which enters its own initial state.
The host reads timers and history only when asked, so keeping them adds nothing to an event's work.
Pick the method for your question
Each of these calls, the typed methods, takes one object of params and resolves with one result object:
| Method | Params | Result |
|---|---|---|
actorState | { session } | { value, history }: the active states, and where each history state would return (history) |
actorContext | { session } | { variables }: each <data> and its value |
actorGet | { session } | { session, segment, chart, parent, mailbox, invocations, timers, timersPending }; timers are its pending delayed sends (delayed sends) |
actorList | { cursor, limit }, both optional | { sessions, cursor }: a page of sessions; cursor is null after the last page |
hostStats | none | { host, pools, charts }: counters (the host's counters) |
hostConfig | none | the config the host runs with, every default filled in |
traceConfigure, traceWatch, traceUnwatch, traceEnd, traceSpansDecode | Telemetry |
A method without params is called with none: await host.hostStats(). A session param takes an Actor too.
The host checks the params: one the method does not take, of a wrong type or out of range fails. A session that names no actor, ended or never spawned, fails too.
actorContext and actorState refuse a hibernated actor with reason 'state': wake it first (Hibernation).
Catch a question the host refuses
A refused method rejects with a TinyactorsError. Its reason is a word such as stale or unknown, and its path names the param it is about.
Its code is JSON-RPC's number and its message is for people. A call on a closed host rejects the same way.
import { Host } from '@tinyactors/node';
const host = new Host([], { system: 'shop' });
try {
await host.actorState({ session: 99 });
} catch (error) {
console.log(error.reason, error.path, error.code);
}
// @ts-expect-error: a param actorGet does not take, which the types refuse too
await host.actorGet({ name: 'first' }).catch((error) => console.log(error.reason, error.path));
host.close();stale params.session -32001
unknown params.nameCatch each rejection where you await it: host.idle() never sees it. One you do not catch is an unhandled rejection, which ends a Node.js or Bun process by default.
host.close() drops the methods still waiting, and their promises never settle.
Page through every actor
actorList answers a page of sessions and a cursor for the next, null after the last page. This loop reads five actors two at a time.
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="idle"><state id="waiting"/></scxml>` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
for (let i = 0; i < 5; i++) host.spawn('idle');
const sessions = [];
let cursor = 0;
do {
const page = await host.actorList({ cursor, limit: 2 });
sessions.push(...page.sessions);
cursor = page.cursor;
} while (cursor !== null);
console.log('sessions:', sessions.join(' '));
host.close();sessions: 1 2 3 4 5Compare listed sessions as numbers
A result's sessions are numbers, while actor.id and the views give bigints. So result.sessions.includes(actor.id) is false, and a Map keyed by one misses the other.
Compare with Number(actor.id) === listed, or key by String(actor.id) (Actors, sessions and addresses).
The inputs take either as it is, as in host.send(result.sessions[0], ...), and host.actor(result.sessions[0]) gives its Actor. await host.actors({ chart }) reads every page and lists the live actors as Actors.
Count what the host has done
await host.hostStats() gives counters for the whole host, for each segment's pools and for each chart. Here one of three jobs finishes and one hits an error.
hostsegments(live),actorsandhibernated(now),runnable(actors with work waiting),migrations(running),regionBytes(the memory of the live segments),delivered(events put in queues),routed(sends between the host's segments),migrated(actors moved),retired(segments freed after a migration) andfuelClock(the work the host has done, the clock its trace records are stamped with).poolsAn array with one entry per live segment, in segment order. Each entry has itssegmentnumber and one object per pool,actors,events,timers,workspaces,requestsandslabBytes, each{ capacity, used, highWater }:stats.pools[0].actors.used(Capacity and memory).chartsOne entry per chart name, summed over its versions:name,actors,hibernated,spawned,ended,turns,macrosteps,fuel,errorsExecution,errorsCommunication,errorsPlatform(error.platformevents raised in the chart's actors) andfaults(actors the host had to end because their run failed inside the host).
Four of these names are the host's own terms:
- MacrostepEverything one event does to an actor: its transitions and those that follow on their own, until the actor waits for the next event. A microstep is one set of transitions taken together; spans are named after both (Telemetry).
- FuelThe host's unit of work: an action, a transition, and a share of the JavaScript an expression runs.
- TurnOne time an actor is given the processor. It runs until it waits or has spent its fuel for the turn (
system.quantum), so a busy actor cannot starve the others. - WorkspaceThe room an actor needs while it runs. The host has a few, and an actor waits for one.
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'job.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="job" initial="running">
<state id="running">
<transition event="finish" target="done"/>
<transition event="break"><assign location="undeclared" expr="1"/></transition>
</state>
<final id="done"/>
</scxml>` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const jobs = [1, 2, 3].map(() => host.spawn('job'));
jobs[0].send('finish');
jobs[1].send('break');
await host.idle();
const stats = await host.hostStats();
const [job] = stats.charts;
console.log(`${job.name}: ${job.spawned} spawned, ${job.ended} ended, ${job.actors} running, ${job.errorsExecution} execution error`);
console.log(`${stats.host.segments} segment, ${stats.pools[0].actors.used} actors in its pool`);
host.close();job: 3 spawned, 1 ended, 2 running, 1 execution error
1 segment, 2 actors in its poolFind actors that never rest
Actors that answer each other forever keep the host busy, and await host.idle() never resolves. Nothing is logged or thrown, since every step is legal.
The usual cause is SCXML's prefix match (Charts): a transition on join also takes the answer join.refused, and asks again.
Between two readings with no input, a loop's charts gain macrosteps and fuel without end, and host.delivered grows. host.runnable stays above zero, where a host that is only slow drains its queue.
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([
{ name: 'user.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="user">
<state id="s">
<onentry><send event="join" target="tinyactors://chat/@room"/></onentry>
<transition event="join"><send event="join" target="tinyactors://chat/@room"/></transition>
</state>
</scxml>` },
{ name: 'room.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="room">
<state id="s"><transition event="join"><send event="join.refused" targetexpr="_event.origin"/></transition></state>
</scxml>` },
]);
const host = new Host(compiled, { system: 'chat' });
compiled.close();
host.spawn('room', { name: 'room' });
const user = host.spawn('user');
/** The charts whose actors kept working for `ms` with no input given. */
async function busy(host, ms) {
const before = await host.hostStats();
await new Promise((resolve) => setTimeout(resolve, ms));
const after = await host.hostStats();
if (after.host.runnable === 0) return [];
return after.charts
.filter((chart) => chart.macrosteps - (before.charts.find((c) => c.name === chart.name)?.macrosteps ?? 0) > 1000)
.map((chart) => chart.name)
.sort();
}
console.log('busy:', (await busy(host, 200)).join(', '));
user.terminate(); // in production: alert, and fix the chart
await host.idle();
console.log('idle again; busy:', (await busy(host, 50)).length);
host.close();busy: room, user
idle again; busy: 0A watchdog running this on a timer finds such a loop, alerting when a chart stays busy over several readings.
Fix the chart: name the answer so it does not extend the request, as refused.join. Or make the join transition's cond refuse what is not a request.
Pass handlers instead of a promise
Each method also takes handlers, as host.actorState(params, onResult, onError), and then returns nothing. A later turn calls onResult(result), or onError(error) with the same TinyactorsError.
The promise is made only when no handler is given, so a caller that passes handlers pays for none. A method without params takes undefined: host.hostStats(undefined, onResult).
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="idle"><state id="waiting"/></scxml>` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const session = host.spawn('idle');
await host.idle();
host.actorState({ session }, (result) => console.log('state:', JSON.stringify(result.value)));
host.hostStats(undefined, (stats) => console.log('actors:', stats.host.actors));
host.actorGet({ session: 99 }, () => {}, (error) => console.log('error:', error.reason));
console.log('asked');
await host.idle();
host.close();asked
state: "waiting"
actors: 1
error: staleThe handlers ran after asked, in a later turn. Without an onError, an error rejects a waiting host.idle(), or is thrown as an uncaught exception like a handler's.
Check params and results with TypeScript
index.d.ts types each method's params and result (SessionParams, ActorStateResult, ActorListResult, HostStatsResult, EffectiveHostConfig, ...), and the config as HostConfig.
The types hold for the promises and the handlers' result alike. An editor completes stats.pools[0].actors.highWater, and tsc refuses a field a result lacks or a param a method does not take.