Actor¶
Guide Home | Previous: Spot | Next: STREAM
View in another language — C++ · C#/.NET · Java · Kotlin · Node/TypeScript
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.
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.
public final class Player implements ZLinkActor {
private final ZLinkActorContext context;
private String nickname = "anonymous";
public Player(ZLinkActorContext context) {
this.context = context;
}
@Override
public ZLinkActorContext context() {
return context;
}
public String nickname() {
return nickname;
}
public void rename(String value) {
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.
public final class PlayerFactory implements ZLinkActorFactory {
@Override
public CompletionStage<ZLinkActor> create(ZLinkActorContext context) {
return CompletableFuture.completedFuture(new 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.
public final class LobbySpot implements ZLinkEntrySpot<Player> {
private final ZLinkEntrySpotContext context;
public LobbySpot(ZLinkEntrySpotContext context) {
this.context = context;
// A message addressed to a player runs inside the Spot the player
// currently occupies, so these handlers are registered on the lobby.
context.handlers().addHandler(ChangeNicknameHandler.class);
context.handlers().addHandler(GetPlayerHandler.class);
}
@Override
public ZLinkEntrySpotContext context() {
return context;
}
@Override
public CompletionStage<Void> onJoinedActor(Player player) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletionStage<Void> onLeaveActor(Player player) {
return CompletableFuture.completedFuture(null);
}
}
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.
public final class ChangeNicknameHandler
implements ZLinkEntrySpotActorSendHandler<LobbySpot, Player, Contracts.ChangeNickname> {
@Override
public CompletionStage<Void> handle(
LobbySpot lobby,
Player player,
ZLinkMessageContext context,
Contracts.ChangeNickname message) {
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.
return player.context()
.boundSession()
.send(new Contracts.NicknameChanged(player.nickname()))
.submit()
.exceptionally(
error -> {
if (error instanceof ZLinkFrameworkException framework
&& framework.kind()
== ZLinkFrameworkErrorKind.INVALID_OPERATION) {
return null;
}
throw new CompletionException(error);
});
}
}
For a handler that returns a value, that value becomes the response.
// The return value is the reply. This handler only reads.
public final class GetPlayerHandler
implements ZLinkEntrySpotActorRequestHandler<
LobbySpot, Player, Contracts.GetPlayer, Contracts.PlayerInfo> {
@Override
public CompletionStage<Contracts.PlayerInfo> handle(
LobbySpot lobby,
Player player,
ZLinkMessageContext context,
Contracts.GetPlayer request) {
return CompletableFuture.completedFuture(
new Contracts.PlayerInfo(player.context().actorId(), 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.class);
// Nodes that register "player" are candidates to host one.
objects.addActorFactory(
"player",
Player.class,
PlayerFactory.class,
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.
//
// A caller that names a routing id in connect(...) compares the advertised
// endpoint against the endpoint it dialed. Both use 127.0.0.1 here.
ZLinkMeshNodeBuilder mesh =
options.addRouteMesh("game")
.listen("tcp://127.0.0.1:7501")
.setAdvertiseHost("127.0.0.1")
.setRoutingId(RoutingId.from("game-server-1"));
The call that creates the Actor in that mesh follows.
@PostMapping("/players/{playerId}")
CompletionStage<String> createPlayer(
@PathVariable String playerId, @RequestBody Contracts.CreatePlayer request) {
// getOrCreate returns the existing player if there is one. The caller
// does not choose which node hosts it.
return playerManager
.getOrCreate(playerId, "player")
.inMesh("game")
.request(request)
.timeout(Duration.ofSeconds(10))
.submit()
.thenApply(
result ->
switch (result) {
case ZLinkActorCreateResult.Existing ignored -> "existing";
case ZLinkActorCreateResult.Created ignored -> "created";
case ZLinkActorCreateResult.Rejected ignored -> "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")
CompletionStage<ResponseEntity<Void>> changeNickname(
@PathVariable String playerId, @RequestBody Contracts.ChangeNickname message) {
// Addressed by player id, like a room is by room id.
return players.sendToActor(playerId, message)
.submit()
.thenApply(ignored -> ResponseEntity.accepted().build());
}
When you need an answer, send a request.
@GetMapping("/players/{playerId}")
CompletionStage<Contracts.PlayerInfo> getPlayer(@PathVariable String playerId) {
return players.requestToActor(playerId, new Contracts.GetPlayer())
.timeout(Duration.ofSeconds(3))
.submit(Contracts.PlayerInfo.class);
}
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.
6. Related Documents¶
- A place several parties share — Spot
- The path that calls by name — Channel Messaging
- Moving and membership — Actor Membership
- A running version of this chapter's code — the tutorial README in the examples repository