See what your actors did in OpenTelemetry
Each step an actor takes becomes a span with its event and the states it left and entered, in the caller's trace when it passes one. Your code sends the OTLP bytes to the collector it chooses.
Decide where the OTLP bytes go
The host writes OTLP requests, the protobuf bytes a collector takes at /v1/traces, /v1/logs and /v1/metrics. Your code posts them where it chooses, and retries when it must (operating a host).
A step's span holds the event, the transitions, and the states left and entered. Each <log> and failed action becomes a log record, and the host's counters become metrics.
Turning telemetry on changes nothing an actor does. Telemetry: every step is a span runs a traced payment in your browser and shows its spans.
Export spans to your collector
A telemetry map in the config makes the host write OTLP. A telemetry handler in the options gets each request it writes as a Buffer, with its signal, 'traces' or 'logs'.
This order continues a caller's trace, and its spans come back with the caller's span as their parent:
import { compileCharts, decodeTraces, Host, SimulatedClock } 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">
<state id="open">
<transition event="pay" target="paid"><log label="order" expr="'paid'"/></transition>
</state>
<final id="paid"/>
</scxml>` }]);
const requests = [];
const clock = new SimulatedClock();
const host = new Host(compiled, {
system: 'shop',
config: {
system: { ticksPerSecond: 1000 }, // the host's clock in milliseconds
telemetry: { flushInterval: 1000, resource: { 'service.name': 'shop' } }, // a request at most a second after its first record
},
clock,
telemetry: (signal, data) => {
// A real exporter posts the bytes, from a promise so the host goes on:
// fetch(`${collector}/v1/${signal}`, { method: 'POST', headers: { 'content-type': 'application/x-protobuf' }, body: data })
requests.push([signal, data]);
},
});
compiled.close();
const caller = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'; // a W3C traceparent, from an HTTP header
host.spawn('order').send('pay', undefined, { traceparent: caller });
await host.idle();
console.log('requests before the flush interval:', requests.length);
clock.increment(1000);
await host.idle();
console.log('signals:', requests.map(([signal]) => signal).sort().join(', '));
// Read the spans back (for a test; a collector does this for you).
for (const [signal, data] of requests) {
if (signal !== 'traces') continue;
const spans = decodeTraces(data);
const ours = spans.filter((span) => span.trace === '0af7651916cd43dd8448eb211c80319c');
console.log('spans in the caller\'s trace:', ours.map((span) => span.name).sort().join(', '));
const step = ours.find((span) => span.name === 'scxml.macrostep pay');
console.log('the step\'s parent is the caller\'s span:', step.parent === 'b7ad6b7169203331');
}
host.close();requests before the flush interval: 0
signals: logs, traces
spans in the caller's trace: scxml.destroyed, scxml.finished, scxml.macrostep pay, scxml.microstep pay
the step's parent is the caller's span: trueThe handler runs in the host's turn, so start the post there and return without waiting for the collector. decodeTraces reads an export without a host (Wire format).
A handler's error is the turn's (Errors). The request it failed to send is not offered again, so retrying is the exporter's job.
Choose how soon records are sent
Every key of the config's telemetry map is optional, and flushInterval decides how soon a request is ready:
| Key | Default | What it does |
|---|---|---|
flushInterval | 0 | a request is ready this long after its first record, in the host's clock ticks (system.ticksPerSecond); 0 means only when the staging is full, or at close |
resource | none | attributes on every request, such as service.name (at most 32, text to text) |
logs | true | <log> lines and failed actions as log records |
values | false | event data and assigned values in the spans; they may hold personal data, so turn this on knowingly |
linkParents | false | an actor's step is a root span linked to its cause, instead of its child |
stagingBytes | 1048576 | the encoder's staging memory |
The host's clock runs at system.ticksPerSecond, a billion by default, so a flushInterval of 5000 is five microseconds. Most programs that export set ticksPerSecond: 1000 and give the interval in milliseconds.
Step a test's clock past the flush
Once records wait to be sent, the flush is one of the host's deadlines. host.nextDeadline reads it even when no actor has a delayed send left.
The host arms its timer for it, which keeps the process alive until then. A test that asserts no timer is left steps its clock past the flush first:
import { compileCharts, Host, SimulatedClock } 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">
<final id="done"/>
</scxml>` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, {
system: 'shop',
config: { system: { ticksPerSecond: 1000 }, telemetry: { flushInterval: 1000 } },
clock,
telemetry: (signal) => console.log(signal, 'at', clock.now),
});
compiled.close();
host.spawn('job');
await host.idle();
console.log('the job ended; nextDeadline', host.nextDeadline);
clock.increment(host.nextDeadline ?? 0);
await host.idle();
console.log('flushed; nextDeadline', host.nextDeadline);
host.close();the job ended; nextDeadline 1000
traces at 1000
logs at 1000
flushed; nextDeadline undefinedRead metrics on your own schedule
host.metrics() returns the metrics request for the host's counters now, a Buffer for /v1/metrics. On a host without telemetry in its config it throws TA_ERROR_STATE.
Close the host to send the last spans
At host.close() every open span ends, marked incomplete, and the handler gets the last requests before the host is freed.
await host[Symbol.asyncDispose]() also awaits a promise the handler returns there. A host the garbage collector frees without close() sends none of it: close the hosts whose telemetry you want.
Continue a trace across requests
An input continues the trace a W3C traceparent header's text names, and text that does not parse starts a new trace. Pass it as an option:
actor.send(event, data, { traceparent })host.send(actor, event, data, { traceparent })host.spawn(chart, { traceparent })
A send's traceparent is the sending step's context: put it in the header of your request for that send. This handler reads the trace its request would carry:
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="c" initial="s">
<state id="s">
<transition event="go"><send type="urn:example:api" event="call"/></transition>
</state>
</scxml>` }]);
const host = new Host(compiled, {
system: 'demo',
ioProcessors: {
'urn:example:api': {
receive(send) {
const [, trace] = send.traceparent.split('-');
console.log('the outgoing request continues trace', trace);
// fetch(url, { headers: { traceparent: send.traceparent } })
},
},
},
});
compiled.close();
host.spawn('c').send('go', undefined, {
traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
});
await host.idle();
host.close();the outgoing request continues trace 4bf92f3577b34da6a3ce929d0e0e4736send.answer() continues the send's trace unless given another, and null starts a new one.
Tracing is on by default (system.tracing), with or without telemetry in the config, so trace context flows when nothing is exported.
Seed trace IDs to repeat a test's traces
A trace the host starts takes its ID from a generator seeded by system.traceSeed. With none in the config, the package draws a random seed for each new host (crypto.getRandomValues).
So two processes, or one process and its restart, do not collide at the collector. The same seed gives the same IDs, which reproduces a test's traces:
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
datamodel="ecmascript" name="c" initial="s">
<state id="s"><onentry><send type="urn:example:api" event="call"/></onentry></state>
</scxml>` }]);
const image = compiled.image;
compiled.close();
const firstTrace = async (system) => {
let trace;
const host = new Host(image, {
system: 'demo',
config: { system },
ioProcessors: { 'urn:example:api': { receive: (send) => { trace = send.traceparent.split('-')[1]; } } },
});
host.spawn('c');
await host.idle();
host.close();
return trace;
};
console.log('no seed, twice:', (await firstTrace({})) === (await firstTrace({})));
console.log('seed 7, twice:', (await firstTrace({ traceSeed: 7 })) === (await firstTrace({ traceSeed: 7 })));no seed, twice: false
seed 7, twice: trueA host made with Host.restore keeps the snapshot's generators, so its IDs go on from where the snapshot left them.
Change what is traced while the host runs
Call these methods on the host to change what it records while it runs (Inspecting a host):
traceConfigure(params)sets what every actor traces:detail('summary','decisions','full'or'off'),values,sample(the share of new traces sampled, 0 to 1) andrules. It replaces the previous configuration.traceWatch({ rules, seconds })adds rules in front of the configured ones for a while (900 seconds by default) and answers{ id }. A watch is how an operator looks closely at one chart or one actor without tracing everything.traceUnwatch({ id })ends a watch early.traceEnd()ends every open span now, asclose()does.traceSpansDecode({ traces })reads the spans of a traces request back through the host.decodeTraces(bytes)needs no host, and also gives each span'sflags,links,resourceandscope.
A rule picks the steps it applies to, then says how to trace them:
- What it matches
chart,actor(a trailing*makes it a prefix),event(SCXML's prefix rule),sessionorfrom, which is'host','actor','timer','spawn'and so on. - What it decides
sample('keep','sample','drop'or a share) anddetail, at mostperSecondwith aburst.
This host samples 1 trace in 100 in summary, then traces every checkout in full for a minute:
import { Host } from '@tinyactors/node';
const host = new Host([], { system: 'shop', config: { telemetry: {} } });
await host.traceConfigure({ detail: 'summary', sample: 0.01 });
console.log('1 trace in 100, summarized');
const watch = await host.traceWatch({ rules: [{ chart: 'checkout', sample: 'keep', detail: 'full' }], seconds: 60 });
console.log(`watch ${watch.id}: every checkout in full for a minute`);
host.close();1 trace in 100, summarized
watch 1: every checkout in full for a minute