Skip to content

Session and Actor

Guide Home | Previous: STREAM | Next: Location

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.

↗ View larger

▶ 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.

data class Authenticate(val playerId: String)

data class Authenticated(val playerId: String)

// Pushed by the player to its own connection, with no request to answer.
data class NicknameChanged(val nickname: String)

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.

// Ties this connection to one player. After this, packets without a session
// handler reach that player, and the player can push to this connection.
class AuthenticateHandler(players: ZLinkActorManager) :
    ZLinkSuspendingTypedSessionPacketHandler<ZLinkSessionContext, Authenticate> {

    private val players = players.kotlin()

    override fun packetName(): String = "Authenticate"

    override fun messageType(): Class<Authenticate> = Authenticate::class.java

    override suspend fun handle(
        context: ZLinkSessionContext,
        dispatch: ZLinkSessionDispatchContext,
        message: Authenticate,
    ) {
        // A returning client finds its existing player rather than a new one.
        val result =
            players
                .getOrCreate(message.playerId, "player")
                .inMesh("game")
                .request(CreatePlayer(message.playerId))
                .timeout(Duration.ofSeconds(10))
                .await()

        val bound = context.actors().bindOrGetActor(resolve(result))

        context.client().kotlin().reply(Authenticated(bound.actorId())).await()
    }

    private fun resolve(result: ZLinkActorCreateResult): ActorRef =
        when (result) {
            is ZLinkActorCreateResult.Existing -> result.actor()
            is ZLinkActorCreateResult.Created -> result.actor()
            else -> throw IllegalStateException("Player creation was rejected.")
        }
}

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.
val player =
    dispatch.actor()
        ?: run {
            val bound = context.actors().bound()
            when (bound.size) {
                1 -> bound[0]
                0 -> error("Authenticate an Actor before sending player packets.")
                else -> error("Select an Actor handle when more than one Actor is bound.")
            }
        }

player.kotlin().relay(dispatch, payload).await()

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 {
    actor.context().boundSession().kotlin().send(NicknameChanged(actor.nickname)).await()
} catch (error: ZLinkFrameworkException) {
    if (error.kind() != ZLinkFrameworkErrorKind.INVALID_OPERATION) {
        throw error
    }
}

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.

val boundNotice =
    launch(start = CoroutineStart.UNDISPATCHED) {
        connector.actorBound().collect { actor -> println("actor bound: ${actor.actorId}") }
    }
val unboundNotice =
    launch(start = CoroutineStart.UNDISPATCHED) {
        connector.actorUnbound().collect { actor -> println("actor unbound: ${actor.actorId}") }
    }
// With one Actor bound, the connector can send without an Actor handle.
val authenticatedP1 =
    connector.request<Authenticated>(Authenticate("p1")).timeout(Duration.ofSeconds(5)).await()

println("bound player: ${authenticatedP1.playerId}")

val singleChanged = CompletableFuture<ZLinkStreamMessage<NicknameChanged>>()
val singleReceive =
    connector.on<NicknameChanged> { message ->
        singleChanged.complete(message)
        CompletableFuture.completedFuture(null)
    }
connector.send(ChangeNickname("speedy")).await()
val pushed = singleChanged.await()
println("pushed: ${pushed.payload().nickname}, actor: ${pushed.actorId()}")
singleReceive.close()

// A second Actor on the same connection calls for explicit handles.
val authenticatedP2 =
    connector.request<Authenticated>(Authenticate("p2")).timeout(Duration.ofSeconds(5)).await()
println("bound player: ${authenticatedP2.playerId}")

val playerP1 = requireNotNull(connector.actor(authenticatedP1.playerId))
val playerP2 = requireNotNull(connector.actor(authenticatedP2.playerId))
println("actor handle: ${playerP1.actorId}")
println("actor handle: ${playerP2.actorId}")

// Each callback receives only the push for its handle's Actor.
val changedP1 = CompletableFuture<ZLinkStreamMessage<NicknameChanged>>()
val changedP2 = CompletableFuture<ZLinkStreamMessage<NicknameChanged>>()
val receiveP1 =
    playerP1.on<NicknameChanged> { message ->
        changedP1.complete(message)
        CompletableFuture.completedFuture(null)
    }
val receiveP2 =
    playerP2.on<NicknameChanged> { message ->
        changedP2.complete(message)
        CompletableFuture.completedFuture(null)
    }

// Connector-level callbacks can distinguish the same pushes by ActorId.
val receiveActorIds =
    connector.on<NicknameChanged> { message ->
        println("received actor id: ${message.actorId()}")
        CompletableFuture.completedFuture(null)
    }

// Each handle sends to its own player over the same connection.
playerP1.send(ChangeNickname("speedy-p1")).await()
playerP2.send(ChangeNickname("speedy-p2")).await()

val pushedP1 = changedP1.await()
val pushedP2 = changedP2.await()
println("pushed: ${pushedP1.payload().nickname}, actor: ${pushedP1.actorId()}")
println("pushed: ${pushedP2.payload().nickname}, actor: ${pushedP2.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.