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.
class Player(private val actorContext: ZLinkActorContext) : ZLinkActor {

    var nickname: String = "anonymous"
        private set

    override fun context(): ZLinkActorContext = actorContext

    fun rename(value: String) {
        nickname = 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.
class PlayerFactory : ZLinkActorFactory {
    override fun create(context: ZLinkActorContext): CompletionStage<ZLinkActor> =
        CompletableFuture.completedFuture(Player(context))
}

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.
class LobbySpot(override val context: ZLinkEntrySpotContext) : ZLinkSuspendingEntrySpot<Player>() {

    init {
        // The handlers for a player's messages are registered on the Spot the
        // player occupies, which is this lobby.
        context.handlers().addHandler<ChangeNicknameHandler>()
        context.handlers().addHandler<GetPlayerHandler>()
    }

    override suspend fun onJoinedActorSuspending(actor: Player) {}

    override suspend fun onLeaveActorSuspending(actor: Player) {}
}

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.

class ChangeNicknameHandler :
    ZLinkSuspendingEntrySpotActorSendHandler<LobbySpot, Player, ChangeNickname> {
    override suspend fun handle(
        entrySpot: LobbySpot,
        actor: Player,
        context: ZLinkMessageContext,
        message: ChangeNickname,
    ) {
        actor.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 {
            actor.context().boundSession().kotlin().send(NicknameChanged(actor.nickname)).await()
        } catch (error: ZLinkFrameworkException) {
            if (error.kind() != ZLinkFrameworkErrorKind.INVALID_OPERATION) {
                throw error
            }
        }
    }
}

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

class GetPlayerHandler :
    ZLinkSuspendingEntrySpotActorRequestHandler<LobbySpot, Player, GetPlayer, PlayerInfo> {
    override suspend fun handle(
        entrySpot: LobbySpot,
        actor: Player,
        context: ZLinkMessageContext,
        request: GetPlayer,
    ): PlayerInfo = PlayerInfo(actor.context().actorId(), actor.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 "player" are candidates to host one.
objects.addActorFactory<Player, PlayerFactory>("player") { 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.
val mesh =
    options
        .addRouteMesh("game")
        .listen("tcp://127.0.0.1:7601")
        // The advertised endpoint must match the endpoint passed to
        // connect(routingId, endpoint). Both use 127.0.0.1 here.
        .setAdvertiseHost("127.0.0.1")
        .setRoutingId(RoutingId.from("game-server-1"))

The call that creates the Actor in that mesh follows.

@PostMapping("/players/{playerId}")
suspend fun createPlayer(
    @PathVariable playerId: String,
    @RequestBody request: CreatePlayer,
): String {
    // getOrCreate returns the existing player if there is one. The caller
    // does not choose which node hosts it.
    val result =
        playerManager
            .getOrCreate(playerId, "player")
            .inMesh("game")
            .request(request)
            .timeout(Duration.ofSeconds(10))
            .await()

    return when (result) {
        is ZLinkActorCreateResult.Existing -> "existing"
        is ZLinkActorCreateResult.Created -> "created"
        is ZLinkActorCreateResult.Rejected -> "rejected"
    }
}

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.

@PostMapping("/players/{playerId}/nickname")
suspend fun changeNickname(
    @PathVariable playerId: String,
    @RequestBody message: ChangeNickname,
): ResponseEntity<Void> {
    // Addressed by player id, like a room is by room id.
    players.sendToActor(playerId, message).await()

    return ResponseEntity.accepted().build()
}

When you need an answer, send a request.

@GetMapping("/players/{playerId}")
suspend fun getPlayer(@PathVariable playerId: String): PlayerInfo =
    players
        .requestToActor<PlayerInfo>(playerId, GetPlayer())
        .timeout(Duration.ofSeconds(3))
        .await()

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.