Tutorial

Build a team chat, step by step.

A team chat is a system of things with lifecycles: workspaces that make rooms, rooms that fan out posts, people who connect, go idle and leave. This tutorial builds one in five steps. Each step is a program you can run, and each adds one idea to the step before. By the end, a thousand users run with fifty of them in memory.

Node.js and Bun
npm install @tinyactors/node

Start with a roomGet the code

Step 1

A room is an actor.

A room keeps a list of members. Your program sends it events, and it sends each post out. Its chart has one state. A join adds a member, and a post sends the message to an I/O processor of type chat:client:

charts/room.scxmlscxml
<state id="open">
  <transition event="join">
    <assign location="members" expr="members.concat([_event.data.user])"/>
  </transition>
  <transition event="post">
    <send type="chat:client" event="message">
      <content expr="({ to: members, from: _event.data.user, text: _event.data.text })"/>
    </send>
  </transition>
</state>

The program gives the host that processor: an object with receive(send), standing in for the users' screens. Then it starts one room and sends it three events.

main.mjsjavascript
// The client processor stands in for the users' screens.
class Client {
  lines = [];

  receive(send) {
    for (const user of send.data.to) this.lines.push(`${user} sees ${send.data.from}: ${send.data.text}`);
  }
}
main.mjsjavascript
const room = host.spawn('room', { name: 'general' });
room.send('join', { user: 'ada' });
room.send('join', { user: 'bob' });
room.send('post', { user: 'ada', text: 'hi' });
await host.idle();
output
ada sees ada: hi
bob sees ada: hi

The room does no I/O. It decides who gets a message, and your program delivers it.

Step 2

People come and go.

Each user is now an actor too, offline, active or away. online holds active and away, so one disconnect leaves either. An active user turns away after 300 seconds without activity: entering active sends the actor an idle event, delayed, and activity cancels it and starts it again.

charts/user.scxmlscxml
<state id="online" initial="active">
  <transition event="disconnect" target="offline"/>
  <transition event="message">
    <send type="chat:client" event="message"><content expr="({ to: name, from: _event.data.from, text: _event.data.text })"/></send>
  </transition>
  <state id="active">
    <onentry>
      <send type="chat:client" event="status"><content expr="({ user: name, status: 'active' })"/></send>
      <send id="idle" event="idle" delay="300s"/>
    </onentry>
    <onexit><cancel sendid="idle"/></onexit>
    <transition event="activity">            <!-- no target: the state stays, the timer starts again -->
      <cancel sendid="idle"/>
      <send id="idle" event="idle" delay="300s"/>
    </transition>
    <transition event="idle" target="away"/>
  </state>
  <state id="away">
    <onentry>
      <send type="chat:client" event="status"><content expr="({ user: name, status: 'away' })"/></send>
    </onentry>
    <transition event="activity" target="active"/>
  </state>
</state>

The room no longer talks to your program. It sends each post to each member's user actor, by name, and a user shows a message only while it is online. An offline user has no transition for message, so the event is dropped.

charts/room.scxmlscxml
<transition event="post">
  <foreach array="members" item="member">
    <send targetexpr="'tinyactors://chat/@user.' + member" event="message">
      <content expr="({ from: _event.data.user, text: _event.data.text })"/>
    </send>
  </foreach>
</transition>

The program runs on a SimulatedClock, so 300 seconds take no time:

main.mjsjavascript
client.lines.push('-- 300 seconds pass');
clock.increment(300_000);
await host.idle();

client.lines.push('-- bob types, ada closes the app');
host.actor('user.bob').send('activity');
host.actor('user.ada').send('disconnect');
room.send('post', { user: 'bob', text: 'anyone?' });
await host.idle();
output
ada is offline
bob is offline
ada is active
bob is active
-- 300 seconds pass
ada is away
bob is away
-- bob types, ada closes the app
bob is active
ada is offline
bob sees bob: anyone?

Step 3

The workspace makes the rooms.

In step 2 your program spawned the room. Now a workspace actor decides which rooms exist, and it alone spawns them. It sends a request to the package's Spawner, an I/O processor that spawns actors, and remembers who asked under the request's send id. The Spawner answers spawned with that id. A second request for one name finds it in rooms or in creating, so no room is made twice.

charts/workspace.scxmlscxml
<state id="ready">
  <transition event="room.create" cond="refusal(rooms, creating, _event.data.name) === null">
    <send type="spawn" event="spawn" idlocation="sendid">
      <content expr="({ chart: 'room', name: 'room.' + _event.data.name, params: { name: _event.data.name } })"/>
    </send>
    <assign location="creating[sendid]" expr="({ name: _event.data.name, by: _event.origin })"/>
  </transition>
  <transition event="room.create">
    <send targetexpr="_event.origin" event="room.refused">
      <content expr="({ name: _event.data.name, reason: refusal(rooms, creating, _event.data.name) })"/>
    </send>
  </transition>

  <!-- the Spawner answers by the sendid of the spawn -->
  <transition event="spawned" cond="_event.sendid in creating">
    <assign location="rooms" expr="rooms.concat([creating[_event.sendid].name])"/>
    <send targetexpr="creating[_event.sendid].by" event="room.created">
      <content expr="({ name: creating[_event.sendid].name })"/>
    </send>
    <script>delete creating[_event.sendid];</script>
  </transition>

