Repository navigation
3. Login Process
Now that we have a client, we need to add a login endpoint to register players so they can look for games to join. This will be the last non-streaming endpoint we will be adding to the server.
In http4s servers, it is typical to separate groups of routes with
similar purposes into different service objects, then compose them
into a full server with combineK (symbolic operator <+>). You
already have a service in HealthCheck that you can use to check if
your server is listening for web traffic. According to convention you
now need to create a set of routes under a WebServer object.
This is also the first time you will be building an endpoint that
accepts data from the client and sends data back to the client. As
this data not part of the game domain that you just built and is used
only in http requests used to initialize game models, a new group of
domain models has been added to the common subproject.
When a user logs into the game server, they send a Nickname to
identify themselves as a PATCH request to /login. The Nickname
is modeled as an opaque string in ids.scala, similar to how GameId
and PlayerId were modeled as opaque types before. However, since it
is sent through http as a String, you need a way to encode and decode
the String nickname into the opaque Nickname type at runtime.
You will handle this with json encoding. http4s integrates well with the circe scala json library.
Circe json codecs are made of Encoder[A] and Decoder[A]
traits. The Encoder encodes objects of type A into json, and the
Decoder attempts to decode json into an Either[DecodingFailure, A].
Circe comes with several built-in Encoders and Decoders. These
exist in io.Circe.Encoder and io.Circe.Decoder, respectively.
The decoder for Strings is decodeString. However, that will only
decode strings. To make decoders of type A into a decoder of any
other type B while preserving DecodingFailures, circe Decoders
have a method, emap that takes a function A => Either[String, B]. Errors in the function can be reported by returning a Left in
the function containing an error message.
The encoder for Strings is encodeString.
Recall that opaque types can freely convert between the type they are modeling within the same file they are declared within.
3-1-login-endpoint-exercise-setup
|
|---|
Open
modules/common/shared/src/main/scala/scaladays/models/ids.scala. Using
the provided CirceEncoder and CirceDecoder import aliases,
complete the encoder and decoder for Nickname and save the file.
Scala 3 also added the ability to derive instances of typeclasses like
Encoder and Decoder. This ability is provided in
io.circe.generic.semiauto. As long as encoders and decoders exist in
implicit scope for all the types of a datatype, they can be derived
using deriveEncoder and deriveDecoder, respectively.
Now, open modules/common/shared/src/main/scala/scaladays/models/http.scala.
Derive the encoders and decoders for Login and LoginResponse. Once you're
done save the file.
Finally, you are ready to complete the login endpoint in
modules/server/src/main/scala/scaladays/server/WebServer.scala.
Http requests are modeled as pattern match extractors in http4s. The
match for /login is bound to the req value as a Request[F]. The
as[A] method will create an http entity decoder from the data in the
http request body, which in this case is json, from the json decoder
for the type (using the given/implicits provided in the
org.http4s.circe.* import) in the effect type F[_]. This decoded
type then needs to return a new LoginResponse. To do that, you will
need to use the PlayerId.apply[F[_]: Sync](): F[PlayerId] method
that was added in ids via the last commit. PlayerId() will create
a new random uuid in F[_]. Then you will need to pass the id to a
LoginResponse object in an Ok response, like you did for the /ping
healthcheck endpoint.
Because all of these things occur within F[_] and F[_] is an
Async, which extends Monad, you will need to use flatMap to
chain the incompleted transformations described above together.
Complete the transformations and save the file.
You can verify that you have completed the task correctly by running:
dockerComposeUpin the sbt console, opening your browser, opening the developer console in the browser, and entering:
fetch('http://localhost:28082/login', {
method: 'PATCH',
body: JSON.stringify("testName"),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
})
.then(res => res.json())
.then(console.log)You should get a successful json object with an uuid formatted string
id field in the developer console logs.
Congratulations! You have just completed your first fully encoded http4s endpoint.
A key element in every event-driven architecture is the message broker or message system. In this workshop, we are going to use Kafka. In the initial exercises, we saw how to add the needed services to our docker-compose config and run them.
Kafka functionality works around the concept of Topics and Partitions. A topic can be seen as a stream of records where each record is a key-value pair. Keys help in data partitioning and ordering, and Values hold the actual data.
The topics are split into multiple partitions for parallel processing and scalability and the partitions are further replicated across multiple Kafka brokers for fault tolerance and high availability. One unique characteristic of Kafka topics is that they maintain the order of records within a partition, ensuring strong ordering guarantees for the messages produced and consumed.
There are multiple ways of creating topics as part of our architecture. The most typical ones are:
- At the infrastructure level, fulfilled as part of Kafka cluster provisioning
- Automatically by Kafka
- As part of our application deployment
3-3-kafka-topic-and-codecs-exercise-setup
|
|---|
In this exercise, we're going to go with the latest one. When the application starts, it will check if the needed topic exists, and if not, we create them.
Open the file modules/server/src/main/scala/scaladays/config/KafkaSetup.scala
and complete the content of the createTopicUnless method. The topics param
contains the list of topics already created; use it to avoid trying to create an
existing topic.
Then in the bootTopics, using the kafkaAdminClientResource, get the list of
topics and call the implemented method passing the inputTopic
(it's a field inside of the KafkaConfiguration).
Opening the file modules/server/src/main/scala/scaladays/Server.scala to verify
that bootTopics is called when the server starts.
As you have seen, we create topics without specifying the data types. Events are serialized when they are written to a topic and deserialized when they are read. These operations turn binary data into the forms our application understand, and vice versa. Importantly, these operations are done solely by the Kafka clients.
Kafka brokers, on the other hand, are agnostic to the serialization format or
"type" of a stored event. All they see is a pair of raw bytes for event key and
event value (<byte[], byte[]> in Java notation) coming in when being written,
and going out when being read. Brokers thus have no idea what’s in the data
they serve—it’s a black box to them. Being this “dumb” is actually pretty smart,
because this design decision allows brokers to scale much better than traditional
messaging systems.
In this exercise, we're going to implement the serializers and deserializers for the messages written in the topic created in the previous exercise. There is no single "storage format" in Kafka. Common serialization formats used by Kafka clients include Apache Avro™ (with the Confluent Schema Registry), Protobuf, and JSON.
For this workshop, we are going to use Apache Avro™, with the Confluent Schema Registry we prepared in the docker section.
The input topic will receive messages of type EventId for the key and Event for the
value. To develop the codecs, we're going to use Vulcan.
Vulcan is a library for writing Avro codecs built on top of cats-effect.
Vulcan provides Avro schemas, encoders, and decoders between Scala types and types used by the official Apache Avro library. The aims are reduced boilerplate code and improved type safety, compared to when directly using the Apache Avro library. In particular, the following features are supported.
- Schemas, encoders, and decoders for many standard library types.
- Ability to easily create schemas, encoders, and decoders for custom types.
- Derivation of schemas, encoders, and decoders for case classes and sealed traits.
The first thing to do is to add the Vulcan dependency. Open the project/Dependencies.scala
and add the library to the server dependencies:
"com.github.fd4s" %% "vulcan" % Versions.vulcan,
"com.github.fd4s" %% "vulcan-generic" % Versions.vulcanEventId
The key for the input topic is EventId. As we saw in previous exercises, is an opaque type
for the type io.chrisdavenport.fuuid.FUUID. To implement the Vulcan code, we're going to use
String as the base type.
Open the file modules/server/src/main/scala/scaladays/kafka/codecs/Codecs.scala, and implement
the given uuidCodec: Codec[FUUID] using vulcan.Codec.string. This instance will be used by
the opaque types EventId, PlayerId, and GameId.
Event
This is a complex type, defined in the file modules/server/src/main/scala/scaladays/kafka/messages/Events.scala.
Open the definition and take a look.
As you can see, it's a sealed trait representing all the different actions.
- Login
- Register player
- Waiting for match
- Start game
- End game
- Turn game
- Reject event
The codec is defined in the file modules/server/src/main/scala/scaladays/kafka/codecs/Codecs.scala.
Open it, and, using the StartGame as the base, implement the rest of the Event subtype codecs.
Once finished, take a look at the Event codec itself, defined as a semigroup combination of the other
subtypes. For that, we have used the |+| operator.
Complete also the Position codec in the same way you did for the Event subclasses.
Enums
Enumerations are a largely used type for modeling a set of named identifiers. Vulcan produces a special
constructor for building enumeration codecs with Codec.enumeration. To finalize, implement the codec
for GameState using Codec.enumeration.
Now that you have serialization/deserialization (serde) completed, and the topics created, you can start communicating with the Kafka brokers.
To do that, we're going to use the kafka-streams-scala library, and the fs2-kafka library.
3-5-kafka-producer-exercise-setup
|
|---|
Open modules/server/src/main/scala/scaladays/kafka/Producer.scala.
To send events to Kakfa, you will use the Producer
created in this file. A kafka producer encodes events using an avro
serializable key and an avro serializable value to send the event
key-value pair to the kafka cluster identified by the bootstrap
servers in brokerAddress on the Kafka topic, identifying itself
using a clientId.
The mapped KafkaProducer resource produces an anonymous function
from K to V, which is assigned as the sendMessage implementation
of the Producer trait.
The Producer implementation is passed to EventStorage.impl when it is created.
Your task is to use Producer#sendMessage in EventStorage.impl#sendEvent to send events to Kafka.
Open modules/server/src/main/scala/scaladays/kafka/EventStorage.scala.
You should see an algebra interface with a login(Nickname): F[EventId] method.
If you look at the implementation impl, you will
notice that all the public methods delegate to an unimplemented private sendEvent method.
TTTEventThe value for the input topic is
TTTEvent. This is a complex type, defined in the filemodules/server/src/main/scala/scaladays/kafka/messages/Events.scala. Open the definition and take a look.As you can see, it's a case class with two fields, an
Instantfor storing when the event was created and anEvent, the sealed trait representing all the different actions.
Recall that before an event can be sent to Kafka using Producer, the
event must have both a key and a value. You can use the EventId.apply
to generate a new key as an effect.
Finally, to complete the exercise, open the file modules/server/src/main/scala/scaladays/server/TTTServer.scala.
This is an algebra that will be used by our server to perform different operations.
Since our method EventStorage#login(Nickname) is now complete, complete the TTTServer#login(Nickname) implementation
to call EventStorage#login(Nickname) before returning the generated PlayerId.
If we take a look at the UML sequence diagram of the login process and abstract from the server part that is already completed, then we can see that we still have to implement it at different levels.
3-7-client-login-exercise-setup
|
|---|
Let's break this exercise into five small tasks to help us understand how Tyrian works.
But first, we will analyze the possible states that the login process entails to evaluate how it affects the model, the events that allow us to transit between states, and the effects that are triggered (such as making an HTTP request to the server).
| State | What is happening? |
|---|---|
| Pre-login state | The user has not clicked the login button, nor is the server aware of who this player is. |
| Waiting state | The user has already pressed the login button, and the login request has been carried out, but the server has not responded yet |
| Confirmed as success | The server has responded successfully with a new PlayerId. |
| Confirmed as failure | The server has responded with some error. We don't have any PlayerId. |
So far, the Model only contains the nickname: NickName, but this is not enough if we want to be able to represent
all the new states. We propose to add also the property player: Player and errors: List[ClientError].
That way the model would evolve like:
| State | Nickname | Player | Errors |
|---|---|---|---|
| Pre-login state | Non empty | Player.empty |
Empty |
| Waiting state | Non empty | Player.waiting |
Empty |
| Confirmed as success | Non empty | Player.registered |
Empty |
| Confirmed as failure | Non empty | Player.empty |
Non empty |
- Edit the file
modules/client/src/main/scala/scaladays/models/Model.scalato:- Describe these changes in the case class
Model - Update the init
Model.
- Describe these changes in the case class
So far, the only possible event the client is delivering is UpdateNickname. However we have to think about Msg as the
events that will trigger a new state, that is to say, a Model evolution.
As you could already realized, the UpdateNickname event already bring us to the pre-login state, but we need to create
the rest of the Msg to jump to other states. We propose:
| State | Triggered by the Msg: |
|---|---|
| Pre-login state | UpdateNickname(nickname: Nickname) |
| Waiting state | LoginRequest(nickname: Nickname) |
| Confirmed as success | LoginSuccess(playerId: PlayerId) |
| Confirmed as failure | LoginError(error: ClientError) |
- Edit the file
modules/client/src/main/scala/scaladays/models/Messages.scalato add these events.
As we already mentioned during the introduction of Tyrian, the Update method represented the state map, that is, how the
Model changes according to the new events received.
Well, now we have new events to which we must react with model evolutions, as follows:
| Msg: | Model | Cmd |
|---|---|---|
LoginRequest(nickname: Nickname) |
player = Player.Waiting |
client.getLogin(nickname) |
LoginSuccess(playerId: PlayerId) |
player = Player.Registered(playerId) |
Cmd.None |
LoginError(error: ClientError) |
errors = List(error) |
Cmd.None |
- Edit the file
modules/client/src/main/scala/scaladays/main/Update.scalato react to these events as described above.
ℹ️ INFO: When the user emits the LoginRequest event, the app performs the actual HTTP request to the server, so the Cmd client.getLogin(nickname) will be implemented in the part 5 |
|---|
As you might expect, we now need to define a view for each possible state the app can adopt. Here are some ideas:
Pre-login state:

Waiting state

Confirmed as success

Confirmed as failure

- In the file
modules/client/src/main/scala/scaladays/views/MainView.scalaimplement the new views as shown above. - In the file
modules/client/src/main/scala/scaladays/Main.scalaimplement thedef view(model: ModelIO): Html[Msg]to show the new views accordingly.
ℹ️ INFO: The login button has to submit the LoginRequest event. For example like this: button(tpe := "button", cls := "btn btn-primary", onClick(Msg.LoginRequest(nickname)))("Login")
|
|---|
We want to complete the Login process, so we still have to perform an HTTP request to log the user in. So this is the last part of this exercise.
- Edit the file
modules/client/src/main/scala/scaladays/clients/ScalaDaysClient.scalato implement the functiondef getLogin(nickname: Nickname): Cmd[F, Msg]
Tip 1: The
Cmd[F, Msg]typeIf you have an effect
fthat returnsF[Msg], you can convert it into aCmd[F, Msg]byCmd.Run(f)(identity)
Tip 2: Empty nickname
If the nickname is empty, we should return something like
Msg.LoginError(InvalidNickname), before perfirming the HTTP request
Tip 3: Request/Response types
The server expects a
Loginentity in the body as JSON, and returns aLoginResponse. Both model are in the shared project atscaladays.models.http
Once finished all the previous steps, we need to make a minor change in our server to allow non-origin domain calls.
CORS Policy
Cross-origin resource sharing (CORS) is a standard mechanism that allows JavaScript XMLHttpRequest (XHR) calls executed in a web page to interact with resources from non-origin domains. CORS is a commonly implemented solution to the same-origin policy that is enforced by all browsers.
For example, if you make an XHR call to the Twitter API from JavaScript code executing in your browser, the call will fail. This is because the domain serving the page to your browser is not the same as the domain serving the Twitter API. CORS provides a solution to this problem by allowing servers to opt-in if they wish to provide cross-origin resource sharing.
Fortunately, http4s comes with built-in support for CORS policy. Open the file modules/server/src/main/scala/scaladays/Server.scala
and wrap the routes with CORS.policy.withAllowOriginAll.withAllowCredentials(false).apply(_)
You can also See the event in kafka-magic:
To monitor kafka, kafka-magic has been added to the docker-compose. You can use it to view topics and messages on the kafka brokers.
First, start the app with dockerComposeUp. Then:
- Open Kafka Magic.
- Click Register New.
- Enter
Scaladays Workshopin theCluster Nameinput. - Enter
kakfa-1:9092,kafka-2:9092,kafka-1:9092in theBootstrap Serversinput. - Click
Schema Registry. - Enter
http://schema-registry:8081in theSchema Registry URLinput. - Toggle
Auto-register schemasto true. - Click
Verify. An alert will show success. Close it. - Click Register Connection. Your cluster is registered.
To view topics after registering:
- Open Kafka Magic.
- Click on
Scaladays Workshop. - Under the
Cluster Explorer, click> Scaladays Workshop. - Click
> Topics. - Click the topic you want (
ttt.game.topic|ttt.input.topic|ttt.player.topic) - Click
Run Search. The messages will appear as json underResults. Click the arrow to expand them.