Skip to content

Actor

Guide Home | Previous: Spot | Next: STREAM

What you get from this chapter

You can create one entity by id, send messages to it, and receive answers. The code comes from the tutorial README in the examples repository; follow its Download, Build, and Run sections to reproduce the results below.

Spot covered a place several parties share, such as a room or a queue. An Actor holds per-entity state instead — one player, one session. Both are called by id and process one thing at a time; what differs is that an Actor is always inside some Spot. This chapter goes as far as creating one Actor and calling it; moving between rooms and membership are covered by Actor Membership.

1. An Actor Always Belongs to a Spot

An Actor does not float on its own. Right after creation it belongs to an Entry Spot, and entering a room moves it to that User Spot. The Entry Spot is the Spot the Framework creates when the Object Server starts, and it is the default place for an Actor that belongs to no room yet.

↗ View larger

That is why a handler receives both the Spot and the Actor. A message sent to an actor id runs inside the Spot that Actor belongs to now, so that Spot's state and the Actor's state are handled in one place.

An Actor uses the same Location Store as a Spot. The registration code is the one in Spot.

2. The Receiving Side — the Node That Hosts the Actor

The receiving process

The code in this section goes into the process that runs the Actor.

2.1 Writing the Actor

An Actor holds its state in fields and reads its own id from the context.

// A player is addressed by its own id and carries state that outlives any one
// connection. Like a room, its messages run one at a time. The scope is
// TRANSIENT because the Framework builds one instance per player.
@Injectable({ scope: Scope.TRANSIENT })
class Player implements ZLinkActor {
  readonly context!: ZLinkActorContext;

  private currentNickname = 'anonymous';

  get nickname(): string {
    return this.currentNickname;
  }

  rename(value: string): void {
    this.currentNickname = value;
  }
}

An Actor is not made by a constructor. The Framework makes it through a factory, so any dependency it needs is taken there.

// The Framework creates players through this factory rather than by calling a
// constructor, so dependencies can be injected here.
@Injectable()
class PlayerFactory implements ZLinkActorFactory<Player> {
  async create(context: ZLinkActorContext): Promise<Player> {
    const player = new Player();
    (player as { context: ZLinkActorContext }).context = context;
    return player;
  }
}

2.2 Writing the Entry Spot

This is the first place an Actor lands. Unlike a room, an application does not create it; one is registered per Object Server.

// Every new player lands here before joining a room, and returns here after
// leaving one. A node that hosts players registers exactly one of these.
@Injectable({ scope: Scope.TRANSIENT })
class LobbySpot implements ZLinkEntrySpot {
  readonly context!: ZLinkEntrySpotContext;

  // Runs after the move is committed, on the side the player arrived at.
  async onJoinedActor(_actor: ZLinkActor): Promise<void> {}

  // Runs on the side the player left. The player still exists elsewhere.
  async onLeaveActor(_actor: ZLinkActor): Promise<void> {}
}

2.3 Writing the Handlers

A handler receives both the Spot and the Actor as its first two arguments. A handler that returns no value receives a message that arrived by send.

@zlinkEntrySpotActorSendHandler({
  entrySpot: () => LobbySpot,
  actor: () => Player,
  packetName: PacketNames.changeNickname
})
class ChangeNicknameHandler {
  async handle(
    _lobby: LobbySpot,
    player: Player,
    _context: ZLinkMessageContext,
    message: ChangeNickname
  ): Promise<void> {
    player.rename(message.nickname);

    // Pushes over the connection bound to this player. The same handler also runs
    // on an HTTP path with no bound connection, where push ends with InvalidOperation.
    // Rename is already complete, so only that failure is discarded.
    try {
      await player.context.boundSession.send(new NicknameChanged(player.nickname)).submit();
    } catch (error) {
      if (
        !(error instanceof ZLinkFrameworkException) ||
        error.kind !== ZLinkFrameworkErrorKind.InvalidOperation
      ) {
        throw error;
      }
    }
  }
}

For a handler that returns a value, that value becomes the response.

// The return value is the reply. This handler only reads.
@zlinkEntrySpotActorRequestHandler({
  entrySpot: () => LobbySpot,
  actor: () => Player,
  packetName: PacketNames.getPlayer
})
class GetPlayerHandler {
  async handle(
    _lobby: LobbySpot,
    player: Player,
    _context: ZLinkMessageContext,
    _request: GetPlayer
  ): Promise<PlayerInfo> {
    return { playerId: String(player.context.actorId), nickname: player.nickname };
  }
}

2.4 Registration