The user actor now joins rooms and posts to them, by name. A send to a name no actor has fails at once: the sender gets error.communication with the send's id, and tells its screen.

charts/user.scxmlscxml
<transition event="join">
  <send id="join" targetexpr="'tinyactors://chat/@room.' + _event.data.room" event="join">
    <content expr="({ user: name })"/>
  </send>
  <raise event="activity"/>
</transition>
<transition event="joined">
  <send type="chat:client" event="joined"><content expr="({ to: name, room: _event.data.room })"/></send>
</transition>
<transition event="error.communication" cond="_event.sendid === 'join'">
  <send type="chat:client" event="error"><content expr="({ to: name, reason: 'no such room' })"/></send>
</transition>

Your program asks the workspace with actor.ask. The workspace answers to _event.origin, and ask returns the answer.

main.mjsjavascript
for (const name of ['general', 'general', 'Bad Name']) {
  const [event, data] = await workspace.ask('room.create', { name });
  client.lines.push(`create ${name}: ${event}${data.reason ? ` (${data.reason})` : ''}`);
}
const [, { rooms }] = await workspace.ask('rooms.list');
client.lines.push(`rooms: ${rooms.join(', ')}`);

ada.send('join', { room: 'general' });
bob.send('join', { room: 'general' });
bob.send('join', { room: 'random' });
output
create general: room.created
create general: room.refused (exists)
create Bad Name: room.refused (invalid name)
rooms: general
ada joined general
bob gets an error: no such room
bob joined general
ada sees ada in general: hi
bob sees ada in general: hi

Step 4

Everyone sees who is here.

The workspace now keeps a roster of each user's status. Each state of a user reports itself to the workspace on entry, so a status is sent only when it changes. A user who comes online gets the whole roster, and the other online users get each change.

charts/workspace.scxmlscxml
<transition event="status">
  <assign location="arriving" expr="cameOnline(roster, _event)"/>
  <assign location="roster[_event.data.user]" expr="_event.data.status"/>
  <if cond="arriving">
    <send targetexpr="_event.origin" event="roster"><content expr="({ roster: roster })"/></send>
  </if>
  <foreach array="online(roster, _event.data.user)" item="user">
    <send targetexpr="'tinyactors://chat/@user.' + user" event="roster.update">
      <content expr="_event.data"/>
    </send>
  </foreach>
</transition>

cameOnline and online are functions of the chart's <script>, which take the variables they read as arguments.

output
-- ada connects
ada sees the roster: ada active, bob offline, cat offline
-- bob connects
bob sees the roster: ada active, bob active, cat offline
ada sees bob is active
-- 300 seconds pass
bob sees ada is away
ada sees bob is away
-- bob closes the app
ada sees bob is offline
the workspace answers: {"ada":"away","bob":"offline","cat":"offline"}

Step 5

A thousand users, fifty in memory.

Most users and rooms wait most of the time, so the host can keep them out of memory. The charts do not change in this step, only the host's options. resident is the most actors the host keeps in memory: after each turn it hibernates the rest into store, an object with save, load and delete.

main.mjsjavascript
const host = new Host(compiled, {
  system: 'chat',
  clock,
  store,
  resident,
  ioProcessors: { 'chat:client': client, spawn: new Spawner() },
  ...options,
});
output
1000 users spawned: 1002 actors, 50 in memory, 952 in the store
100 users connect and join general: 1002 actors, 50 in memory, 952 in the store
u0 posts: 1002 actors, 50 in memory, 952 in the store
100 messages reached the screens
300 seconds pass: 1002 actors, 50 in memory, 952 in the store
14850 roster updates reached the screens
the store saved 1156 blobs and loaded 204
at most 50 actors were in memory at rest

An event for a hibernated actor wakes it: the host loads its blob, deletes it from the store and delivers the event. A user's idle timer stays in the host while the user is out of memory, and wakes the user when it is due. Your program never wakes an actor itself. The post reached a hundred users, most of them in the store, and the bound held throughout.

This store keeps the blobs in a Map. The package has MemoryStore, and SQLiteStore for blobs that outlive the process.

Next

From here to production.

The charts stay as they are. What changes is what your program connects them to.

  • ConnectionsThe chat:client processor writes to each user's socket instead of a list, and a socket's close sends disconnect.
  • StorageSQLiteStore keeps hibernated users and rooms on disk, and a snapshot keeps the whole host.
  • New versionsAdd a new version of the user chart: new users start in it, and a migration moves the running ones while messages keep coming.
  • TelemetryEvery step an actor takes is a span, so a slow post shows which room and which users it went through.

Read the Node.js guideSimulate a chart