Session and Actor¶
Guide Home | Previous: STREAM | Next: Location
View in another language — C++ · C#/.NET · Java · Kotlin · Node/TypeScript
What you get from this chapter
You can bind one external client's connection to one Actor, and have that Actor push a notification back over the same connection. The code comes from the tutorial README in the examples repository; follow its Download, Build, and Run sections to reproduce the results below.
A STREAM session ends when its connection drops. A player's state has to outlive that, and what holds it is an Actor. This chapter binds the two — once bound, packets the session does not handle reach that Actor, and the Actor can push over that connection.
1. The Role of Binding an Actor and a Session¶
Binding connects a connection and an entity whose lifetimes differ. When the same player drops and returns, the connection is a new one and the entity is the one that was already there. So the connection is made to point at its entity, and packets after that are received by the entity.
▶ Try it in the interactive tour — Lobby and dungeon
The session does not disappear once bound. Packets the session knows are handled by the session first, and only the ones it does not know go to the Actor.
2. Deciding the Packets¶
An authentication request, its answer, and the notification the Actor pushes. The last one answers no request.
public sealed record Authenticate(string PlayerId);
public sealed record Authenticated(string PlayerId);
// Pushed by the player to its own connection, with no request to answer.
public sealed record NicknameChanged(string Nickname);
3. The Receiving Side — the Node That Binds the Connection¶
The receiving process
The code in this section goes into the process that registered the stream node in STREAM. Actor dispatch has to be turned on at that registration for the relay in this chapter to work.
3.1 Binding¶
When the client names its id, the Actor for that id is found or created and bound to this connection.
// Binds each authenticated player to this connection. The packet's Actor slot
// then selects which player receives a packet without a session handler.
public sealed class AuthenticateHandler(IZLinkActorManager players)
: IZLinkSessionPacketHandler<IZLinkSessionContext, Authenticate>
{
public async ValueTask HandleAsync(
IZLinkSessionContext context,
ZLinkSessionDispatchContext dispatch,
Authenticate message,
CancellationToken cancellationToken
)
{
// A returning client finds its existing player rather than a new one.
var result = await players
.GetOrCreate(message.PlayerId, "player")
.InMesh("game")
.Request(new CreatePlayer(message.PlayerId))
.Async(cancellationToken);
var player = result switch
{
ZLinkActorCreateResult.Existing value => value.Actor,
ZLinkActorCreateResult.Created value => value.Actor,
_ => throw new InvalidOperationException("Player creation was rejected."),
};
var bound = await context.Actors.BindOrGetAsync(player, cancellationToken);
await context.Client.Reply(new Authenticated(bound.ActorId)).Async();
}
}
A client that returns with the same id binds to the Actor that is already there. That is why creating and finding are one call.
3.2 Forwarding What Is Left¶
Packets the session did not handle are sent to the bound Actor. The dispatch context's Actor names the target for each packet — a packet the client sent through an Actor handle points at that Actor. A packet sent without an Actor handle has no Actor, so when one Actor is bound to this connection it goes to that Actor. With no bound Actor there is nowhere to send it, which is where authentication first is enforced. The client side of telling Actors apart is covered in Receiving Packets §8.
// A slotted packet uses its dispatch Actor. An unslotted packet can use
// the connection only while exactly one Actor is bound.
var actor =
dispatch.Actor
?? (
Context.Actors.Bound.Count switch
{
1 => Context.Actors.Bound.Single(),
0 => throw new InvalidOperationException(
"Authenticate an Actor before sending player packets."
),
_ => throw new InvalidOperationException(
"Select an Actor handle when more than one Actor is bound."
),
}
);
await actor.RelayAsync(payload);
A forwarded packet is received by that Actor's handler — the same handler written in Actor. One handler is called both by a mesh call and by a STREAM relay.
3.3 The Actor Pushes Over That Connection¶
An Actor knows the connection bound to it. This is not a reply but a notification it sends on its own.
// 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) { }
A push without a bound connection ends with InvalidOperation
The same handler is also called by a mesh call, where no connection is bound. In that case, the
push ends with InvalidOperation at the call's terminal, and the failure is observed through each
language's asynchronous completion mechanism. The code above has already completed the rename
before pushing, so it discards only that failure.
4. The Attaching Side — a Client Outside the Mesh¶
The attaching process
The code in this section goes into the process that opened the connection in STREAM. It pairs with the section above.
It authenticates, then receives a notification. The second call is one-way and waits for no answer, yet a value arrives after it — that is the notification the Actor pushed.
using var boundNotice = connector.OnActorBound(
(actor, _) =>
{
Console.WriteLine($"actor bound: {actor.ActorId}");
return ValueTask.CompletedTask;
}
);
using var unboundNotice = connector.OnActorUnbound(
(actor, _) =>
{
Console.WriteLine($"actor unbound: {actor.ActorId}");
return ValueTask.CompletedTask;
}
);
// With one Actor bound, the connector can send without an Actor handle.
var authenticated1 = await connector
.Request(new Authenticate("p1"))
.Timeout(TimeSpan.FromSeconds(5))
.Async<Authenticated>();
Console.WriteLine($"bound player: {authenticated1.PlayerId}");
var singleChanged = new TaskCompletionSource<ZlinkStreamMessage<NicknameChanged>>(
TaskCreationOptions.RunContinuationsAsynchronously
);
using (
connector.On<NicknameChanged>(
(message, _) =>
{
singleChanged.SetResult(message);
return ValueTask.CompletedTask;
}
)
)
{
await connector.Send(new ChangeNickname("speedy")).Async();
var pushed = await singleChanged.Task;
Console.WriteLine($"pushed: {pushed.Payload.Nickname}, actor: {pushed.ActorId}");
}
// A second Actor on the same connection calls for explicit handles.
var authenticated2 = await connector
.Request(new Authenticate("p2"))
.Timeout(TimeSpan.FromSeconds(5))
.Async<Authenticated>();
Console.WriteLine($"bound player: {authenticated2.PlayerId}");
var player1 =
connector.Actor(authenticated1.PlayerId)
?? throw new InvalidOperationException("Player Actor p1 was not bound.");
var player2 =
connector.Actor(authenticated2.PlayerId)
?? throw new InvalidOperationException("Player Actor p2 was not bound.");
Console.WriteLine($"actor handle: {player1.ActorId}");
Console.WriteLine($"actor handle: {player2.ActorId}");
// Each callback receives only the push for its handle's Actor.
var changed1 = new TaskCompletionSource<ZlinkStreamMessage<NicknameChanged>>(
TaskCreationOptions.RunContinuationsAsynchronously
);
var changed2 = new TaskCompletionSource<ZlinkStreamMessage<NicknameChanged>>(
TaskCreationOptions.RunContinuationsAsynchronously
);
using var receive1 = player1.On<NicknameChanged>(
(message, _) =>
{
changed1.SetResult(message);
return ValueTask.CompletedTask;
}
);
using var receive2 = player2.On<NicknameChanged>(
(message, _) =>
{
changed2.SetResult(message);
return ValueTask.CompletedTask;
}
);
// Connector-level callbacks can distinguish the same pushes by ActorId.
using var receiveActorIds = connector.On<NicknameChanged>(
(message, _) =>
{
Console.WriteLine($"received actor id: {message.ActorId}");
return ValueTask.CompletedTask;
}
);
// Each handle sends to its own player over the same connection.
await player1.Send(new ChangeNickname("speedy-p1")).Async();
await player2.Send(new ChangeNickname("speedy-p2")).Async();
var pushed1 = await changed1.Task;
var pushed2 = await changed2.Task;
Console.WriteLine($"pushed: {pushed1.Payload.Nickname}, actor: {pushed1.ActorId}");
Console.WriteLine($"pushed: {pushed2.Payload.Nickname}, actor: {pushed2.ActorId}");
5. What You See When You Run It¶
With the tutorial Server running as the README's Run section specifies, start StreamClient with the command below: its bind request and received Actor notification appear on the StreamClient process's stdout, while session and Actor handler records appear on the Server process's stdout or in server.log.
dotnet run --project StreamClient/StreamClient.csproj
# connected: True
# round trip: 56ms
# bound player: p1
# pushed: speedy
pushed is the point. The client sent a rename and asked for no answer, and what came back is
a notification the player pushed on its own. In between, the packet passed the session,
reached the Actor, and the Actor sent back over the same connection.
6. After the Connection Drops — the Session Ends and the Actor Stays¶
The session ends and the Actor stays. A client that returns with the same id is bound to that Actor again.
The callback that tells the Actor about the drop, the rules for a binding moving to another connection, and what happens while the Actor moves to another node are covered by Session and Actor.
7. Related Documents¶
- Where the connection is accepted — STREAM
- The entity that gets bound — Actor
- Disconnect notices and relocation — Session and Actor
- A running version of this chapter's code — the tutorial README in the examples repository