Register the Entry Spot and the Actor factory on the same Object Server. The nodes that registered the actor type become the creation candidates.

// One lobby per object server. Newly created players start there.
objects.addEntrySpot(LobbySpot);

// Nodes that register the player type are candidates to host one.
objects.addActorFactory(TutorialNames.playerActorType, PlayerFactory, (factory) =>
  factory.disableRelocation()
);

3. The Calling Side — the Node That Calls an Actor

The calling process

The code in this section goes into the other process, the one that creates the Actor and calls it. It pairs with the section above.

Registration is the same as for calling a Spot — the code in the node that calls a Spot is used as it stands.

3.1 Creating

Unlike a Spot, the calling side decides the id, because a value that already exists — a player id — is used as it stands. Call again with the same id and nothing is created; the existing one comes back.

The tutorial Server first defines the game route mesh. A mesh name names the set of nodes that can host an Actor, and inMesh selects the mesh in which a host node is chosen when creating one. The receiving side of Channel Messaging shows the registration code.

// Both sides must name the mesh identically, or they never see each other
// as peers. The routing id names this node; without it the Framework assigns
// a generated one, which a caller cannot type into a URL. This local
// example binds and advertises a loopback endpoint.
const mesh = builder
  .addRouteMesh(TutorialNames.mesh)
  .listen('tcp://127.0.0.1:7701')
  .setAdvertiseHost('127.0.0.1')
  .routingId(TutorialNames.serverRoutingId);

The call that creates the Actor in that mesh follows.

map('POST', /^\/players\/([^/]+)$/, async ([playerId], body) => {
  const request = JSON.parse(body) as { nickname: string };

  // getOrCreate returns the existing player if there is one. The caller does
  // not choose which node hosts it.
  const result = await playerManager
    .getOrCreate(playerId, TutorialNames.playerActorType)
    .inMesh(TutorialNames.mesh)
    .request(new CreatePlayer(request.nickname))
    .timeout(10_000)
    .submit();

  return ok(result.status);
});

The result tells the two apart: created when it was made for the first time, existing when one was found.

3.2 Calling

Give only the actor id. The Framework finds which Spot that Actor is in now.

map('POST', /^\/players\/([^/]+)\/nickname$/, async ([playerId], body) => {
  const message = JSON.parse(body) as { nickname: string };

  // Addressed by player id, like a room is by room id.
  await players.sendToActor(playerId, new ChangeNickname(message.nickname)).submit();

  return accepted();
});

When you need an answer, send a request.

map('GET', /^\/players\/([^/]+)$/, async ([playerId]) => {
  const info = await players
    .requestToActor(playerId, new GetPlayer())
    .timeout(3000)
    .submit<PlayerInfo>();

  return ok(info);
});

3.3 Generation in a Reference

The generation in an ActorRef or SpotRef counts which instance of the same id this is. The Location Store issues it when the object is created; it does not change on join, relocation, or RecreateOnRelocation. Destroying and creating the same id again receives a new generation.

Ordinary messages do not look at generation: they go to the object that exists now. Lifecycle calls such as close, delete, and move through a reference take effect only while that reference's generation equals the current generation. That is why a stale reference cannot touch the new instance under the same id.

4. What You See When You Run It

With the tutorial Server and Client running as the README's Run section specifies, send these curl requests to the Client's HTTP surface: each HTTP response appears on curl stdout, and handler records appear on the Server process's stdout or in server.log.

curl -X POST http://127.0.0.1:5080/players/p7 \
  -H 'Content-Type: application/json' -d '{"nickname":"rookie"}'
# "created"

curl -X POST http://127.0.0.1:5080/players/p7 \
  -H 'Content-Type: application/json' -d '{"nickname":"rookie"}'
# "existing"

curl -X POST http://127.0.0.1:5080/players/p7/nickname \
  -H 'Content-Type: application/json' -d '{"nickname":"veteran"}'
# 202

curl http://127.0.0.1:5080/players/p7
# {"playerId":"p7","nickname":"veteran"}

The point is that the second call answered existing. Calling again with the same id creates nothing. The third call changed the name, and the fourth read the changed value.

5. The Difference from a Spot

Both are called by id and process one thing at a time. To choose between them, look at who decides the id and what it holds. A Spot's id is issued by the Framework at creation, and it holds a place several parties share, such as a room or a queue. An Actor's id is decided by the calling side, and it holds the state of one entity, such as a player or a session.

Moving between rooms is covered by Actor Membership, the membership callbacks per kind by Activation and Lifetime, and preserving state during a move by Relocation.