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 sealed class Player(IZLinkActorContext context) : IZLinkActor
{
public IZLinkActorContext Context { get; } = context;
public string Nickname { get; private set; } = "anonymous";
public void Rename(string nickname) => Nickname = nickname;
}
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 sealed class PlayerFactory : IZLinkActorFactory<Player>
{
public ValueTask<Player> CreateAsync(
IZLinkActorContext context,
CancellationToken cancellationToken = default
) => ValueTask.FromResult(new Player(context));
async ValueTask<IZLinkActor> IZLinkActorFactory.CreateAsync(
IZLinkActorContext context,
CancellationToken cancellationToken
) => await CreateAsync(context, cancellationToken);
}
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 sealed class LobbySpot(IZLinkEntrySpotContext context) : IZLinkEntrySpot<Player>
{
public IZLinkEntrySpotContext Context { get; } = context;
// Runs after the move is committed, on the side the player arrived at.
public ValueTask OnJoinedActorAsync(Player player, CancellationToken cancellationToken) =>
ValueTask.CompletedTask;
// Runs on the side the player left. The player still exists elsewhere.
public ValueTask OnLeaveActorAsync(Player player, CancellationToken cancellationToken) =>
ValueTask.CompletedTask;
}
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 sealed class ChangeNicknameHandler
: IZLinkEntrySpotActorSendHandler<LobbySpot, Player, ChangeNickname>
{
public async ValueTask HandleAsync(
LobbySpot lobby,
Player player,
IZLinkMessageContext context,
ChangeNickname message,
CancellationToken cancellationToken
)
{
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)).Async();
}
catch (ZLinkFrameworkException error)
when (error.Kind == ZLinkFrameworkErrorKind.InvalidOperation) { }
}
}
For a handler that returns a value, that value becomes the response.
public sealed class GetPlayerHandler
: IZLinkEntrySpotActorRequestHandler<LobbySpot, Player, GetPlayer, PlayerInfo>
{
public ValueTask<PlayerInfo> HandleAsync(
LobbySpot lobby,
Player player,
IZLinkMessageContext context,
GetPlayer request,
CancellationToken cancellationToken
) => ValueTask.FromResult(new 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>();
// Nodes that register "player" are candidates to host one.
objects.AddActorFactory<Player, PlayerFactory>(
"player",
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.
var mesh = options
.AddRouteMesh("game")
.Listen("tcp://127.0.0.1:7201")
.SetRoutingId(RoutingId.From("game-server-1"));
The call that creates the Actor in that mesh follows.
app.MapPost(
"/players/{playerId}",
async (
string playerId,
CreatePlayer request,
IZLinkActorManager players,
CancellationToken cancellationToken
) =>
{
// GetOrCreate returns the existing player if there is one. The caller does
// not choose which node hosts it.
var result = await players
.GetOrCreate(playerId, "player")
.InMesh("game")
.Request(request)
.Timeout(TimeSpan.FromSeconds(10))
.Async(cancellationToken);
return result switch
{
ZLinkActorCreateResult.Existing => Results.Ok("existing"),
ZLinkActorCreateResult.Created => Results.Ok("created"),
_ => Results.BadRequest("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.
app.MapPost(
"/players/{playerId}/nickname",
async (
string playerId,
ChangeNickname message,
IZLinkActorClient players,
CancellationToken cancellationToken
) =>
{
// Addressed by player id, like a room is by room id.
await players.SendToActor(playerId, message).Async();
return Results.Accepted();
}
);
When you need an answer, send a request.
app.MapGet(
"/players/{playerId}",
async (string playerId, IZLinkActorClient players, CancellationToken cancellationToken) =>
{
var info = await players
.RequestToActor(playerId, new GetPlayer())
.Timeout(TimeSpan.FromSeconds(3))
.Async<PlayerInfo>(cancellationToken);
return Results.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.
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